blob: 18e3dbc839990b270ab543ffecf00658fccbe7f4 [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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000030#include <memory>
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.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000168 bool HandleTopLevelDecl(DeclGroupRef D) override {
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
Craig Topperfb6b25b2014-03-15 04:29:04 +0000196 void HandleTranslationUnit(ASTContext &C) override;
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);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000331
332 virtual void Initialize(ASTContext &context) override = 0;
333
Fariborz Jahanian83077422011-12-08 18:25:15 +0000334 // 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() {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000524 virtual void Initialize(ASTContext &context) override;
525
Fariborz Jahanian83077422011-12-08 18:25:15 +0000526 // 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);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000534 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
535 StringRef prefix, StringRef ClassName,
536 std::string &Result) override;
537 void RewriteObjCProtocolListMetaData(
538 const ObjCList<ObjCProtocolDecl> &Prots,
539 StringRef prefix, StringRef ClassName, std::string &Result) override;
540 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
541 std::string &Result) override;
542 void RewriteMetaDataIntoBuffer(std::string &Result) override;
543 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
544 std::string &Result) override;
545
Fariborz Jahanian83077422011-12-08 18:25:15 +0000546 // Rewriting ivar
Craig Topperfb6b25b2014-03-15 04:29:04 +0000547 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
548 std::string &Result) override;
549 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahanian83077422011-12-08 18:25:15 +0000550 };
Chris Lattnere99c8322007-10-11 00:43:27 +0000551}
552
Mike Stump11289f42009-09-09 15:08:12 +0000553void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
554 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000555 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000556 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000557 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
558 E = fproto->param_type_end();
559 I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000560 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000561 // All the args are checked/rewritten. Don't call twice!
562 RewriteBlockPointerDecl(D);
563 break;
564 }
565 }
566}
567
568void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000569 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000570 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000571 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000572}
573
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000574static bool IsHeaderFile(const std::string &Filename) {
575 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000576
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000577 if (DotPos == std::string::npos) {
578 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000579 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000580 }
Mike Stump11289f42009-09-09 15:08:12 +0000581
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000582 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
583 // C header: .h
584 // C++ header: .hh or .H;
585 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000586}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000587
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000588RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000589 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000590 bool silenceMacroWarn)
591 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
592 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000593 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000594 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000595 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000596 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
597 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000598 "rewriter doesn't support user-specified control flow semantics "
599 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000600}
601
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000602ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000603 raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000604 DiagnosticsEngine &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000605 const LangOptions &LOpts,
606 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000607 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000608}
Chris Lattnere99c8322007-10-11 00:43:27 +0000609
Fariborz Jahanian83077422011-12-08 18:25:15 +0000610void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000611 Context = &context;
612 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000613 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000614 MsgSendFunctionDecl = 0;
615 MsgSendSuperFunctionDecl = 0;
616 MsgSendStretFunctionDecl = 0;
617 MsgSendSuperStretFunctionDecl = 0;
618 MsgSendFpretFunctionDecl = 0;
619 GetClassFunctionDecl = 0;
620 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000621 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000622 SelGetUidFunctionDecl = 0;
623 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000624 ConstantStringClassReference = 0;
625 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000626 CurMethodDef = 0;
627 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000628 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000629 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000630 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000631 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000632 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000633 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000634 SuperConstructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000635 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000636 PropParentMap = 0;
637 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000638 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000639 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000640
Chris Lattner187f6262008-01-31 19:38:44 +0000641 // Get the ID and start/end of the main file.
642 MainFileID = SM->getMainFileID();
643 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
644 MainFileStart = MainBuf->getBufferStart();
645 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000646
David Blaikiebbafb8a2012-03-11 07:00:24 +0000647 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000648}
649
Chris Lattner3c799d72007-10-24 17:06:59 +0000650//===----------------------------------------------------------------------===//
651// Top Level Driver Code
652//===----------------------------------------------------------------------===//
653
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000654void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000655 if (Diags.hasErrorOccurred())
656 return;
657
Chris Lattner0bd1c972007-10-16 21:07:07 +0000658 // Two cases: either the decl could be in the main file, or it could be in a
659 // #included file. If the former, rewrite it now. If the later, check to see
660 // if we rewrote the #include/#import.
661 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000662 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattner0bd1c972007-10-16 21:07:07 +0000664 // If this is for a builtin, ignore it.
665 if (Loc.isInvalid()) return;
666
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000667 // Look for built-in declarations that we need to refer during the rewrite.
668 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000669 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000670 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000671 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000672 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000673 ConstantStringClassReference = FVD;
674 return;
675 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000676 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
677 if (ID->isThisDeclarationADefinition())
678 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000679 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000680 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000681 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000682 if (PD->isThisDeclarationADefinition())
683 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000684 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
685 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000686 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
687 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000688 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000689 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
690 if (!IFace->isThisDeclarationADefinition()) {
691 SmallVector<Decl *, 8> DG;
692 SourceLocation StartLoc = IFace->getLocStart();
693 do {
694 if (isa<ObjCInterfaceDecl>(*DI) &&
695 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
696 StartLoc == (*DI)->getLocStart())
697 DG.push_back(*DI);
698 else
699 break;
700
Douglas Gregordc9166c2011-12-15 20:29:51 +0000701 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000702 } while (DI != DIEnd);
703 RewriteForwardClassDecl(DG);
704 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000705 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000706 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000707
708 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
709 if (!Proto->isThisDeclarationADefinition()) {
710 SmallVector<Decl *, 8> DG;
711 SourceLocation StartLoc = Proto->getLocStart();
712 do {
713 if (isa<ObjCProtocolDecl>(*DI) &&
714 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
715 StartLoc == (*DI)->getLocStart())
716 DG.push_back(*DI);
717 else
718 break;
719
720 ++DI;
721 } while (DI != DIEnd);
722 RewriteForwardProtocolDecl(DG);
723 continue;
724 }
725 }
726
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000727 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000728 ++DI;
729 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000730 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000732 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000733 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000734}
735
Chris Lattner3c799d72007-10-24 17:06:59 +0000736//===----------------------------------------------------------------------===//
737// Syntactic (non-AST) Rewriting Code
738//===----------------------------------------------------------------------===//
739
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000740void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000741 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000742 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000743 const char *MainBufStart = MainBuf.begin();
744 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000745 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000746
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000747 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000748 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
749 if (*BufPtr == '#') {
750 if (++BufPtr == MainBufEnd)
751 return;
752 while (*BufPtr == ' ' || *BufPtr == '\t')
753 if (++BufPtr == MainBufEnd)
754 return;
755 if (!strncmp(BufPtr, "import", ImportLen)) {
756 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000757 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000758 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000759 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000760 BufPtr += ImportLen;
761 }
762 }
763 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000764}
765
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000766static std::string getIvarAccessString(ObjCIvarDecl *OID) {
767 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000768 std::string S;
769 S = "((struct ";
770 S += ClassDecl->getIdentifier()->getName();
771 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000772 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000773 return S;
774}
775
Steve Naroffc038b3a2008-12-02 17:36:43 +0000776void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
777 ObjCImplementationDecl *IMD,
778 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000779 static bool objcGetPropertyDefined = false;
780 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000781 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000782 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000783 const char *startBuf = SM->getCharacterData(startLoc);
784 assert((*startBuf == '@') && "bogus @synthesize location");
785 const char *semiBuf = strchr(startBuf, ';');
786 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000787 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000788 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000789
790 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
791 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000792
Steve Naroff9af94912008-12-02 15:48:25 +0000793 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000794 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000795 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000796
Steve Naroff003d00e2008-12-02 16:05:55 +0000797 if (!OID)
798 return;
Bill Wendling44426052012-12-20 19:22:21 +0000799 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000800 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000801 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
802 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000803 ObjCPropertyDecl::OBJC_PR_copy));
804 std::string Getr;
805 if (GenGetProperty && !objcGetPropertyDefined) {
806 objcGetPropertyDefined = true;
807 // FIXME. Is this attribute correct in all cases?
808 Getr = "\nextern \"C\" __declspec(dllimport) "
809 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000810 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000811 RewriteObjCMethodDecl(OID->getContainingInterface(),
812 PD->getGetterMethodDecl(), Getr);
813 Getr += "{ ";
814 // Synthesize an explicit cast to gain access to the ivar.
815 // See objc-act.c:objc_synthesize_new_getter() for details.
816 if (GenGetProperty) {
817 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
818 Getr += "typedef ";
819 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000820 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000821 FPRetType);
822 Getr += " _TYPE";
823 if (FPRetType) {
824 Getr += ")"; // close the precedence "scope" for "*".
825
826 // Now, emit the argument types (if any).
827 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
828 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000829 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000830 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000831 std::string ParamStr =
832 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000833 Getr += ParamStr;
834 }
835 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000836 if (FT->getNumParams())
837 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000838 Getr += "...";
839 }
840 Getr += ")";
841 } else
842 Getr += "()";
843 }
844 Getr += ";\n";
845 Getr += "return (_TYPE)";
846 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000847 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000848 Getr += ", 1)";
849 }
850 else
851 Getr += "return " + getIvarAccessString(OID);
852 Getr += "; }";
853 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000854 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000855
856 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000857 return;
Mike Stump11289f42009-09-09 15:08:12 +0000858
Steve Naroff9af94912008-12-02 15:48:25 +0000859 // Generate the 'setter' function.
860 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000861 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000862 ObjCPropertyDecl::OBJC_PR_copy);
863 if (GenSetProperty && !objcSetPropertyDefined) {
864 objcSetPropertyDefined = true;
865 // FIXME. Is this attribute correct in all cases?
866 Setr = "\nextern \"C\" __declspec(dllimport) "
867 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
868 }
869
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000870 RewriteObjCMethodDecl(OID->getContainingInterface(),
871 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000872 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000873 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000874 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000875 if (GenSetProperty) {
876 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000877 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000878 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000879 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000880 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000881 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000882 Setr += "0, ";
883 else
884 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000885 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000886 Setr += "1)";
887 else
888 Setr += "0)";
889 }
890 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000891 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000892 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000893 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000894 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000895 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000896}
Chris Lattner16a0de42007-10-11 18:38:32 +0000897
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000898static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
899 std::string &typedefString) {
900 typedefString += "#ifndef _REWRITER_typedef_";
901 typedefString += ForwardDecl->getNameAsString();
902 typedefString += "\n";
903 typedefString += "#define _REWRITER_typedef_";
904 typedefString += ForwardDecl->getNameAsString();
905 typedefString += "\n";
906 typedefString += "typedef struct objc_object ";
907 typedefString += ForwardDecl->getNameAsString();
908 typedefString += ";\n#endif\n";
909}
910
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000911void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000912 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000913 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000914 const char *startBuf = SM->getCharacterData(startLoc);
915 const char *semiPtr = strchr(startBuf, ';');
916 // Replace the @class with typedefs corresponding to the classes.
917 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
918}
919
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000920void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000921 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000922 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000923 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000924 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000925 // Translate to typedef's that forward reference structs with the same name
926 // as the class. As a convenience, we include the original declaration
927 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000928 typedefString += "// @class ";
929 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000930 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000931 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000932 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000933 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000934 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000935 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000936}
Mike Stump11289f42009-09-09 15:08:12 +0000937
Craig Topper5603df42013-07-05 19:34:19 +0000938void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000939 std::string typedefString;
940 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000941 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000942 if (i == 0) {
943 typedefString += "// @class ";
944 typedefString += ForwardDecl->getNameAsString();
945 typedefString += ";\n";
946 }
947 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
948 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000949 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000950}
951
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000952void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000953 // When method is a synthesized one, such as a getter/setter there is
954 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000955 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000956 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000957 SourceLocation LocStart = Method->getLocStart();
958 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chandler Carruthd48db212011-07-25 21:09:52 +0000960 if (SM->getExpansionLineNumber(LocEnd) >
961 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000962 InsertText(LocStart, "#if 0\n");
963 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000964 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000965 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000966 }
967}
968
Mike Stump11289f42009-09-09 15:08:12 +0000969void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000970 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000972 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000973 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000974}
975
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000976void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000977 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Steve Naroff5448cf62007-10-30 13:30:57 +0000979 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000980 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000981
Aaron Ballmand174edf2014-03-13 19:11:50 +0000982 for (auto *I : CatDecl->properties())
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000983 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000984 for (auto *I : CatDecl->instance_methods())
985 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000986 for (auto *I : CatDecl->class_methods())
987 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000988
Steve Naroff5448cf62007-10-30 13:30:57 +0000989 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000990 ReplaceText(CatDecl->getAtEndRange().getBegin(),
991 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000992}
993
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000994void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000995 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000996 assert(PDecl->isThisDeclarationADefinition());
997
Steve Narofff921385f2007-10-30 16:42:30 +0000998 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000999 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001000
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001001 for (auto *I : PDecl->instance_methods())
1002 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001003 for (auto *I : PDecl->class_methods())
1004 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001005 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001006 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001007
Steve Narofff921385f2007-10-30 16:42:30 +00001008 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001009 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001010 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001011
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001012 // Must comment out @optional/@required
1013 const char *startBuf = SM->getCharacterData(LocStart);
1014 const char *endBuf = SM->getCharacterData(LocEnd);
1015 for (const char *p = startBuf; p < endBuf; p++) {
1016 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001017 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001018 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001019
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001020 }
1021 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001022 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001023 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001024
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001025 }
1026 }
Steve Narofff921385f2007-10-30 16:42:30 +00001027}
1028
Douglas Gregorf6102672012-01-01 21:23:57 +00001029void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1030 SourceLocation LocStart = (*D.begin())->getLocStart();
1031 if (LocStart.isInvalid())
1032 llvm_unreachable("Invalid SourceLocation");
1033 // FIXME: handle forward protocol that are declared across multiple lines.
1034 ReplaceText(LocStart, 0, "// ");
1035}
1036
1037void
Craig Topper5603df42013-07-05 19:34:19 +00001038RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001039 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001040 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001041 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001042 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001043 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001044}
1045
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001046void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1047 const FunctionType *&FPRetType) {
1048 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001049 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001050 else if (T->isFunctionPointerType() ||
1051 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001052 // needs special handling, since pointer-to-functions have special
1053 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001054 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001055 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001056 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001057 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001058 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001059 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001060 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001061 ResultStr +=
1062 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001063 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001064 }
1065 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001066 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001067}
1068
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001069void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1070 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001071 std::string &ResultStr) {
1072 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1073 const FunctionType *FPRetType = 0;
1074 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001075 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001076 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001077
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001079 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregorffca3a22009-01-09 17:18:27 +00001081 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001082 NameStr += "_I_";
1083 else
1084 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001085
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001086 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001087 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001088
1089 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001090 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001091 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001092 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 }
Mike Stump11289f42009-09-09 15:08:12 +00001094 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001095 {
1096 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 int len = selString.size();
1098 for (int i = 0; i < len; i++)
1099 if (selString[i] == ':')
1100 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001101 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001102 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001103 // Remember this name for metadata emission
1104 MethodInternalNames[OMD] = NameStr;
1105 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001107 // Rewrite arguments
1108 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001109
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001110 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001111 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001112 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001113 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001114 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001115 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001116 ResultStr += "struct ";
1117 }
1118 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001119 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001120 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001121 }
1122 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001123 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001124 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001125
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001126 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001127 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001128 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001129
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001130 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001131 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001132 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001133 if (PDecl->getType()->isObjCQualifiedIdType()) {
1134 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001135 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001136 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001137 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001138 QualType QT = PDecl->getType();
1139 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001140 (void)convertBlockPointerToFunctionPointer(QT);
1141 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001142 ResultStr += Name;
1143 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001144 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001145 if (OMD->isVariadic())
1146 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001147 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001148
Steve Naroffb067bbd2008-07-16 14:40:40 +00001149 if (FPRetType) {
1150 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001151
Steve Naroffb067bbd2008-07-16 14:40:40 +00001152 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001153 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001154 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001155 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001156 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001157 std::string ParamStr =
1158 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001159 ResultStr += ParamStr;
1160 }
1161 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001162 if (FT->getNumParams())
1163 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001164 ResultStr += "...";
1165 }
1166 ResultStr += ")";
1167 } else {
1168 ResultStr += "()";
1169 }
1170 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001172void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001173 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1174 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001175
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001176 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001177
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001178 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001179 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001180 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001181 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001182 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001183
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001184 const char *startBuf = SM->getCharacterData(LocStart);
1185 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001186 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001189 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001190 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001191 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001192 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001193 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001194
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001195 const char *startBuf = SM->getCharacterData(LocStart);
1196 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001197 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001198 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001199 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1200 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001201
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001202 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001203}
1204
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001205void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001206 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001207 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001208 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001209 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001210 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001211 ResultStr += "\n";
1212 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001213 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001214 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001215 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001216 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001217 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001218 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001219 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001220 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001221 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Aaron Ballmand174edf2014-03-13 19:11:50 +00001223 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001224 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001225 for (auto *I : ClassDecl->instance_methods())
1226 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001227 for (auto *I : ClassDecl->class_methods())
1228 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +00001229
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001230 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001231 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1232 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001233}
1234
John McCallfe96e0b2011-11-06 09:01:30 +00001235Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1236 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001237
John McCallfe96e0b2011-11-06 09:01:30 +00001238 // We just magically know some things about the structure of this
1239 // expression.
1240 ObjCMessageExpr *OldMsg =
1241 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1242 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001243
John McCallfe96e0b2011-11-06 09:01:30 +00001244 // Because the rewriter doesn't allow us to rewrite rewritten code,
1245 // we need to suppress rewriting the sub-statements.
1246 Expr *Base, *RHS;
1247 {
1248 DisableReplaceStmtScope S(*this);
1249
1250 // Rebuild the base expression if we have one.
1251 Base = 0;
1252 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1253 Base = OldMsg->getInstanceReceiver();
1254 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1255 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1256 }
1257
1258 // Rebuild the RHS.
1259 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1260 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1261 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1262 }
1263
1264 // TODO: avoid this copy.
1265 SmallVector<SourceLocation, 1> SelLocs;
1266 OldMsg->getSelectorLocs(SelLocs);
1267
Chad Rosier598f3d22012-01-06 20:05:14 +00001268 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001269 switch (OldMsg->getReceiverKind()) {
1270 case ObjCMessageExpr::Class:
1271 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1272 OldMsg->getValueKind(),
1273 OldMsg->getLeftLoc(),
1274 OldMsg->getClassReceiverTypeInfo(),
1275 OldMsg->getSelector(),
1276 SelLocs,
1277 OldMsg->getMethodDecl(),
1278 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001279 OldMsg->getRightLoc(),
1280 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001281 break;
1282
1283 case ObjCMessageExpr::Instance:
1284 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1285 OldMsg->getValueKind(),
1286 OldMsg->getLeftLoc(),
1287 Base,
1288 OldMsg->getSelector(),
1289 SelLocs,
1290 OldMsg->getMethodDecl(),
1291 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001292 OldMsg->getRightLoc(),
1293 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001294 break;
1295
1296 case ObjCMessageExpr::SuperClass:
1297 case ObjCMessageExpr::SuperInstance:
1298 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1299 OldMsg->getValueKind(),
1300 OldMsg->getLeftLoc(),
1301 OldMsg->getSuperLoc(),
1302 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1303 OldMsg->getSuperType(),
1304 OldMsg->getSelector(),
1305 SelLocs,
1306 OldMsg->getMethodDecl(),
1307 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001308 OldMsg->getRightLoc(),
1309 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001310 break;
1311 }
1312
1313 Stmt *Replacement = SynthMessageExpr(NewMsg);
1314 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1315 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001316}
1317
John McCallfe96e0b2011-11-06 09:01:30 +00001318Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1319 SourceRange OldRange = PseudoOp->getSourceRange();
1320
1321 // We just magically know some things about the structure of this
1322 // expression.
1323 ObjCMessageExpr *OldMsg =
1324 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1325
1326 // Because the rewriter doesn't allow us to rewrite rewritten code,
1327 // we need to suppress rewriting the sub-statements.
1328 Expr *Base = 0;
1329 {
1330 DisableReplaceStmtScope S(*this);
1331
1332 // Rebuild the base expression if we have one.
1333 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1334 Base = OldMsg->getInstanceReceiver();
1335 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1336 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001337 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001338 }
Steve Narofff326f402008-12-03 00:56:33 +00001339
John McCallfe96e0b2011-11-06 09:01:30 +00001340 // Intentionally empty.
1341 SmallVector<SourceLocation, 1> SelLocs;
1342 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001343
Chad Rosier598f3d22012-01-06 20:05:14 +00001344 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001345 switch (OldMsg->getReceiverKind()) {
1346 case ObjCMessageExpr::Class:
1347 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1348 OldMsg->getValueKind(),
1349 OldMsg->getLeftLoc(),
1350 OldMsg->getClassReceiverTypeInfo(),
1351 OldMsg->getSelector(),
1352 SelLocs,
1353 OldMsg->getMethodDecl(),
1354 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001355 OldMsg->getRightLoc(),
1356 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001357 break;
1358
1359 case ObjCMessageExpr::Instance:
1360 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1361 OldMsg->getValueKind(),
1362 OldMsg->getLeftLoc(),
1363 Base,
1364 OldMsg->getSelector(),
1365 SelLocs,
1366 OldMsg->getMethodDecl(),
1367 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001368 OldMsg->getRightLoc(),
1369 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001370 break;
1371
1372 case ObjCMessageExpr::SuperClass:
1373 case ObjCMessageExpr::SuperInstance:
1374 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1375 OldMsg->getValueKind(),
1376 OldMsg->getLeftLoc(),
1377 OldMsg->getSuperLoc(),
1378 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1379 OldMsg->getSuperType(),
1380 OldMsg->getSelector(),
1381 SelLocs,
1382 OldMsg->getMethodDecl(),
1383 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001384 OldMsg->getRightLoc(),
1385 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001386 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001387 }
John McCallfe96e0b2011-11-06 09:01:30 +00001388
1389 Stmt *Replacement = SynthMessageExpr(NewMsg);
1390 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1391 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001392}
1393
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394/// SynthCountByEnumWithState - To print:
1395/// ((unsigned int (*)
1396/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001397/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001398/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001399/// "countByEnumeratingWithState:objects:count:"),
1400/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001401/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001403void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001404 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1405 "id *, unsigned int))(void *)objc_msgSend)";
1406 buf += "\n\t\t";
1407 buf += "((id)l_collection,\n\t\t";
1408 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1409 buf += "\n\t\t";
1410 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001411 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001412}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001413
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001414/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1415/// statement to exit to its outer synthesized loop.
1416///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001417Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001418 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1419 return S;
1420 // replace break with goto __break_label
1421 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001423 SourceLocation startLoc = S->getLocStart();
1424 buf = "goto __break_label_";
1425 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001426 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001427
1428 return 0;
1429}
1430
1431/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1432/// statement to continue with its inner synthesized loop.
1433///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001434Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001435 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1436 return S;
1437 // replace continue with goto __continue_label
1438 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001439
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001440 SourceLocation startLoc = S->getLocStart();
1441 buf = "goto __continue_label_";
1442 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001443 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001445 return 0;
1446}
1447
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001448/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001449/// It rewrites:
1450/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001451
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001452/// Into:
1453/// {
Mike Stump11289f42009-09-09 15:08:12 +00001454/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001455/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001456/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001457/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001458/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001459/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001460/// if (limit) {
1461/// unsigned long startMutations = *enumState.mutationsPtr;
1462/// do {
1463/// unsigned long counter = 0;
1464/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001465/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001466/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001467/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001468/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001469/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001470/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001471/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001472/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001473/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001474/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001475/// }
1476/// else
1477/// elem = nil;
1478/// }
1479///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001480Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001481 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001482 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001483 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001485 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001486 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001487
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001488 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001489 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001490 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001491 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001492 std::string buf;
1493 buf = "\n{\n\t";
1494 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1495 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001496 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001497 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001498 if (ElementType->isObjCQualifiedIdType() ||
1499 ElementType->isObjCQualifiedInterfaceType())
1500 // Simply use 'id' for all qualified types.
1501 elementTypeAsString = "id";
1502 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001503 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001504 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001506 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 buf += elementName;
1508 buf += ";\n\t";
1509 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001510 else {
1511 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001512 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001513 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1514 if (VD->getType()->isObjCQualifiedIdType() ||
1515 VD->getType()->isObjCQualifiedInterfaceType())
1516 // Simply use 'id' for all qualified types.
1517 elementTypeAsString = "id";
1518 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001519 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001520 }
Mike Stump11289f42009-09-09 15:08:12 +00001521
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 // struct __objcFastEnumerationState enumState = { 0 };
1523 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001524 // id __rw_items[16];
1525 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526 // id l_collection = (id)
1527 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001528 // Find start location of 'collection' the hard way!
1529 const char *startCollectionBuf = startBuf;
1530 startCollectionBuf += 3; // skip 'for'
1531 startCollectionBuf = strchr(startCollectionBuf, '(');
1532 startCollectionBuf++; // skip '('
1533 // find 'in' and skip it.
1534 while (*startCollectionBuf != ' ' ||
1535 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1536 (*(startCollectionBuf+3) != ' ' &&
1537 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1538 startCollectionBuf++;
1539 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001540
1541 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001542 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001543 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001544 SourceLocation rightParenLoc = S->getRParenLoc();
1545 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001546 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001547 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001548
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001549 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001550 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001551 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001552 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001553 // ((unsigned int (*)
1554 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001555 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001557 // "countByEnumeratingWithState:objects:count:"),
1558 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001559 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001560 buf += "unsigned long limit =\n\t\t";
1561 SynthCountByEnumWithState(buf);
1562 buf += ";\n\t";
1563 /// if (limit) {
1564 /// unsigned long startMutations = *enumState.mutationsPtr;
1565 /// do {
1566 /// unsigned long counter = 0;
1567 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001568 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001569 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001570 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001571 buf += "if (limit) {\n\t";
1572 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1573 buf += "do {\n\t\t";
1574 buf += "unsigned long counter = 0;\n\t\t";
1575 buf += "do {\n\t\t\t";
1576 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1577 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1578 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001579 buf += " = (";
1580 buf += elementTypeAsString;
1581 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001582 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001583 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001584
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001585 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001586 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001587 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001588 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001589 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001590 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001591 /// }
1592 /// else
1593 /// elem = nil;
1594 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001595 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001596 buf = ";\n\t";
1597 buf += "__continue_label_";
1598 buf += utostr(ObjCBcLabelNo.back());
1599 buf += ": ;";
1600 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001601 buf += "} while (counter < limit);\n\t";
1602 buf += "} while (limit = ";
1603 SynthCountByEnumWithState(buf);
1604 buf += ");\n\t";
1605 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001606 buf += " = ((";
1607 buf += elementTypeAsString;
1608 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001609 buf += "__break_label_";
1610 buf += utostr(ObjCBcLabelNo.back());
1611 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001612 buf += "}\n\t";
1613 buf += "else\n\t\t";
1614 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001615 buf += " = ((";
1616 buf += elementTypeAsString;
1617 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001618 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001619
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001620 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001621 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001622 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001623 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001624 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001625 } else {
1626 /* Need to treat single statements specially. For example:
1627 *
1628 * for (A *a in b) if (stuff()) break;
1629 * for (A *a in b) xxxyy;
1630 *
1631 * The following code simply scans ahead to the semi to find the actual end.
1632 */
1633 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1634 const char *semiBuf = strchr(stmtBuf, ';');
1635 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001636 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001637 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001638 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001639 Stmts.pop_back();
1640 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001641 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001642}
1643
Mike Stump11289f42009-09-09 15:08:12 +00001644/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001645/// This routine rewrites @synchronized(expr) stmt;
1646/// into:
1647/// objc_sync_enter(expr);
1648/// @try stmt @finally { objc_sync_exit(expr); }
1649///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001650Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001651 // Get the start location and compute the semi location.
1652 SourceLocation startLoc = S->getLocStart();
1653 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001655 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001656
1657 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001658 buf = "objc_sync_enter((id)";
1659 const char *lparenBuf = startBuf;
1660 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001661 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001662 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1663 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001664 // been rewritten! (which implies the SourceLocation's are invalid).
1665 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001666 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001667 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001668 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001669 buf = ");\n";
1670 // declare a new scope with two variables, _stack and _rethrow.
1671 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1672 buf += "int buf[18/*32-bit i386*/];\n";
1673 buf += "char *pointers[4];} _stack;\n";
1674 buf += "id volatile _rethrow = 0;\n";
1675 buf += "objc_exception_try_enter(&_stack);\n";
1676 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001677 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001678 startLoc = S->getSynchBody()->getLocEnd();
1679 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Steve Naroffad7013b2008-08-19 13:04:19 +00001681 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001682 SourceLocation lastCurlyLoc = startLoc;
1683 buf = "}\nelse {\n";
1684 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001685 buf += "}\n";
1686 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001687 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001688
1689 std::string syncBuf;
1690 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001691
1692 Expr *syncExpr = S->getSynchExpr();
1693 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1694 ? CK_BitCast :
1695 syncExpr->getType()->isBlockPointerType()
1696 ? CK_BlockPointerToObjCPointerCast
1697 : CK_CPointerToObjCPointerCast;
1698 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1699 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001700 std::string syncExprBufS;
1701 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smith235341b2012-08-16 03:56:14 +00001702 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001703 syncBuf += syncExprBuf.str();
1704 syncBuf += ");";
1705
1706 buf += syncBuf;
1707 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001708 buf += "}\n";
1709 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001710
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001711 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001712
1713 bool hasReturns = false;
1714 HasReturnStmts(S->getSynchBody(), hasReturns);
1715 if (hasReturns)
1716 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1717
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001718 return 0;
1719}
1720
Steve Naroffec60b432009-12-05 21:43:12 +00001721void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1722{
Steve Naroff6d6da252008-12-05 17:03:39 +00001723 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001724 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001725 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001726 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001727
Steve Naroffec60b432009-12-05 21:43:12 +00001728 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001729 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001730 TryFinallyContainsReturnDiag);
1731 }
1732 return;
1733}
1734
Steve Naroffec60b432009-12-05 21:43:12 +00001735void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1736{
1737 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001738 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001739 if (*CI)
1740 HasReturnStmts(*CI, hasReturns);
1741
1742 if (isa<ReturnStmt>(S))
1743 hasReturns = true;
1744 return;
1745}
1746
1747void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1748 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001749 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001750 if (*CI) {
1751 RewriteTryReturnStmts(*CI);
1752 }
1753 if (isa<ReturnStmt>(S)) {
1754 SourceLocation startLoc = S->getLocStart();
1755 const char *startBuf = SM->getCharacterData(startLoc);
1756
1757 const char *semiBuf = strchr(startBuf, ';');
1758 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001759 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001760
1761 std::string buf;
1762 buf = "{ objc_exception_try_exit(&_stack); return";
1763
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001764 ReplaceText(startLoc, 6, buf);
1765 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001766 }
1767 return;
1768}
1769
1770void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1771 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001772 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001773 if (*CI) {
1774 RewriteSyncReturnStmts(*CI, syncExitBuf);
1775 }
1776 if (isa<ReturnStmt>(S)) {
1777 SourceLocation startLoc = S->getLocStart();
1778 const char *startBuf = SM->getCharacterData(startLoc);
1779
1780 const char *semiBuf = strchr(startBuf, ';');
1781 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001782 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001783
1784 std::string buf;
1785 buf = "{ objc_exception_try_exit(&_stack);";
1786 buf += syncExitBuf;
1787 buf += " return";
1788
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001789 ReplaceText(startLoc, 6, buf);
1790 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001791 }
1792 return;
1793}
1794
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001795Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001796 // Get the start location and compute the semi location.
1797 SourceLocation startLoc = S->getLocStart();
1798 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Steve Naroffbf478ec2007-11-07 04:08:17 +00001800 assert((*startBuf == '@') && "bogus @try location");
1801
1802 std::string buf;
1803 // declare a new scope with two variables, _stack and _rethrow.
1804 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1805 buf += "int buf[18/*32-bit i386*/];\n";
1806 buf += "char *pointers[4];} _stack;\n";
1807 buf += "id volatile _rethrow = 0;\n";
1808 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001809 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001811 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001812
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 startLoc = S->getTryBody()->getLocEnd();
1814 startBuf = SM->getCharacterData(startLoc);
1815
1816 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001817
Steve Naroffbf478ec2007-11-07 04:08:17 +00001818 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001819 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001820 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001821 buf = " /* @catch begin */ else {\n";
1822 buf += " id _caught = objc_exception_extract(&_stack);\n";
1823 buf += " objc_exception_try_enter (&_stack);\n";
1824 buf += " if (_setjmp(_stack.buf))\n";
1825 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1826 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001827
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001828 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001829 } else { /* no catch list */
1830 buf = "}\nelse {\n";
1831 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1832 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001833 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001834 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001836 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1837 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001838 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001839
Douglas Gregor96c79492010-04-23 22:50:49 +00001840 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001841 buf = "if ("; // we are generating code for the first catch clause
1842 else
1843 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001844 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001846
Steve Naroffbf478ec2007-11-07 04:08:17 +00001847 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001848
Steve Naroffbf478ec2007-11-07 04:08:17 +00001849 const char *lParenLoc = strchr(startBuf, '(');
1850
Douglas Gregor96c79492010-04-23 22:50:49 +00001851 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001852 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001853 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001854 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1855 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001856 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001857 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001858 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001859
Steve Naroffedb5bc62008-02-01 20:02:07 +00001860 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001861 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001862 } else if (catchDecl) {
1863 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001864 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001865 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001867 } else if (const ObjCObjectPointerType *Ptr =
1868 t->getAs<ObjCObjectPointerType>()) {
1869 // Should be a pointer to a class.
1870 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1871 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001872 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001873 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001874 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001875 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001876 }
1877 }
1878 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001879 lastCatchBody = Catch->getCatchBody();
1880 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001881 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1882 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1883 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1884 assert((*rParenBuf == ')') && "bogus @catch paren location");
1885 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001886
Mike Stump11289f42009-09-09 15:08:12 +00001887 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001888 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001889 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001890 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001891 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001892 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001893 }
1894 // Complete the catch list...
1895 if (lastCatchBody) {
1896 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001897 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1898 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroff4adbe312008-09-11 15:29:03 +00001900 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001901 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001902 buf = "} /* last catch end */\n";
1903 buf += "else {\n";
1904 buf += " _rethrow = _caught;\n";
1905 buf += " objc_exception_try_exit(&_stack);\n";
1906 buf += "} } /* @catch end */\n";
1907 if (!S->getFinallyStmt())
1908 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001909 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001910
Steve Naroffbf478ec2007-11-07 04:08:17 +00001911 // Set lastCurlyLoc
1912 lastCurlyLoc = lastCatchBody->getLocEnd();
1913 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001914 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001915 startLoc = finalStmt->getLocStart();
1916 startBuf = SM->getCharacterData(startLoc);
1917 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001918
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001919 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001920
Steve Naroffbf478ec2007-11-07 04:08:17 +00001921 Stmt *body = finalStmt->getFinallyBody();
1922 SourceLocation startLoc = body->getLocStart();
1923 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001924 assert(*SM->getCharacterData(startLoc) == '{' &&
1925 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001926 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001927 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001928
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001929 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001930 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001931 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001932 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001933
Steve Naroffbf478ec2007-11-07 04:08:17 +00001934 // Set lastCurlyLoc
1935 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001936
Steve Naroff6d6da252008-12-05 17:03:39 +00001937 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001938 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001939 } else { /* no finally clause - make sure we synthesize an implicit one */
1940 buf = "{ /* implicit finally clause */\n";
1941 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1942 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1943 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001944 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001945
1946 // Now check for any return/continue/go statements within the @try.
1947 // The implicit finally clause won't called if the @try contains any
1948 // jump statements.
1949 bool hasReturns = false;
1950 HasReturnStmts(S->getTryBody(), hasReturns);
1951 if (hasReturns)
1952 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001953 }
1954 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001955 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001956 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001957 return 0;
1958}
1959
Mike Stump11289f42009-09-09 15:08:12 +00001960// This can't be done with ReplaceStmt(S, ThrowExpr), since
1961// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001962// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001963Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001964 // Get the start location and compute the semi location.
1965 SourceLocation startLoc = S->getLocStart();
1966 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Steve Naroffa733c7f2007-11-07 15:32:26 +00001968 assert((*startBuf == '@') && "bogus @throw location");
1969
1970 std::string buf;
1971 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001972 if (S->getThrowExpr())
1973 buf = "objc_exception_throw(";
1974 else // add an implicit argument
1975 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001976
Steve Naroff29788342008-07-25 15:41:30 +00001977 // handle "@ throw" correctly.
1978 const char *wBuf = strchr(startBuf, 'w');
1979 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001980 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffa733c7f2007-11-07 15:32:26 +00001982 const char *semiBuf = strchr(startBuf, ';');
1983 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001984 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001985 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001986 return 0;
1987}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001988
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001990 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00001991 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001992 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00001993 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001994 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001995
Chris Lattner4431a1b2007-11-30 22:53:43 +00001996 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001997 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001998 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001999}
2000
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002001Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002002 if (!SelGetUidFunctionDecl)
2003 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002004 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2005 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002006 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002007 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002008 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2009 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002010 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002011 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002012 return SelExp;
2013}
2014
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002015CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002016 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2017 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002018 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002019 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002020
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002021 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002022 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2023 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002024
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002025 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002026 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002027 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002028 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002029 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002030
John McCall9dd450b2009-09-21 23:43:11 +00002031 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002032
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002033 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002034 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCall7decc9e2010-11-18 06:31:45 +00002035 FT->getCallResultType(*Context),
2036 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002037 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002038}
2039
Steve Naroff50d42052007-11-01 13:24:47 +00002040static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2041 const char *&startRef, const char *&endRef) {
2042 while (startBuf < endBuf) {
2043 if (*startBuf == '<')
2044 startRef = startBuf; // mark the start.
2045 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002046 if (startRef && *startRef == '<') {
2047 endRef = startBuf; // mark the end.
2048 return true;
2049 }
2050 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002051 }
2052 startBuf++;
2053 }
2054 return false;
2055}
2056
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002057static void scanToNextArgument(const char *&argRef) {
2058 int angle = 0;
2059 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2060 if (*argRef == '<')
2061 angle++;
2062 else if (*argRef == '>')
2063 angle--;
2064 argRef++;
2065 }
2066 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2067}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002068
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002069bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002070 if (T->isObjCQualifiedIdType())
2071 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002072 if (const PointerType *PT = T->getAs<PointerType>()) {
2073 if (PT->getPointeeType()->isObjCQualifiedIdType())
2074 return true;
2075 }
2076 if (T->isObjCObjectPointerType()) {
2077 T = T->getPointeeType();
2078 return T->isObjCQualifiedInterfaceType();
2079 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002080 if (T->isArrayType()) {
2081 QualType ElemTy = Context->getBaseElementType(T);
2082 return needToScanForQualifiers(ElemTy);
2083 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002084 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002085}
2086
Steve Naroff873bd842008-07-29 18:15:38 +00002087void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2088 QualType Type = E->getType();
2089 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002090 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002091
Steve Naroffdbfc6932008-11-19 21:15:47 +00002092 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2093 Loc = ECE->getLParenLoc();
2094 EndLoc = ECE->getRParenLoc();
2095 } else {
2096 Loc = E->getLocStart();
2097 EndLoc = E->getLocEnd();
2098 }
2099 // This will defend against trying to rewrite synthesized expressions.
2100 if (Loc.isInvalid() || EndLoc.isInvalid())
2101 return;
2102
Steve Naroff873bd842008-07-29 18:15:38 +00002103 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002104 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002105 const char *startRef = 0, *endRef = 0;
2106 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2107 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002108 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2109 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002110 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002111 InsertText(LessLoc, "/*");
2112 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002113 }
2114 }
2115}
2116
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002117void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002118 SourceLocation Loc;
2119 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002120 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002121 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2122 Loc = VD->getLocation();
2123 Type = VD->getType();
2124 }
2125 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2126 Loc = FD->getLocation();
2127 // Check for ObjC 'id' and class types that have been adorned with protocol
2128 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002129 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002130 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002132 if (!proto)
2133 return;
Alp Toker314cc812014-01-25 16:55:45 +00002134 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002135 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002136 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2137 Loc = FD->getLocation();
2138 Type = FD->getType();
2139 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002140 else
2141 return;
Mike Stump11289f42009-09-09 15:08:12 +00002142
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002143 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002144 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002145
Steve Naroff50d42052007-11-01 13:24:47 +00002146 const char *endBuf = SM->getCharacterData(Loc);
2147 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002148 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002149 startBuf--; // scan backward (from the decl location) for return type.
2150 const char *startRef = 0, *endRef = 0;
2151 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2152 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002153 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2154 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002155 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002156 InsertText(LessLoc, "/*");
2157 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002158 }
2159 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002160 if (!proto)
2161 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002162 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002163 const char *startBuf = SM->getCharacterData(Loc);
2164 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002165 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2166 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002167 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002168
Steve Naroff50d42052007-11-01 13:24:47 +00002169 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002170 // scan forward (from the decl location) for argument types.
2171 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002172 const char *startRef = 0, *endRef = 0;
2173 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2174 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002175 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002176 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002177 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002178 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002179 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002182 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002183 startBuf = ++endBuf;
2184 }
2185 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002186 // If the function name is derived from a macro expansion, then the
2187 // argument buffer will not follow the name. Need to speak with Chris.
2188 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002189 startBuf++; // scan forward (from the decl location) for argument types.
2190 startBuf++;
2191 }
Steve Naroff50d42052007-11-01 13:24:47 +00002192 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002193}
2194
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002195void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2196 QualType QT = ND->getType();
2197 const Type* TypePtr = QT->getAs<Type>();
2198 if (!isa<TypeOfExprType>(TypePtr))
2199 return;
2200 while (isa<TypeOfExprType>(TypePtr)) {
2201 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2202 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2203 TypePtr = QT->getAs<Type>();
2204 }
2205 // FIXME. This will not work for multiple declarators; as in:
2206 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002207 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002208 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2209 const char *startBuf = SM->getCharacterData(DeclLoc);
2210 if (ND->getInit()) {
2211 std::string Name(ND->getNameAsString());
2212 TypeAsString += " " + Name + " = ";
2213 Expr *E = ND->getInit();
2214 SourceLocation startLoc;
2215 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2216 startLoc = ECE->getLParenLoc();
2217 else
2218 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002219 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002220 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002221 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002222 }
2223 else {
2224 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002225 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002226 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002227 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002228 }
2229}
2230
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002231// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002232void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002233 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002234 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002235 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002236 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002237 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002238 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002239 SourceLocation(),
2240 SourceLocation(),
2241 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002242 SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002243}
2244
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002245void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002246 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002247 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002248 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002249 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002250 return;
2251 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002252 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002253}
2254
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002255void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002256 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002257 const char *argPtr = TypeString.c_str();
2258 if (!strchr(argPtr, '^')) {
2259 Str += TypeString;
2260 return;
2261 }
2262 while (*argPtr) {
2263 Str += (*argPtr == '^' ? '*' : *argPtr);
2264 argPtr++;
2265 }
2266}
2267
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002268// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002269void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2270 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002271 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002272 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002273 const char *argPtr = TypeString.c_str();
2274 int paren = 0;
2275 while (*argPtr) {
2276 switch (*argPtr) {
2277 case '(':
2278 Str += *argPtr;
2279 paren++;
2280 break;
2281 case ')':
2282 Str += *argPtr;
2283 paren--;
2284 break;
2285 case '^':
2286 Str += '*';
2287 if (paren == 1)
2288 Str += VD->getNameAsString();
2289 break;
2290 default:
2291 Str += *argPtr;
2292 break;
2293 }
2294 argPtr++;
2295 }
2296}
2297
2298
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002299void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2300 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2301 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2302 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2303 if (!proto)
2304 return;
Alp Toker314cc812014-01-25 16:55:45 +00002305 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002306 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002307 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002308 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002309 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002310 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002311 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002313 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002314 if (i+1 < numArgs)
2315 FdStr += ", ";
2316 }
2317 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002318 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002319 CurFunctionDeclToDeclareForBlock = 0;
2320}
2321
Benjamin Kramer60509af2013-09-09 14:48:42 +00002322// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2323void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2324 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002325 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002326 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002327 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002328 QualType argT = Context->getObjCIdType();
2329 assert(!argT.isNull() && "Can't find 'id' type");
2330 ArgTys.push_back(argT);
2331 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002332 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002333 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002334 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002338 0, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002339}
2340
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002341// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002342void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002343 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002344 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002345 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002346 assert(!argT.isNull() && "Can't find 'id' type");
2347 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002348 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002349 assert(!argT.isNull() && "Can't find 'SEL' type");
2350 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002351 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002352 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002353 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002354 SourceLocation(),
2355 SourceLocation(),
2356 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002357 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002358}
2359
Steve Naroff7fa2f042007-11-15 10:28:18 +00002360// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002361void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002362 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002363 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002364 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002365 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002366 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002367 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2368 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2369 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002370 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002371 assert(!argT.isNull() && "Can't find 'SEL' type");
2372 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002373 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002374 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002375 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002376 SourceLocation(),
2377 SourceLocation(),
2378 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002379 SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002380}
2381
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002382// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002383void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002384 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002385 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002386 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002387 assert(!argT.isNull() && "Can't find 'id' type");
2388 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002389 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002390 assert(!argT.isNull() && "Can't find 'SEL' type");
2391 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002392 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002393 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002394 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002395 SourceLocation(),
2396 SourceLocation(),
2397 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002398 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002399}
2400
Mike Stump11289f42009-09-09 15:08:12 +00002401// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002402// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002403void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002404 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002405 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002406 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002407 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002408 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002409 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002410 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2411 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2412 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002413 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002414 assert(!argT.isNull() && "Can't find 'SEL' type");
2415 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002416 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002417 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002418 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002419 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002420 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002421 msgSendIdent,
2422 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002423 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002424}
2425
Steve Naroff2e4e3852008-05-08 22:02:18 +00002426// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002427void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002428 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002429 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002430 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002431 assert(!argT.isNull() && "Can't find 'id' type");
2432 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002433 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002434 assert(!argT.isNull() && "Can't find 'SEL' type");
2435 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002436 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002437 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002438 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002439 SourceLocation(),
2440 SourceLocation(),
2441 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002442 SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002443}
2444
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002445// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002446void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002447 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002448 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002449 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002450 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002451 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002452 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002453 SourceLocation(),
2454 SourceLocation(),
2455 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002456 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002457}
2458
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002459// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2460void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2461 IdentifierInfo *getSuperClassIdent =
2462 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002464 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002465 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002466 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002467 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002468 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002469 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002470 getSuperClassIdent,
2471 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002472 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002473}
2474
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002475// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002476void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002477 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002478 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002479 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002480 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002481 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002482 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002483 SourceLocation(),
2484 SourceLocation(),
2485 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002486 0, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002487}
2488
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002489Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002490 QualType strType = getConstantStringStructType();
2491
2492 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002493
2494 std::string tmpName = InFileName;
2495 unsigned i;
2496 for (i=0; i < tmpName.length(); i++) {
2497 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002498 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002499 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002500 tmpName[i] = '_';
2501 }
2502 S += tmpName;
2503 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002504 S += utostr(NumObjCStringLiterals++);
2505
Steve Naroff00a31762008-03-27 22:29:16 +00002506 Preamble += "static __NSConstantStringImpl " + S;
2507 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2508 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002509 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002510 std::string prettyBufS;
2511 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002512 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002513 Preamble += prettyBuf.str();
2514 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002515 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002516
2517 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002518 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002519 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002520 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002521 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002522 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002523 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002524 VK_RValue, OK_Ordinary,
2525 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002526 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002527 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002528 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002529 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002530 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002531 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002532}
2533
Steve Naroff7fa2f042007-11-15 10:28:18 +00002534// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002535QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002536 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002537 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002538 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002539 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002540 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002541
Steve Naroff7fa2f042007-11-15 10:28:18 +00002542 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002543 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002544 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002545 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002546
Steve Naroff7fa2f042007-11-15 10:28:18 +00002547 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002548 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002549 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002550 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002551 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002552 FieldTypes[i], 0,
2553 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002554 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002555 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002556 }
Mike Stump11289f42009-09-09 15:08:12 +00002557
Douglas Gregord5058122010-02-11 01:19:42 +00002558 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002559 }
2560 return Context->getTagDeclType(SuperStructDecl);
2561}
2562
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002563QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002564 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002565 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002566 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002567 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002568 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002569
Steve Naroffce8e8862008-03-15 00:55:56 +00002570 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002571 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002572 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002573 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002574 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002575 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002576 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002577 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002578
Steve Naroffce8e8862008-03-15 00:55:56 +00002579 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002580 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2582 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002583 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00002584 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002585 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002586 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002587 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002588 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002589 }
2590
Douglas Gregord5058122010-02-11 01:19:42 +00002591 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002592 }
2593 return Context->getTagDeclType(ConstantStringDecl);
2594}
2595
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002596CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2597 QualType msgSendType,
2598 QualType returnType,
2599 SmallVectorImpl<QualType> &ArgTypes,
2600 SmallVectorImpl<Expr*> &MsgExprs,
2601 ObjCMethodDecl *Method) {
2602 // Create a reference to the objc_msgSend_stret() declaration.
2603 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2604 false, msgSendType,
2605 VK_LValue, SourceLocation());
2606 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2607 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2608 Context->getPointerType(Context->VoidTy),
2609 CK_BitCast, STDRE);
2610 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002611 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2612 Method ? Method->isVariadic()
2613 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002614 castType = Context->getPointerType(castType);
2615 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2616 cast);
2617
2618 // Don't forget the parens to enforce the proper binding.
2619 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2620
2621 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002622 CallExpr *STCE = new (Context) CallExpr(
2623 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002624 return STCE;
2625
2626}
2627
2628
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002629Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2630 SourceLocation StartLoc,
2631 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002632 if (!SelGetUidFunctionDecl)
2633 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002634 if (!MsgSendFunctionDecl)
2635 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002636 if (!MsgSendSuperFunctionDecl)
2637 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002638 if (!MsgSendStretFunctionDecl)
2639 SynthMsgSendStretFunctionDecl();
2640 if (!MsgSendSuperStretFunctionDecl)
2641 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002642 if (!MsgSendFpretFunctionDecl)
2643 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002644 if (!GetClassFunctionDecl)
2645 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002646 if (!GetSuperClassFunctionDecl)
2647 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002648 if (!GetMetaClassFunctionDecl)
2649 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002650
Steve Naroff7fa2f042007-11-15 10:28:18 +00002651 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002652 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2653 // May need to use objc_msgSend_stret() as well.
2654 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002655 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002656 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002657 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002658 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002659 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002660 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Steve Naroff574440f2007-10-24 22:48:43 +00002663 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002664 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002665 switch (Exp->getReceiverKind()) {
2666 case ObjCMessageExpr::SuperClass: {
2667 MsgSendFlavor = MsgSendSuperFunctionDecl;
2668 if (MsgSendStretFlavor)
2669 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2670 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregor9a129192010-04-21 00:45:42 +00002672 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002673
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002675
Douglas Gregor9a129192010-04-21 00:45:42 +00002676 // set the receiver to self, the first argument to all methods.
2677 InitExprs.push_back(
2678 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002679 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002680 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002681 false,
John McCall7decc9e2010-11-18 06:31:45 +00002682 Context->getObjCIdType(),
2683 VK_RValue,
2684 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002685 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregor9a129192010-04-21 00:45:42 +00002687 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002688 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002689 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002690 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2691 &ClsExprs[0],
2692 ClsExprs.size(),
2693 StartLoc,
2694 EndLoc);
2695 // (Class)objc_getClass("CurrentClass")
2696 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2697 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002698 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002699 ClsExprs.clear();
2700 ClsExprs.push_back(ArgExpr);
2701 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2702 &ClsExprs[0], ClsExprs.size(),
2703 StartLoc, EndLoc);
2704
2705 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2706 // To turn off a warning, type-cast to 'id'
2707 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2708 NoTypeInfoCStyleCastExpr(Context,
2709 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002710 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002711 // struct objc_super
2712 QualType superType = getSuperStructType();
2713 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002714
Francois Pichet0706d202011-09-17 17:15:52 +00002715 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002716 SynthSuperConstructorFunctionDecl();
2717 // Simulate a constructor call...
2718 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002719 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002720 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002721 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002722 superType, VK_LValue,
2723 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002724 // The code for super is a little tricky to prevent collision with
2725 // the structure definition in the header. The rewriter has it's own
2726 // internal definition (__rw_objc_super) that is uses. This is why
2727 // we need the cast below. For example:
2728 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2729 //
John McCalle3027922010-08-25 11:45:40 +00002730 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002731 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002732 VK_RValue, OK_Ordinary,
2733 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002734 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2735 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002736 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002737 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002738 // (struct objc_super) { <exprs from above> }
2739 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002740 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 SourceLocation());
2742 TypeSourceInfo *superTInfo
2743 = Context->getTrivialTypeSourceInfo(superType);
2744 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002745 superType, VK_LValue,
2746 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002747 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002748 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002749 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002750 VK_RValue, OK_Ordinary,
2751 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002752 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002753 MsgExprs.push_back(SuperRep);
2754 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002755 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002756
2757 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002758 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002759 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002760 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002761 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002762 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002763 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2764 &ClsExprs[0],
2765 ClsExprs.size(),
2766 StartLoc, EndLoc);
2767 MsgExprs.push_back(Cls);
2768 break;
2769 }
2770
2771 case ObjCMessageExpr::SuperInstance:{
2772 MsgSendFlavor = MsgSendSuperFunctionDecl;
2773 if (MsgSendStretFlavor)
2774 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2775 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2776 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002777 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002778
2779 InitExprs.push_back(
2780 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002781 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002782 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002783 false,
John McCall7decc9e2010-11-18 06:31:45 +00002784 Context->getObjCIdType(),
2785 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002786 ); // set the 'receiver'.
2787
2788 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002789 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002790 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002791 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2792 &ClsExprs[0],
2793 ClsExprs.size(),
2794 StartLoc, EndLoc);
2795 // (Class)objc_getClass("CurrentClass")
2796 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2797 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002798 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002799 ClsExprs.clear();
2800 ClsExprs.push_back(ArgExpr);
2801 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2802 &ClsExprs[0], ClsExprs.size(),
2803 StartLoc, EndLoc);
2804
2805 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2806 // To turn off a warning, type-cast to 'id'
2807 InitExprs.push_back(
2808 // set 'super class', using class_getSuperclass().
2809 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002810 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002811 // struct objc_super
2812 QualType superType = getSuperStructType();
2813 Expr *SuperRep;
2814
Francois Pichet0706d202011-09-17 17:15:52 +00002815 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002816 SynthSuperConstructorFunctionDecl();
2817 // Simulate a constructor call...
2818 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002819 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002820 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002821 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002822 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002823 // The code for super is a little tricky to prevent collision with
2824 // the structure definition in the header. The rewriter has it's own
2825 // internal definition (__rw_objc_super) that is uses. This is why
2826 // we need the cast below. For example:
2827 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2828 //
John McCalle3027922010-08-25 11:45:40 +00002829 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002830 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002831 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002832 SourceLocation());
2833 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2834 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002835 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002836 } else {
2837 // (struct objc_super) { <exprs from above> }
2838 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002839 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002840 SourceLocation());
2841 TypeSourceInfo *superTInfo
2842 = Context->getTrivialTypeSourceInfo(superType);
2843 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002844 superType, VK_RValue, ILE,
2845 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002846 }
2847 MsgExprs.push_back(SuperRep);
2848 break;
2849 }
2850
2851 case ObjCMessageExpr::Instance: {
2852 // Remove all type-casts because it may contain objc-style types; e.g.
2853 // Foo<Proto> *.
2854 Expr *recExpr = Exp->getInstanceReceiver();
2855 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2856 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002857 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2858 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2859 ? CK_BlockPointerToObjCPointerCast
2860 : CK_CPointerToObjCPointerCast;
2861
Douglas Gregor9a129192010-04-21 00:45:42 +00002862 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002863 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002864 MsgExprs.push_back(recExpr);
2865 break;
2866 }
2867 }
2868
Steve Naroffa397efd2007-11-03 11:27:19 +00002869 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002870 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002871 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002872 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002873 &SelExprs[0], SelExprs.size(),
2874 StartLoc,
2875 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002876 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002877
Steve Naroff574440f2007-10-24 22:48:43 +00002878 // Now push any user supplied arguments.
2879 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002880 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002881 // Make all implicit casts explicit...ICE comes in handy:-)
2882 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2883 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002884 QualType type = ICE->getType();
2885 if (needToScanForQualifiers(type))
2886 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002887 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002888 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002889 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002890 CastKind CK;
2891 if (SubExpr->getType()->isIntegralType(*Context) &&
2892 type->isBooleanType()) {
2893 CK = CK_IntegralToBoolean;
2894 } else if (type->isObjCObjectPointerType()) {
2895 if (SubExpr->getType()->isBlockPointerType()) {
2896 CK = CK_BlockPointerToObjCPointerCast;
2897 } else if (SubExpr->getType()->isPointerType()) {
2898 CK = CK_CPointerToObjCPointerCast;
2899 } else {
2900 CK = CK_BitCast;
2901 }
2902 } else {
2903 CK = CK_BitCast;
2904 }
2905
2906 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002907 }
2908 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002909 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002910 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002911 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002912 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002913 CastKind CK;
2914 if (userExpr->getType()->isIntegralType(*Context)) {
2915 CK = CK_IntegralToPointer;
2916 } else if (userExpr->getType()->isBlockPointerType()) {
2917 CK = CK_BlockPointerToObjCPointerCast;
2918 } else if (userExpr->getType()->isPointerType()) {
2919 CK = CK_CPointerToObjCPointerCast;
2920 } else {
2921 CK = CK_BitCast;
2922 }
John McCall97513962010-01-15 18:39:57 +00002923 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002924 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002925 }
Mike Stump11289f42009-09-09 15:08:12 +00002926 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002927 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002928 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2929 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002930 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002931 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002932 }
Steve Narofff36987c2007-11-04 22:37:50 +00002933 // Generate the funky cast.
2934 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002935 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002936 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002937
Steve Narofff36987c2007-11-04 22:37:50 +00002938 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002939 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2940 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2941 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002942 ArgTypes.push_back(Context->getObjCIdType());
2943 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002944 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002945 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002946 for (const auto *PI : OMD->params()) {
2947 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002948 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002949 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002950 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002951 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002952 ArgTypes.push_back(t);
2953 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002954 returnType = Exp->getType();
2955 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002956 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002957 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002958 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002959 }
2960 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002961 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002962
Steve Narofff36987c2007-11-04 22:37:50 +00002963 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002964 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002965 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002966
Mike Stump11289f42009-09-09 15:08:12 +00002967 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002968 // If we don't do this cast, we get the following bizarre warning/note:
2969 // xx.m:13: warning: function called through a non-compatible type
2970 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002971 cast = NoTypeInfoCStyleCastExpr(Context,
2972 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002973 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002974
Steve Narofff36987c2007-11-04 22:37:50 +00002975 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002976 // If we don't have a method decl, force a variadic cast.
2977 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002978 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002979 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002980 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002981 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002982 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002983
2984 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002985 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002986
John McCall9dd450b2009-09-21 23:43:11 +00002987 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002988 CallExpr *CE = new (Context)
2989 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002990 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002991 if (MsgSendStretFlavor) {
2992 // We have the method which returns a struct/union. Must also generate
2993 // call to objc_msgSend_stret and hang both varieties on a conditional
2994 // expression which dictate which one to envoke depending on size of
2995 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002996
2997 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2998 msgSendType, returnType,
2999 ArgTypes, MsgExprs,
3000 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003001
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003002 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003003 UnaryExprOrTypeTraitExpr *sizeofExpr =
3004 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3005 Context->getTrivialTypeSourceInfo(returnType),
3006 Context->getSizeType(), SourceLocation(),
3007 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003008 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3009 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3010 // For X86 it is more complicated and some kind of target specific routine
3011 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003012 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003013 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003014 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3015 llvm::APInt(IntSize, 8),
3016 Context->IntTy,
3017 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003018 BinaryOperator *lessThanExpr =
3019 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003020 VK_RValue, OK_Ordinary, SourceLocation(),
3021 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003022 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003023 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003024 new (Context) ConditionalOperator(lessThanExpr,
3025 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003026 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003027 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003028 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3029 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003030 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003031 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003032 return ReplacingStmt;
3033}
3034
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003035Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003036 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3037 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003038
Steve Naroff574440f2007-10-24 22:48:43 +00003039 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003040 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003042 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003043 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003044}
3045
Steve Naroffd9803712009-04-29 16:37:50 +00003046// typedef struct objc_object Protocol;
3047QualType RewriteObjC::getProtocolType() {
3048 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003049 TypeSourceInfo *TInfo
3050 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003051 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003052 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003053 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003054 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003055 }
3056 return Context->getTypeDeclType(ProtocolTypeDecl);
3057}
3058
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003059/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003060/// a synthesized/forward data reference (to the protocol's metadata).
3061/// The forward references (and metadata) are generated in
3062/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003063Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003064 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3065 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003066 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003067 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003068 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003069 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3070 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003071 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003072 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003073 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003074 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003075 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003076 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003077 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003078 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003079 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003080 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003081
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003082}
3083
Mike Stump11289f42009-09-09 15:08:12 +00003084bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003085 const char *endBuf) {
3086 while (startBuf < endBuf) {
3087 if (*startBuf == '#') {
3088 // Skip whitespace.
3089 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3090 ;
3091 if (!strncmp(startBuf, "if", strlen("if")) ||
3092 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3093 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3094 !strncmp(startBuf, "define", strlen("define")) ||
3095 !strncmp(startBuf, "undef", strlen("undef")) ||
3096 !strncmp(startBuf, "else", strlen("else")) ||
3097 !strncmp(startBuf, "elif", strlen("elif")) ||
3098 !strncmp(startBuf, "endif", strlen("endif")) ||
3099 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3100 !strncmp(startBuf, "include", strlen("include")) ||
3101 !strncmp(startBuf, "import", strlen("import")) ||
3102 !strncmp(startBuf, "include_next", strlen("include_next")))
3103 return true;
3104 }
3105 startBuf++;
3106 }
3107 return false;
3108}
3109
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003110/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003111/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003112void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003113 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003114 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003115 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003116 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003117 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003118 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003119 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003120 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003121 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003122 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003123 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003124
Steve Naroffdde78982007-11-14 19:25:57 +00003125 const char *startBuf = SM->getCharacterData(LocStart);
3126 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003127
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003128 // If no ivars and no root or if its root, directly or indirectly,
3129 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003130 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003131 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003132 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003133 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003134 return;
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
3137 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003138 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003139 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003140 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003141 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003142 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003143
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003144 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003145 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003146 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003147 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003148 // If the buffer contains preprocessor directives, we do more fine-grained
3149 // rewrites. This is intended to fix code that looks like (which occurs in
3150 // NSURL.h, for example):
3151 //
3152 // #ifdef XYZ
3153 // @interface Foo : NSObject
3154 // #else
3155 // @interface FooBar : NSObject
3156 // #endif
3157 // {
3158 // int i;
3159 // }
3160 // @end
3161 //
3162 // This clause is segregated to avoid breaking the common case.
3163 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003164 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003165 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003166 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003167 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003168
Chris Lattnerf5b77512009-02-20 18:18:36 +00003169 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003170 // advance to the end of the referenced protocols.
3171 while (endHeader < cursor && *endHeader != '>') endHeader++;
3172 endHeader++;
3173 }
3174 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003175 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003176 } else {
3177 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003178 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003179 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003180 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003181 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003182 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003183 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003184 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003185 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003186
Steve Naroffdde78982007-11-14 19:25:57 +00003187 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003188 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003189 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003190 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003191 }
3192 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003193
Steve Naroffdde78982007-11-14 19:25:57 +00003194 // Now comment out any visibility specifiers.
3195 while (cursor < endBuf) {
3196 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003197 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003198 // Skip whitespace.
3199 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3200 /*scan*/;
3201
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003202 // FIXME: presence of @public, etc. inside comment results in
3203 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003204 if (!strncmp(cursor, "public", strlen("public")) ||
3205 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003206 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003207 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003208 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003209 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003210 // FIXME: If there are cases where '<' is used in ivar declaration part
3211 // of user code, then scan the ivar list and use needToScanForQualifiers
3212 // for type checking.
3213 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003214 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003215 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003216 cursor = strchr(cursor, '>');
3217 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003218 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003219 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003220 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003221 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003222 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003223 }
Steve Naroffdde78982007-11-14 19:25:57 +00003224 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003225 }
Steve Naroffdde78982007-11-14 19:25:57 +00003226 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003227 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003228 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003229 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003230 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003231 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003232 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003233 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003234 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003235 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003236 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003237 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003238 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikie83d382b2011-09-23 05:06:16 +00003239 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003240}
3241
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003242//===----------------------------------------------------------------------===//
3243// Meta Data Emission
3244//===----------------------------------------------------------------------===//
3245
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003246
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003247/// RewriteImplementations - This routine rewrites all method implementations
3248/// and emits meta-data.
3249
Steve Narofff8cfd162008-11-13 20:07:04 +00003250void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003251 int ClsDefCount = ClassImplementation.size();
3252 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003253
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003254 // Rewrite implemented methods
3255 for (int i = 0; i < ClsDefCount; i++)
3256 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003257
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003258 for (int i = 0; i < CatDefCount; i++)
3259 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003260}
Mike Stump11289f42009-09-09 15:08:12 +00003261
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003262void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3263 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003264 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003265 assert(BlockByRefDeclNo.count(VD) &&
3266 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003267 if (def)
3268 ResultStr += "struct ";
3269 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003270 "_" + utostr(BlockByRefDeclNo[VD]) ;
3271}
3272
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003273static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3274 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3275 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3276 return false;
3277}
3278
Steve Naroff677ab3a2008-10-27 17:20:55 +00003279std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003281 std::string Tag) {
3282 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003283 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003284 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003285 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003286 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003287
Steve Naroff677ab3a2008-10-27 17:20:55 +00003288 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003289
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003290 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003291 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003292 // block (to reference imported block decl refs).
3293 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003294 } else if (BD->param_empty()) {
3295 S += "(" + StructRef + " *__cself)";
3296 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003297 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003298 assert(FT && "SynthesizeBlockFunc: No function proto");
3299 S += '(';
3300 // first add the implicit argument.
3301 S += StructRef + " *__cself, ";
3302 std::string ParamStr;
3303 for (BlockDecl::param_iterator AI = BD->param_begin(),
3304 E = BD->param_end(); AI != E; ++AI) {
3305 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003306 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003307 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003308 (void)convertBlockPointerToFunctionPointer(QT);
3309 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003310 S += ParamStr;
3311 }
3312 if (FT->isVariadic()) {
3313 if (!BD->param_empty()) S += ", ";
3314 S += "...";
3315 }
3316 S += ')';
3317 }
3318 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003319
Steve Naroff677ab3a2008-10-27 17:20:55 +00003320 // Create local declarations to avoid rewriting all closure decl ref exprs.
3321 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003322 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003323 E = BlockByRefDecls.end(); I != E; ++I) {
3324 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003325 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003326 std::string TypeString;
3327 RewriteByRefString(TypeString, Name, (*I));
3328 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003329 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003330 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003331 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003332 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003333 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003334 E = BlockByCopyDecls.end(); I != E; ++I) {
3335 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003336 // Handle nested closure invocation. For example:
3337 //
3338 // void (^myImportedClosure)(void);
3339 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003340 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003341 // void (^anotherClosure)(void);
3342 // anotherClosure = ^(void) {
3343 // myImportedClosure(); // import and invoke the closure
3344 // };
3345 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003346 if (isTopLevelBlockPointerType((*I)->getType())) {
3347 RewriteBlockPointerTypeVariable(S, (*I));
3348 S += " = (";
3349 RewriteBlockPointerType(S, (*I)->getType());
3350 S += ")";
3351 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3352 }
3353 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003354 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003355 QualType QT = (*I)->getType();
3356 if (HasLocalVariableExternalStorage(*I))
3357 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003358 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003359 S += Name + " = __cself->" +
3360 (*I)->getNameAsString() + "; // bound by copy\n";
3361 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003362 }
3363 std::string RewrittenStr = RewrittenBlockExprs[CE];
3364 const char *cstr = RewrittenStr.c_str();
3365 while (*cstr++ != '{') ;
3366 S += cstr;
3367 S += "\n";
3368 return S;
3369}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003370
Steve Naroff677ab3a2008-10-27 17:20:55 +00003371std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003372 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003373 std::string Tag) {
3374 std::string StructRef = "struct " + Tag;
3375 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003376
Steve Naroff677ab3a2008-10-27 17:20:55 +00003377 S += funcName;
3378 S += "_block_copy_" + utostr(i);
3379 S += "(" + StructRef;
3380 S += "*dst, " + StructRef;
3381 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003382 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003383 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003384 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003385 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003386 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003387 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003388 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003389 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003390 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003391 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003392 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003393 else
3394 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003395 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003396 S += "}\n";
3397
Steve Naroff677ab3a2008-10-27 17:20:55 +00003398 S += "\nstatic void __";
3399 S += funcName;
3400 S += "_block_dispose_" + utostr(i);
3401 S += "(" + StructRef;
3402 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003403 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003404 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003405 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003406 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003407 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003408 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003409 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003410 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003411 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003412 else
3413 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003414 }
Mike Stump11289f42009-09-09 15:08:12 +00003415 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003416 return S;
3417}
3418
Steve Naroff30484702009-12-06 21:14:13 +00003419std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3420 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003421 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003422 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Steve Naroff677ab3a2008-10-27 17:20:55 +00003424 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003425 S += " struct " + Desc;
3426 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003427
Steve Naroff30484702009-12-06 21:14:13 +00003428 Constructor += "(void *fp, "; // Invoke function pointer.
3429 Constructor += "struct " + Desc; // Descriptor pointer.
3430 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003431
Steve Naroff677ab3a2008-10-27 17:20:55 +00003432 if (BlockDeclRefs.size()) {
3433 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003434 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003435 E = BlockByCopyDecls.end(); I != E; ++I) {
3436 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003437 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003438 std::string ArgName = "_" + FieldName;
3439 // Handle nested closure invocation. For example:
3440 //
3441 // void (^myImportedBlock)(void);
3442 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003443 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003444 // void (^anotherBlock)(void);
3445 // anotherBlock = ^(void) {
3446 // myImportedBlock(); // import and invoke the closure
3447 // };
3448 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003449 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003450 S += "struct __block_impl *";
3451 Constructor += ", void *" + ArgName;
3452 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003453 QualType QT = (*I)->getType();
3454 if (HasLocalVariableExternalStorage(*I))
3455 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003456 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3457 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003458 Constructor += ", " + ArgName;
3459 }
3460 S += FieldName + ";\n";
3461 }
3462 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003463 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003464 E = BlockByRefDecls.end(); I != E; ++I) {
3465 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003466 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003467 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003468 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003469 std::string TypeString;
3470 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003471 TypeString += " *";
3472 FieldName = TypeString + FieldName;
3473 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003474 Constructor += ", " + ArgName;
3475 }
3476 S += FieldName + "; // by ref\n";
3477 }
3478 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003479 Constructor += ", int flags=0)";
3480 // Initialize all "by copy" arguments.
3481 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003482 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003483 E = BlockByCopyDecls.end(); I != E; ++I) {
3484 std::string Name = (*I)->getNameAsString();
3485 if (firsTime) {
3486 Constructor += " : ";
3487 firsTime = false;
3488 }
3489 else
3490 Constructor += ", ";
3491 if (isTopLevelBlockPointerType((*I)->getType()))
3492 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3493 else
3494 Constructor += Name + "(_" + Name + ")";
3495 }
3496 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003497 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003498 E = BlockByRefDecls.end(); I != E; ++I) {
3499 std::string Name = (*I)->getNameAsString();
3500 if (firsTime) {
3501 Constructor += " : ";
3502 firsTime = false;
3503 }
3504 else
3505 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003506 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003507 }
3508
3509 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003510 if (GlobalVarDecl)
3511 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3512 else
3513 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003514 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003515
Steve Naroff30484702009-12-06 21:14:13 +00003516 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003517 } else {
3518 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003519 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003520 if (GlobalVarDecl)
3521 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3522 else
3523 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003524 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3525 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003526 }
3527 Constructor += " ";
3528 Constructor += "}\n";
3529 S += Constructor;
3530 S += "};\n";
3531 return S;
3532}
3533
Steve Naroff30484702009-12-06 21:14:13 +00003534std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3535 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003536 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003537 unsigned hasCopy) {
3538 std::string S = "\nstatic struct " + DescTag;
3539
3540 S += " {\n unsigned long reserved;\n";
3541 S += " unsigned long Block_size;\n";
3542 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003543 S += " void (*copy)(struct ";
3544 S += ImplTag; S += "*, struct ";
3545 S += ImplTag; S += "*);\n";
3546
3547 S += " void (*dispose)(struct ";
3548 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003549 }
3550 S += "} ";
3551
3552 S += DescTag + "_DATA = { 0, sizeof(struct ";
3553 S += ImplTag + ")";
3554 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003555 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3556 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003557 }
3558 S += "};\n";
3559 return S;
3560}
3561
Steve Naroff677ab3a2008-10-27 17:20:55 +00003562void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003563 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003564 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003565 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003566 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003567 bool RewriteSC = (GlobalVarDecl &&
3568 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003569 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003570 GlobalVarDecl->getType().getCVRQualifiers());
3571 if (RewriteSC) {
3572 std::string SC(" void __");
3573 SC += GlobalVarDecl->getNameAsString();
3574 SC += "() {}";
3575 InsertText(FunLocStart, SC);
3576 }
3577
Steve Naroff677ab3a2008-10-27 17:20:55 +00003578 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003579 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3580 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003581 // Need to copy-in the inner copied-in variables not actually used in this
3582 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003583 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003584 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003585 ValueDecl *VD = Exp->getDecl();
3586 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003587 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003588 BlockByCopyDeclsPtrSet.insert(VD);
3589 BlockByCopyDecls.push_back(VD);
3590 }
John McCall113bee02012-03-10 09:33:50 +00003591 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003592 BlockByRefDeclsPtrSet.insert(VD);
3593 BlockByRefDecls.push_back(VD);
3594 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003595 // imported objects in the inner blocks not used in the outer
3596 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003597 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003598 VD->getType()->isObjCObjectPointerType() ||
3599 VD->getType()->isBlockPointerType())
3600 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003601 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003602
Daniel Dunbar56df9772010-08-17 22:39:59 +00003603 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3604 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003605
Steve Naroff30484702009-12-06 21:14:13 +00003606 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003607
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003608 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003609
Steve Naroff30484702009-12-06 21:14:13 +00003610 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003611
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003612 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003613
3614 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003615 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003616 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003617 }
Steve Naroff30484702009-12-06 21:14:13 +00003618 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3619 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003620 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003621
Steve Naroff677ab3a2008-10-27 17:20:55 +00003622 BlockDeclRefs.clear();
3623 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003624 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003625 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003626 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003627 ImportedBlockDecls.clear();
3628 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003629 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003630 // Must insert any 'const/volatile/static here. Since it has been
3631 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003632 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003633 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003634 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003635 if (GlobalVarDecl->getType().isConstQualified())
3636 SC += "const ";
3637 if (GlobalVarDecl->getType().isVolatileQualified())
3638 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003639 if (GlobalVarDecl->getType().isRestrictQualified())
3640 SC += "restrict ";
3641 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003642 }
3643
Steve Naroff677ab3a2008-10-27 17:20:55 +00003644 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003645 InnerDeclRefsCount.clear();
3646 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003647 RewrittenBlockExprs.clear();
3648}
3649
3650void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3651 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003652 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003653
Steve Naroff677ab3a2008-10-27 17:20:55 +00003654 SynthesizeBlockLiterals(FunLocStart, FuncName);
3655}
3656
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003657static void BuildUniqueMethodName(std::string &Name,
3658 ObjCMethodDecl *MD) {
3659 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003660 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003661 Name += "__" + MD->getSelector().getAsString();
3662 // Convert colons to underscores.
3663 std::string::size_type loc = 0;
3664 while ((loc = Name.find(":", loc)) != std::string::npos)
3665 Name.replace(loc, 1, "_");
3666}
3667
Steve Naroff677ab3a2008-10-27 17:20:55 +00003668void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003669 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3670 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003671 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003672 std::string FuncName;
3673 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003674 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003675}
3676
3677void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00003678 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00003679 if (*CI) {
3680 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3681 GetBlockDeclRefExprs(CBE->getBody());
3682 else
3683 GetBlockDeclRefExprs(*CI);
3684 }
3685 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003686 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3687 if (DRE->refersToEnclosingLocal()) {
3688 // FIXME: Handle enums.
3689 if (!isa<FunctionDecl>(DRE->getDecl()))
3690 BlockDeclRefs.push_back(DRE);
3691 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3692 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003693 }
John McCall113bee02012-03-10 09:33:50 +00003694 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003695
Steve Naroff677ab3a2008-10-27 17:20:55 +00003696 return;
3697}
3698
Craig Topper5603df42013-07-05 19:34:19 +00003699void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3700 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003701 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00003702 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003703 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003704 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3705 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003706 GetInnerBlockDeclRefExprs(CBE->getBody(),
3707 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003708 InnerContexts);
3709 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003710 else
3711 GetInnerBlockDeclRefExprs(*CI,
3712 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003713 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003714
3715 }
3716 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3718 if (DRE->refersToEnclosingLocal()) {
3719 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3720 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3721 InnerBlockDeclRefs.push_back(DRE);
3722 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3723 if (Var->isFunctionOrMethodVarDecl())
3724 ImportedLocalExternalDecls.insert(Var);
3725 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003726 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003727
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003728 return;
3729}
3730
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003731/// convertFunctionTypeOfBlocks - This routine converts a function type
3732/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003733/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003734/// all block pointers to function pointers.
3735QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3736 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3737 // FTP will be null for closures that don't take arguments.
3738 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003739 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003740 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003741 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003742
3743 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003744 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3745 E = FTP->param_type_end();
3746 I && (I != E); ++I) {
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003747 QualType t = *I;
3748 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003749 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003750 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003751 ArgTypes.push_back(t);
3752 }
3753 }
3754 QualType FuncType;
3755 // FIXME. Does this work if block takes no argument but has a return type
3756 // which is of block type?
3757 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003758 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003759 else FuncType = QualType(FT, 0);
3760 return FuncType;
3761}
3762
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003763Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003765 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003766
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003767 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003768 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003769 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003770 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003771 }
3772 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3773 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3774 }
3775 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3776 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3777 else if (const ConditionalOperator *CEXPR =
3778 dyn_cast<ConditionalOperator>(BlockExp)) {
3779 Expr *LHSExp = CEXPR->getLHS();
3780 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3781 Expr *RHSExp = CEXPR->getRHS();
3782 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3783 Expr *CONDExp = CEXPR->getCond();
3784 ConditionalOperator *CondExpr =
3785 new (Context) ConditionalOperator(CONDExp,
3786 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003787 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003788 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003789 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003790 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3791 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003792 } else if (const PseudoObjectExpr *POE
3793 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3794 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003795 } else {
3796 assert(1 && "RewriteBlockClass: Bad type");
3797 }
3798 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003799 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003800 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003801 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003802 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003803
Abramo Bagnara6150c882010-05-11 21:36:43 +00003804 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003805 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003806 &Context->Idents.get("__block_impl"));
3807 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003808
Steve Naroff350b6652008-10-30 10:07:53 +00003809 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003810 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003811
Steve Naroff350b6652008-10-30 10:07:53 +00003812 // Push the block argument type.
3813 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003815 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3816 E = FTP->param_type_end();
3817 I && (I != E); ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003818 QualType t = *I;
3819 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003820 if (!convertBlockPointerToFunctionPointer(t))
3821 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003822 ArgTypes.push_back(t);
3823 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003824 }
Steve Naroff350b6652008-10-30 10:07:53 +00003825 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003826 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003827
Steve Naroff350b6652008-10-30 10:07:53 +00003828 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003829
John McCall97513962010-01-15 18:39:57 +00003830 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003831 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003832 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003833 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003834 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3835 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003836 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003837
Douglas Gregor91f84212008-12-11 16:49:14 +00003838 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003839 SourceLocation(),
3840 &Context->Idents.get("FuncPtr"),
3841 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003842 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003843 ICIS_NoInit);
Ted Kremenek5a201952009-02-07 01:47:29 +00003844 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003845 FD->getType(), VK_LValue,
3846 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00003847
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003848
John McCall97513962010-01-15 18:39:57 +00003849 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00003850 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00003851 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003852
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003853 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003854 // Add the implicit argument.
3855 BlkExprs.push_back(BlkCast);
3856 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003857 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003859 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003860 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003861 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003862 Exp->getType(), VK_RValue,
3863 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003864 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865}
3866
Steve Naroffd9803712009-04-29 16:37:50 +00003867// We need to return the rewritten expression to handle cases where the
3868// BlockDeclRefExpr is embedded in another expression being rewritten.
3869// For example:
3870//
3871// int main() {
3872// __block Foo *f;
3873// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003874//
Steve Naroffd9803712009-04-29 16:37:50 +00003875// void (^myblock)() = ^() {
3876// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3877// i = 77;
3878// };
3879//}
John McCall113bee02012-03-10 09:33:50 +00003880Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003881 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003882 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003883 ValueDecl *VD = DeclRefExp->getDecl();
3884 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003885
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003886 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003887 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003888 &Context->Idents.get("__forwarding"),
3889 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003890 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003891 ICIS_NoInit);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003892 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3893 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003894 FD->getType(), VK_LValue,
3895 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003896
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003897 StringRef Name = VD->getName();
Abramo Bagnaradff19302011-03-08 08:55:46 +00003898 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003899 &Context->Idents.get(Name),
3900 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003901 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003902 ICIS_NoInit);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003903 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003904 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003905
3906
3907
Steve Narofff26a1d42009-02-02 17:19:26 +00003908 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00003909 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3910 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003911 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003912 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003913 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003914}
3915
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003916// Rewrites the imported local variable V with external storage
3917// (static, extern, etc.) as *V
3918//
3919Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3920 ValueDecl *VD = DRE->getDecl();
3921 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3922 if (!ImportedLocalExternalDecls.count(Var))
3923 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003924 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3925 VK_LValue, OK_Ordinary,
3926 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003927 // Need parens to enforce precedence.
3928 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3929 Exp);
3930 ReplaceStmt(DRE, PE);
3931 return PE;
3932}
3933
Steve Naroffc989a7b2008-11-03 23:29:32 +00003934void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3935 SourceLocation LocStart = CE->getLParenLoc();
3936 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003937
3938 // Need to avoid trying to rewrite synthesized casts.
3939 if (LocStart.isInvalid())
3940 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003941 // Need to avoid trying to rewrite casts contained in macros.
3942 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3943 return;
Mike Stump11289f42009-09-09 15:08:12 +00003944
Steve Naroff677ab3a2008-10-27 17:20:55 +00003945 const char *startBuf = SM->getCharacterData(LocStart);
3946 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003947 QualType QT = CE->getType();
3948 const Type* TypePtr = QT->getAs<Type>();
3949 if (isa<TypeOfExprType>(TypePtr)) {
3950 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3951 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3952 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003953 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003954 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003955 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003956 return;
3957 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958 // advance the location to startArgList.
3959 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003960
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 while (*argPtr++ && (argPtr < endBuf)) {
3962 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003963 case '^':
3964 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003965 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003966 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003967 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003968 }
3969 }
3970 return;
3971}
3972
3973void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3974 SourceLocation DeclLoc = FD->getLocation();
3975 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003976
Steve Naroff677ab3a2008-10-27 17:20:55 +00003977 // We have 1 or more arguments that have closure pointers.
3978 const char *startBuf = SM->getCharacterData(DeclLoc);
3979 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003980
Steve Naroff677ab3a2008-10-27 17:20:55 +00003981 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003982
Steve Naroff677ab3a2008-10-27 17:20:55 +00003983 parenCount++;
3984 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003985 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003986 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00003987
Steve Naroff677ab3a2008-10-27 17:20:55 +00003988 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Steve Naroff677ab3a2008-10-27 17:20:55 +00003990 while (*argPtr++ && parenCount) {
3991 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003992 case '^':
3993 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003994 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003995 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003996 break;
3997 case '(':
3998 parenCount++;
3999 break;
4000 case ')':
4001 parenCount--;
4002 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 }
4004 }
4005 return;
4006}
4007
4008bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004009 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004010 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004012 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004013 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004014 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004015 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004016 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004017 }
4018 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004019 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4020 E = FTP->param_type_end();
4021 I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004022 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004023 return true;
4024 }
4025 return false;
4026}
4027
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004028bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4029 const FunctionProtoType *FTP;
4030 const PointerType *PT = QT->getAs<PointerType>();
4031 if (PT) {
4032 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4033 } else {
4034 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4035 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4036 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4037 }
4038 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004039 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4040 E = FTP->param_type_end();
4041 I != E; ++I) {
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004042 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004043 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004044 if ((*I)->isObjCObjectPointerType() &&
4045 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4046 return true;
4047 }
4048
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004049 }
4050 return false;
4051}
4052
Ted Kremenek5a201952009-02-07 01:47:29 +00004053void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4054 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004055 const char *argPtr = strchr(Name, '(');
4056 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004057
Steve Naroff677ab3a2008-10-27 17:20:55 +00004058 LParen = argPtr; // output the start.
4059 argPtr++; // skip past the left paren.
4060 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004061
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 while (*argPtr && parenCount) {
4063 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004064 case '(': parenCount++; break;
4065 case ')': parenCount--; break;
4066 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004067 }
4068 if (parenCount) argPtr++;
4069 }
4070 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4071 RParen = argPtr; // output the end
4072}
4073
4074void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4076 RewriteBlockPointerFunctionArgs(FD);
4077 return;
Mike Stump11289f42009-09-09 15:08:12 +00004078 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 // Handle Variables and Typedefs.
4080 SourceLocation DeclLoc = ND->getLocation();
4081 QualType DeclT;
4082 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4083 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004084 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004085 DeclT = TDD->getUnderlyingType();
4086 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4087 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004088 else
David Blaikie83d382b2011-09-23 05:06:16 +00004089 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004090
Steve Naroff677ab3a2008-10-27 17:20:55 +00004091 const char *startBuf = SM->getCharacterData(DeclLoc);
4092 const char *endBuf = startBuf;
4093 // scan backward (from the decl location) for the end of the previous decl.
4094 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4095 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004096 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004097 std::string buf;
4098 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004099 // *startBuf != '^' if we are dealing with a pointer to function that
4100 // may take block argument types (which will be handled below).
4101 if (*startBuf == '^') {
4102 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004103 buf = '*';
4104 startBuf++;
4105 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004106 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004107 while (*startBuf != ')') {
4108 buf += *startBuf;
4109 startBuf++;
4110 OrigLength++;
4111 }
4112 buf += ')';
4113 OrigLength++;
4114
4115 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4116 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004118 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 DeclLoc = ND->getLocation();
4120 startBuf = SM->getCharacterData(DeclLoc);
4121 const char *argListBegin, *argListEnd;
4122 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4123 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004124 if (*argListBegin == '^')
4125 buf += '*';
4126 else if (*argListBegin == '<') {
4127 buf += "/*";
4128 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004129 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004130 while (*argListBegin != '>') {
4131 buf += *argListBegin++;
4132 OrigLength++;
4133 }
4134 buf += *argListBegin;
4135 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004137 else
4138 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004140 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004142 buf += ')';
4143 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004144 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004145 ReplaceText(Start, OrigLength, buf);
4146
Steve Naroff677ab3a2008-10-27 17:20:55 +00004147 return;
4148}
4149
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004150
4151/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4152/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4153/// struct Block_byref_id_object *src) {
4154/// _Block_object_assign (&_dest->object, _src->object,
4155/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4156/// [|BLOCK_FIELD_IS_WEAK]) // object
4157/// _Block_object_assign(&_dest->object, _src->object,
4158/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4159/// [|BLOCK_FIELD_IS_WEAK]) // block
4160/// }
4161/// And:
4162/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4163/// _Block_object_dispose(_src->object,
4164/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4165/// [|BLOCK_FIELD_IS_WEAK]) // object
4166/// _Block_object_dispose(_src->object,
4167/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4168/// [|BLOCK_FIELD_IS_WEAK]) // block
4169/// }
4170
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004171std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4172 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004173 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004174 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004175 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004176 CopyDestroyCache.insert(flag);
4177 S = "static void __Block_byref_id_object_copy_";
4178 S += utostr(flag);
4179 S += "(void *dst, void *src) {\n";
4180
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004181 // offset into the object pointer is computed as:
4182 // void * + void* + int + int + void* + void *
4183 unsigned IntSize =
4184 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4185 unsigned VoidPtrSize =
4186 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4187
Ken Dyckd9c83e62011-04-30 16:08:27 +00004188 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004189 S += " _Block_object_assign((char*)dst + ";
4190 S += utostr(offset);
4191 S += ", *(void * *) ((char*)src + ";
4192 S += utostr(offset);
4193 S += "), ";
4194 S += utostr(flag);
4195 S += ");\n}\n";
4196
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004197 S += "static void __Block_byref_id_object_dispose_";
4198 S += utostr(flag);
4199 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004200 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4201 S += utostr(offset);
4202 S += "), ";
4203 S += utostr(flag);
4204 S += ");\n}\n";
4205 return S;
4206}
4207
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004208/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4209/// the declaration into:
4210/// struct __Block_byref_ND {
4211/// void *__isa; // NULL for everything except __weak pointers
4212/// struct __Block_byref_ND *__forwarding;
4213/// int32_t __flags;
4214/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004215/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4216/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004217/// typex ND;
4218/// };
4219///
4220/// It then replaces declaration of ND variable with:
4221/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4222/// __size=sizeof(struct __Block_byref_ND),
4223/// ND=initializer-if-any};
4224///
4225///
4226void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004227 // Insert declaration for the function in which block literal is
4228 // used.
4229 if (CurFunctionDeclToDeclareForBlock)
4230 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004231 int flag = 0;
4232 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004233 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004234 if (DeclLoc.isInvalid())
4235 // If type location is missing, it is because of missing type (a warning).
4236 // Use variable's location which is good for this case.
4237 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004238 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004239 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004240 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004241 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004242 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004243 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004244 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004245 ByrefType += " {\n";
4246 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004247 RewriteByRefString(ByrefType, Name, ND);
4248 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004249 ByrefType += " int __flags;\n";
4250 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004251 // Add void *__Block_byref_id_object_copy;
4252 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004253 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004254 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004255 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004256 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4257 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004258 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004259
4260 QualType T = Ty;
4261 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004262 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004263
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004264 ByrefType += " " + Name + ";\n";
4265 ByrefType += "};\n";
4266 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004267 SourceLocation FunLocStart;
4268 if (CurFunctionDef)
4269 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4270 else {
4271 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4272 FunLocStart = CurMethodDef->getLocStart();
4273 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004274 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004275 if (Ty.isObjCGCWeak()) {
4276 flag |= BLOCK_FIELD_IS_WEAK;
4277 isa = 1;
4278 }
4279
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004280 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004281 flag = BLOCK_BYREF_CALLER;
4282 QualType Ty = ND->getType();
4283 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4284 if (Ty->isBlockPointerType())
4285 flag |= BLOCK_FIELD_IS_BLOCK;
4286 else
4287 flag |= BLOCK_FIELD_IS_OBJECT;
4288 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004289 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004290 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004291 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004292
4293 // struct __Block_byref_ND ND =
4294 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4295 // initializer-if-any};
4296 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004297 unsigned flags = 0;
4298 if (HasCopyAndDispose)
4299 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004300 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004301 ByrefType.clear();
4302 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004303 std::string ForwardingCastType("(");
4304 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004305 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004306 ByrefType += " " + Name + " = {(void*)";
4307 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004308 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004309 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004310 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004311 ByrefType += "sizeof(";
4312 RewriteByRefString(ByrefType, Name, ND);
4313 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004314 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004315 ByrefType += ", __Block_byref_id_object_copy_";
4316 ByrefType += utostr(flag);
4317 ByrefType += ", __Block_byref_id_object_dispose_";
4318 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004319 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004320 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004321 unsigned nameSize = Name.size();
4322 // for block or function pointer declaration. Name is aleady
4323 // part of the declaration.
4324 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4325 nameSize = 1;
4326 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004327 }
4328 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004329 SourceLocation startLoc;
4330 Expr *E = ND->getInit();
4331 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4332 startLoc = ECE->getLParenLoc();
4333 else
4334 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004335 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004336 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004337 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004338 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004339 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004340 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004341 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004342 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004343 ByrefType += "sizeof(";
4344 RewriteByRefString(ByrefType, Name, ND);
4345 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004346 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004347 ByrefType += "__Block_byref_id_object_copy_";
4348 ByrefType += utostr(flag);
4349 ByrefType += ", __Block_byref_id_object_dispose_";
4350 ByrefType += utostr(flag);
4351 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004352 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004353 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004354
4355 // Complete the newly synthesized compound expression by inserting a right
4356 // curly brace before the end of the declaration.
4357 // FIXME: This approach avoids rewriting the initializer expression. It
4358 // also assumes there is only one declarator. For example, the following
4359 // isn't currently supported by this routine (in general):
4360 //
4361 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4362 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004363 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4364 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004365 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4366 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004367 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004368
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004369 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004370 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004371 return;
4372}
4373
Mike Stump11289f42009-09-09 15:08:12 +00004374void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004375 // Add initializers for any closure decl refs.
4376 GetBlockDeclRefExprs(Exp->getBody());
4377 if (BlockDeclRefs.size()) {
4378 // Unique all "by copy" declarations.
4379 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004380 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004381 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4382 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4383 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4384 }
4385 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004386 // Unique all "by ref" declarations.
4387 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004388 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004389 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4390 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4391 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4392 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004393 }
4394 // Find any imported blocks...they will need special attention.
4395 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004396 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004397 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004398 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004399 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004400 }
4401}
4402
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004403FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004404 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004405 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004406 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4407 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004408 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004409}
4410
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004411Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004412 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004413 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004414 Blocks.push_back(Exp);
4415
4416 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004417
4418 // Add inner imported variables now used in current block.
4419 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004420 if (!InnerBlockDeclRefs.empty()) {
4421 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004422 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004423 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004424 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004425 // We need to save the copied-in variables in nested
4426 // blocks because it is needed at the end for some of the API generations.
4427 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004428 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4429 BlockDeclRefs.push_back(Exp);
4430 BlockByCopyDeclsPtrSet.insert(VD);
4431 BlockByCopyDecls.push_back(VD);
4432 }
John McCall113bee02012-03-10 09:33:50 +00004433 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004434 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4435 BlockDeclRefs.push_back(Exp);
4436 BlockByRefDeclsPtrSet.insert(VD);
4437 BlockByRefDecls.push_back(VD);
4438 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004439 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004440 // Find any imported blocks...they will need special attention.
4441 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004442 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004443 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4444 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4445 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004446 }
4447 InnerDeclRefsCount.push_back(countOfInnerDecls);
4448
Steve Narofff4b992a2008-10-28 20:29:00 +00004449 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004450
Steve Narofff4b992a2008-10-28 20:29:00 +00004451 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004452 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004453 else if (CurMethodDef)
4454 BuildUniqueMethodName(FuncName, CurMethodDef);
4455 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004456 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004457
Steve Narofff4b992a2008-10-28 20:29:00 +00004458 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004459
Steve Narofff4b992a2008-10-28 20:29:00 +00004460 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4461 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004462
Steve Narofff4b992a2008-10-28 20:29:00 +00004463 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004464 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4465 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004466
4467 FunctionDecl *FD;
4468 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004469
Benjamin Kramer60509af2013-09-09 14:48:42 +00004470 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004471 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004472 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004473 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004474
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004475 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004476
Steve Naroffe2514232008-10-29 21:23:59 +00004477 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004478 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004479 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4480 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004481 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004482 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004483 InitExprs.push_back(castExpr);
4484
Steve Naroff30484702009-12-06 21:14:13 +00004485 // Initialize the block descriptor.
4486 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004487
Abramo Bagnaradff19302011-03-08 08:55:46 +00004488 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4489 SourceLocation(), SourceLocation(),
4490 &Context->Idents.get(DescData.c_str()),
4491 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004492 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004493 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004494 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004495 Context->VoidPtrTy,
4496 VK_LValue,
4497 SourceLocation()),
4498 UO_AddrOf,
4499 Context->getPointerType(Context->VoidPtrTy),
4500 VK_RValue, OK_Ordinary,
4501 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004502 InitExprs.push_back(DescRefExpr);
4503
Steve Narofff4b992a2008-10-28 20:29:00 +00004504 // Add initializers for any closure decl refs.
4505 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004506 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004507 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004508 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004509 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004510 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004511 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004512 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004513 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004514 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004515 if (HasLocalVariableExternalStorage(*I)) {
4516 QualType QT = (*I)->getType();
4517 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004518 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4519 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004520 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004521 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004522 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004523 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004524 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004525 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004526 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004527 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004528 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004529 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004530 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004531 if (HasLocalVariableExternalStorage(*I)) {
4532 QualType QT = (*I)->getType();
4533 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004534 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4535 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004536 }
4537
Steve Narofff4b992a2008-10-28 20:29:00 +00004538 }
Mike Stump11289f42009-09-09 15:08:12 +00004539 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004540 }
4541 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004542 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004543 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004544 ValueDecl *ND = (*I);
4545 std::string Name(ND->getNameAsString());
4546 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004547 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004548 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4549 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004550 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004551 SourceLocation(), SourceLocation(),
4552 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004553 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4554 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4555
Daniel Dunbar56df9772010-08-17 22:39:59 +00004556 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004557 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004558 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004559 bool isNestedCapturedVar = false;
4560 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00004561 for (const auto &CI : block->captures()) {
4562 const VarDecl *variable = CI.getVariable();
4563 if (variable == ND && CI.isNested()) {
4564 assert (CI.isByRef() &&
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004565 "SynthBlockInitExpr - captured block variable is not byref");
4566 isNestedCapturedVar = true;
4567 break;
4568 }
4569 }
4570 // captured nested byref variable has its address passed. Do not take
4571 // its address again.
4572 if (!isNestedCapturedVar)
4573 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004574 Context->getPointerType(Exp->getType()),
4575 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004576 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004577 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004578 }
4579 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004580 if (ImportedBlockDecls.size()) {
4581 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4582 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004583 unsigned IntSize =
4584 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004585 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4586 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004587 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004588 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004589 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004590 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004591 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004592 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004593 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004594 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004595 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 BlockDeclRefs.clear();
4597 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004598 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004599 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004600 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004601 ImportedBlockDecls.clear();
4602 return NewRep;
4603}
4604
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004605bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4606 if (const ObjCForCollectionStmt * CS =
4607 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4608 return CS->getElement() == DS;
4609 return false;
4610}
4611
Steve Narofff4b992a2008-10-28 20:29:00 +00004612//===----------------------------------------------------------------------===//
4613// Function Body / Expression rewriting
4614//===----------------------------------------------------------------------===//
4615
4616Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004617 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 isa<DoStmt>(S) || isa<ForStmt>(S))
4619 Stmts.push_back(S);
4620 else if (isa<ObjCForCollectionStmt>(S)) {
4621 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004622 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
John McCallfe96e0b2011-11-06 09:01:30 +00004625 // Pseudo-object operations and ivar references need special
4626 // treatment because we're going to recursively rewrite them.
4627 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4628 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4629 return RewritePropertyOrImplicitSetter(PseudoOp);
4630 } else {
4631 return RewritePropertyOrImplicitGetter(PseudoOp);
4632 }
4633 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4634 return RewriteObjCIvarRefExpr(IvarRefExpr);
4635 }
4636
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004638
Steve Narofff4b992a2008-10-28 20:29:00 +00004639 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00004640 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00004641 if (*CI) {
John McCallfe96e0b2011-11-06 09:01:30 +00004642 Stmt *childStmt = (*CI);
4643 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004644 if (newStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004645 *CI = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004646 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004647 }
Mike Stump11289f42009-09-09 15:08:12 +00004648
Steve Narofff4b992a2008-10-28 20:29:00 +00004649 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004650 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004651 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4652 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004653 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004654 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004655 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004656 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004657 Stmt *SaveCurrentBody = CurrentBody;
4658 CurrentBody = BE->getBody();
4659 PropParentMap = 0;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004660 // block literal on rhs of a property-dot-sytax assignment
4661 // must be replaced by its synthesize ast so getRewrittenText
4662 // works as expected. In this case, what actually ends up on RHS
4663 // is the blockTranscribed which is the helper function for the
4664 // block literal; as in: self.c = ^() {[ace ARR];};
4665 bool saveDisableReplaceStmt = DisableReplaceStmt;
4666 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004667 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004668 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004669 CurrentBody = SaveCurrentBody;
4670 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004671 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004672 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004673 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004674 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004675
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004676 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4677
Steve Narofff4b992a2008-10-28 20:29:00 +00004678 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004679 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004680 return blockTranscribed;
4681 }
4682 // Handle specific things.
4683 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4684 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004685
Steve Narofff4b992a2008-10-28 20:29:00 +00004686 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4687 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004688
Steve Narofff4b992a2008-10-28 20:29:00 +00004689 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4690 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004691
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004693#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 // Before we rewrite it, put the original message expression in a comment.
4695 SourceLocation startLoc = MessExpr->getLocStart();
4696 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004697
Steve Narofff4b992a2008-10-28 20:29:00 +00004698 const char *startBuf = SM->getCharacterData(startLoc);
4699 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004700
Steve Narofff4b992a2008-10-28 20:29:00 +00004701 std::string messString;
4702 messString += "// ";
4703 messString.append(startBuf, endBuf-startBuf+1);
4704 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004705
4706 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 // InsertText(clang::SourceLocation, char const*, unsigned int).
4708 // InsertText(startLoc, messString.c_str(), messString.size());
4709 // Tried this, but it didn't work either...
4710 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004711#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 return RewriteMessageExpr(MessExpr);
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Steve Narofff4b992a2008-10-28 20:29:00 +00004715 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4716 return RewriteObjCTryStmt(StmtTry);
4717
4718 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4719 return RewriteObjCSynchronizedStmt(StmtTry);
4720
4721 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4722 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004723
Steve Narofff4b992a2008-10-28 20:29:00 +00004724 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4725 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004726
4727 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004728 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004729 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004730 OrigStmtRange.getEnd());
4731 if (BreakStmt *StmtBreakStmt =
4732 dyn_cast<BreakStmt>(S))
4733 return RewriteBreakStmt(StmtBreakStmt);
4734 if (ContinueStmt *StmtContinueStmt =
4735 dyn_cast<ContinueStmt>(S))
4736 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004737
4738 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004739 // and cast exprs.
4740 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4741 // FIXME: What we're doing here is modifying the type-specifier that
4742 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004743 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004744 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4745 // the context of an ObjCForCollectionStmt. For example:
4746 // NSArray *someArray;
4747 // for (id <FooProtocol> index in someArray) ;
4748 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4749 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004750 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004751 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004752
Steve Narofff4b992a2008-10-28 20:29:00 +00004753 // Blocks rewrite rules.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004754 for (auto *SD : DS->decls()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004755 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004756 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004758 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004759 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004760 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004761 if (VD->hasAttr<BlocksAttr>()) {
4762 static unsigned uniqueByrefDeclCount = 0;
4763 assert(!BlockByRefDeclNo.count(ND) &&
4764 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4765 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004766 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004767 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004768 else
4769 RewriteTypeOfDecl(VD);
4770 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004771 }
Richard Smithdda56e42011-04-15 14:24:37 +00004772 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004773 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004774 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004775 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4777 }
4778 }
4779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4782 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004783
4784 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004785 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4786 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004787 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4788 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004789 && "Statement stack mismatch");
4790 Stmts.pop_back();
4791 }
4792 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004793 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4794 ValueDecl *VD = DRE->getDecl();
4795 if (VD->hasAttr<BlocksAttr>())
4796 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004797 if (HasLocalVariableExternalStorage(VD))
4798 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004799 }
4800
Steve Narofff4b992a2008-10-28 20:29:00 +00004801 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004802 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004803 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004804 ReplaceStmt(S, BlockCall);
4805 return BlockCall;
4806 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004808 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 RewriteCastExpr(CE);
4810 }
4811#if 0
4812 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004813 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4814 ICE->getSubExpr(),
4815 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004816 // Get the new text.
4817 std::string SStr;
4818 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004819 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004820 const std::string &Str = Buf.str();
4821
4822 printf("CAST = %s\n", &Str[0]);
4823 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4824 delete S;
4825 return Replacement;
4826 }
4827#endif
4828 // Return this stmt unmodified.
4829 return S;
4830}
4831
Steve Naroffe70a52a2009-12-05 15:55:59 +00004832void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004833 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004834 if (isTopLevelBlockPointerType(FD->getType()))
4835 RewriteBlockPointerDecl(FD);
4836 if (FD->getType()->isObjCQualifiedIdType() ||
4837 FD->getType()->isObjCQualifiedInterfaceType())
4838 RewriteObjCQualifiedInterfaceTypes(FD);
4839 }
4840}
4841
Steve Narofff4b992a2008-10-28 20:29:00 +00004842/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4843/// main file of the input.
4844void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004845 switch (D->getKind()) {
4846 case Decl::Function: {
4847 FunctionDecl *FD = cast<FunctionDecl>(D);
4848 if (FD->isOverloadedOperator())
4849 return;
Mike Stump11289f42009-09-09 15:08:12 +00004850
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004851 // Since function prototypes don't have ParmDecl's, we check the function
4852 // prototype. This enables us to rewrite function declarations and
4853 // definitions using the same code.
4854 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004855
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004856 if (!FD->isThisDeclarationADefinition())
4857 break;
4858
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004859 // FIXME: If this should support Obj-C++, support CXXTryStmt
4860 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4861 CurFunctionDef = FD;
4862 CurFunctionDeclToDeclareForBlock = FD;
4863 CurrentBody = Body;
4864 Body =
4865 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4866 FD->setBody(Body);
4867 CurrentBody = 0;
4868 if (PropParentMap) {
4869 delete PropParentMap;
4870 PropParentMap = 0;
4871 }
4872 // This synthesizes and inserts the block "impl" struct, invoke function,
4873 // and any copy/dispose helper functions.
4874 InsertBlockLiteralsWithinFunction(FD);
4875 CurFunctionDef = 0;
4876 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004877 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004878 break;
Mike Stump11289f42009-09-09 15:08:12 +00004879 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004880 case Decl::ObjCMethod: {
4881 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4882 if (CompoundStmt *Body = MD->getCompoundBody()) {
4883 CurMethodDef = MD;
4884 CurrentBody = Body;
4885 Body =
4886 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4887 MD->setBody(Body);
4888 CurrentBody = 0;
4889 if (PropParentMap) {
4890 delete PropParentMap;
4891 PropParentMap = 0;
4892 }
4893 InsertBlockLiteralsWithinMethod(MD);
4894 CurMethodDef = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004895 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004896 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004897 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004898 case Decl::ObjCImplementation: {
4899 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4900 ClassImplementation.push_back(CI);
4901 break;
4902 }
4903 case Decl::ObjCCategoryImpl: {
4904 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4905 CategoryImplementation.push_back(CI);
4906 break;
4907 }
4908 case Decl::Var: {
4909 VarDecl *VD = cast<VarDecl>(D);
4910 RewriteObjCQualifiedInterfaceTypes(VD);
4911 if (isTopLevelBlockPointerType(VD->getType()))
4912 RewriteBlockPointerDecl(VD);
4913 else if (VD->getType()->isFunctionPointerType()) {
4914 CheckFunctionPointerDecl(VD->getType(), VD);
4915 if (VD->getInit()) {
4916 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4917 RewriteCastExpr(CE);
4918 }
4919 }
4920 } else if (VD->getType()->isRecordType()) {
4921 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4922 if (RD->isCompleteDefinition())
4923 RewriteRecordBody(RD);
4924 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004926 GlobalVarDecl = VD;
4927 CurrentBody = VD->getInit();
4928 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4929 CurrentBody = 0;
4930 if (PropParentMap) {
4931 delete PropParentMap;
4932 PropParentMap = 0;
4933 }
4934 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4935 GlobalVarDecl = 0;
4936
4937 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004938 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004939 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004940 }
4941 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004942 break;
4943 }
4944 case Decl::TypeAlias:
4945 case Decl::Typedef: {
4946 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4947 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4948 RewriteBlockPointerDecl(TD);
4949 else if (TD->getUnderlyingType()->isFunctionPointerType())
4950 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4951 }
4952 break;
4953 }
4954 case Decl::CXXRecord:
4955 case Decl::Record: {
4956 RecordDecl *RD = cast<RecordDecl>(D);
4957 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004958 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004959 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004961 default:
4962 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004963 }
4964 // Nothing yet.
4965}
4966
Chris Lattnercf169832009-03-28 04:11:33 +00004967void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004968 if (Diags.hasErrorOccurred())
4969 return;
Mike Stump11289f42009-09-09 15:08:12 +00004970
Steve Narofff4b992a2008-10-28 20:29:00 +00004971 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004972
Steve Naroffd9803712009-04-29 16:37:50 +00004973 // Here's a great place to add any extra declarations that may be needed.
4974 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004975 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004976 E = ProtocolExprDecls.end(); I != E; ++I)
4977 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4978
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004979 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004980 if (ClassImplementation.size() || CategoryImplementation.size())
4981 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004982
Steve Narofff4b992a2008-10-28 20:29:00 +00004983 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4984 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004985 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 Rewrite.getRewriteBufferFor(MainFileID)) {
4987 //printf("Changed:\n");
4988 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4989 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004990 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004992
Steve Naroffd9803712009-04-29 16:37:50 +00004993 if (ClassImplementation.size() || CategoryImplementation.size() ||
4994 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004995 // Rewrite Objective-c meta data*
4996 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00004997 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004998 // Emit metadata.
4999 *OutFile << ResultStr;
5000 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005001 OutFile->flush();
5002}
Fariborz Jahanian83077422011-12-08 18:25:15 +00005003
5004void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5005 InitializeCommon(context);
5006
5007 // declaring objc_selector outside the parameter list removes a silly
5008 // scope related warning...
5009 if (IsHeader)
5010 Preamble = "#pragma once\n";
5011 Preamble += "struct objc_selector; struct objc_class;\n";
5012 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5013 Preamble += "struct objc_object *superClass; ";
5014 if (LangOpts.MicrosoftExt) {
5015 // Add a constructor for creating temporary objects.
5016 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5017 ": ";
5018 Preamble += "object(o), superClass(s) {} ";
5019 }
5020 Preamble += "};\n";
5021 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5022 Preamble += "typedef struct objc_object Protocol;\n";
5023 Preamble += "#define _REWRITER_typedef_Protocol\n";
5024 Preamble += "#endif\n";
5025 if (LangOpts.MicrosoftExt) {
5026 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5027 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5028 } else
5029 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5030 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5031 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5032 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5033 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5034 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5035 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5036 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5037 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5039 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5040 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5041 Preamble += "(const char *);\n";
5042 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5043 Preamble += "(struct objc_class *);\n";
5044 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5045 Preamble += "(const char *);\n";
5046 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5047 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5048 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5049 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5050 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5051 Preamble += "(struct objc_class *, struct objc_object *);\n";
5052 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005053 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5054 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005055 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5056 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5057 Preamble += "struct __objcFastEnumerationState {\n\t";
5058 Preamble += "unsigned long state;\n\t";
5059 Preamble += "void **itemsPtr;\n\t";
5060 Preamble += "unsigned long *mutationsPtr;\n\t";
5061 Preamble += "unsigned long extra[5];\n};\n";
5062 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5063 Preamble += "#define __FASTENUMERATIONSTATE\n";
5064 Preamble += "#endif\n";
5065 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5066 Preamble += "struct __NSConstantStringImpl {\n";
5067 Preamble += " int *isa;\n";
5068 Preamble += " int flags;\n";
5069 Preamble += " char *str;\n";
5070 Preamble += " long length;\n";
5071 Preamble += "};\n";
5072 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5073 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5074 Preamble += "#else\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5076 Preamble += "#endif\n";
5077 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5078 Preamble += "#endif\n";
5079 // Blocks preamble.
5080 Preamble += "#ifndef BLOCK_IMPL\n";
5081 Preamble += "#define BLOCK_IMPL\n";
5082 Preamble += "struct __block_impl {\n";
5083 Preamble += " void *isa;\n";
5084 Preamble += " int Flags;\n";
5085 Preamble += " int Reserved;\n";
5086 Preamble += " void *FuncPtr;\n";
5087 Preamble += "};\n";
5088 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5089 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5090 Preamble += "extern \"C\" __declspec(dllexport) "
5091 "void _Block_object_assign(void *, const void *, const int);\n";
5092 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5093 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5094 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5095 Preamble += "#else\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5100 Preamble += "#endif\n";
5101 Preamble += "#endif\n";
5102 if (LangOpts.MicrosoftExt) {
5103 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5104 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5105 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5106 Preamble += "#define __attribute__(X)\n";
5107 Preamble += "#endif\n";
5108 Preamble += "#define __weak\n";
5109 }
5110 else {
5111 Preamble += "#define __block\n";
5112 Preamble += "#define __weak\n";
5113 }
5114 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5115 // as this avoids warning in any 64bit/32bit compilation model.
5116 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5117}
5118
5119/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5120/// ivar offset.
5121void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5122 std::string &Result) {
5123 if (ivar->isBitField()) {
5124 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5125 // place all bitfields at offset 0.
5126 Result += "0";
5127 } else {
5128 Result += "__OFFSETOFIVAR__(struct ";
5129 Result += ivar->getContainingInterface()->getNameAsString();
5130 if (LangOpts.MicrosoftExt)
5131 Result += "_IMPL";
5132 Result += ", ";
5133 Result += ivar->getNameAsString();
5134 Result += ")";
5135 }
5136}
5137
5138/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5139void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5140 ObjCProtocolDecl *PDecl, StringRef prefix,
5141 StringRef ClassName, std::string &Result) {
5142 static bool objc_protocol_methods = false;
5143
5144 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005145 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005146 /* struct protocol_methods {
5147 SEL _cmd;
5148 char *method_types;
5149 }
5150 */
5151 Result += "\nstruct _protocol_methods {\n";
5152 Result += "\tstruct objc_selector *_cmd;\n";
5153 Result += "\tchar *method_types;\n";
5154 Result += "};\n";
5155
5156 objc_protocol_methods = true;
5157 }
5158 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005159 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005160 return;
5161
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005162 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5163 PDecl = Def;
5164
Fariborz Jahanian83077422011-12-08 18:25:15 +00005165 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5166 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5167 PDecl->instmeth_end());
5168 /* struct _objc_protocol_method_list {
5169 int protocol_method_count;
5170 struct protocol_methods protocols[];
5171 }
5172 */
5173 Result += "\nstatic struct {\n";
5174 Result += "\tint protocol_method_count;\n";
5175 Result += "\tstruct _protocol_methods protocol_methods[";
5176 Result += utostr(NumMethods);
5177 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5178 Result += PDecl->getNameAsString();
5179 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5180 "{\n\t" + utostr(NumMethods) + "\n";
5181
5182 // Output instance methods declared in this protocol.
5183 for (ObjCProtocolDecl::instmeth_iterator
5184 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5185 I != E; ++I) {
5186 if (I == PDecl->instmeth_begin())
5187 Result += "\t ,{{(struct objc_selector *)\"";
5188 else
5189 Result += "\t ,{(struct objc_selector *)\"";
5190 Result += (*I)->getSelector().getAsString();
5191 std::string MethodTypeString;
5192 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5193 Result += "\", \"";
5194 Result += MethodTypeString;
5195 Result += "\"}\n";
5196 }
5197 Result += "\t }\n};\n";
5198 }
5199
5200 // Output class methods declared in this protocol.
5201 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5202 PDecl->classmeth_end());
5203 if (NumMethods > 0) {
5204 /* struct _objc_protocol_method_list {
5205 int protocol_method_count;
5206 struct protocol_methods protocols[];
5207 }
5208 */
5209 Result += "\nstatic struct {\n";
5210 Result += "\tint protocol_method_count;\n";
5211 Result += "\tstruct _protocol_methods protocol_methods[";
5212 Result += utostr(NumMethods);
5213 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5214 Result += PDecl->getNameAsString();
5215 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5216 "{\n\t";
5217 Result += utostr(NumMethods);
5218 Result += "\n";
5219
5220 // Output instance methods declared in this protocol.
5221 for (ObjCProtocolDecl::classmeth_iterator
5222 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5223 I != E; ++I) {
5224 if (I == PDecl->classmeth_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:
5239 /* struct _objc_protocol {
5240 // Objective-C 1.0 extensions
5241 struct _objc_protocol_extension *isa;
5242 char *protocol_name;
5243 struct _objc_protocol **protocol_list;
5244 struct _objc_protocol_method_list *instance_methods;
5245 struct _objc_protocol_method_list *class_methods;
5246 };
5247 */
5248 static bool objc_protocol = false;
5249 if (!objc_protocol) {
5250 Result += "\nstruct _objc_protocol {\n";
5251 Result += "\tstruct _objc_protocol_extension *isa;\n";
5252 Result += "\tchar *protocol_name;\n";
5253 Result += "\tstruct _objc_protocol **protocol_list;\n";
5254 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5255 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5256 Result += "};\n";
5257
5258 objc_protocol = true;
5259 }
5260
5261 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5262 Result += PDecl->getNameAsString();
5263 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5264 "{\n\t0, \"";
5265 Result += PDecl->getNameAsString();
5266 Result += "\", 0, ";
5267 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5268 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5269 Result += PDecl->getNameAsString();
5270 Result += ", ";
5271 }
5272 else
5273 Result += "0, ";
5274 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5275 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5276 Result += PDecl->getNameAsString();
5277 Result += "\n";
5278 }
5279 else
5280 Result += "0\n";
5281 Result += "};\n";
5282
5283 // Mark this protocol as having been generated.
Douglas Gregor33b24292012-01-01 18:09:12 +00005284 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005285 llvm_unreachable("protocol already synthesized");
5286
5287}
5288
5289void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5290 const ObjCList<ObjCProtocolDecl> &Protocols,
5291 StringRef prefix, StringRef ClassName,
5292 std::string &Result) {
5293 if (Protocols.empty()) return;
5294
5295 for (unsigned i = 0; i != Protocols.size(); i++)
5296 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5297
5298 // Output the top lovel protocol meta-data for the class.
5299 /* struct _objc_protocol_list {
5300 struct _objc_protocol_list *next;
5301 int protocol_count;
5302 struct _objc_protocol *class_protocols[];
5303 }
5304 */
5305 Result += "\nstatic struct {\n";
5306 Result += "\tstruct _objc_protocol_list *next;\n";
5307 Result += "\tint protocol_count;\n";
5308 Result += "\tstruct _objc_protocol *class_protocols[";
5309 Result += utostr(Protocols.size());
5310 Result += "];\n} _OBJC_";
5311 Result += prefix;
5312 Result += "_PROTOCOLS_";
5313 Result += ClassName;
5314 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5315 "{\n\t0, ";
5316 Result += utostr(Protocols.size());
5317 Result += "\n";
5318
5319 Result += "\t,{&_OBJC_PROTOCOL_";
5320 Result += Protocols[0]->getNameAsString();
5321 Result += " \n";
5322
5323 for (unsigned i = 1; i != Protocols.size(); i++) {
5324 Result += "\t ,&_OBJC_PROTOCOL_";
5325 Result += Protocols[i]->getNameAsString();
5326 Result += "\n";
5327 }
5328 Result += "\t }\n};\n";
5329}
5330
5331void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5332 std::string &Result) {
5333 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5334
5335 // Explicitly declared @interface's are already synthesized.
5336 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005337 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005338 // produce correct synthesis as yet.
5339 RewriteObjCInternalStruct(CDecl, Result);
5340 }
5341
5342 // Build _objc_ivar_list metadata for classes ivars if needed
5343 unsigned NumIvars = !IDecl->ivar_empty()
5344 ? IDecl->ivar_size()
5345 : (CDecl ? CDecl->ivar_size() : 0);
5346 if (NumIvars > 0) {
5347 static bool objc_ivar = false;
5348 if (!objc_ivar) {
5349 /* struct _objc_ivar {
5350 char *ivar_name;
5351 char *ivar_type;
5352 int ivar_offset;
5353 };
5354 */
5355 Result += "\nstruct _objc_ivar {\n";
5356 Result += "\tchar *ivar_name;\n";
5357 Result += "\tchar *ivar_type;\n";
5358 Result += "\tint ivar_offset;\n";
5359 Result += "};\n";
5360
5361 objc_ivar = true;
5362 }
5363
5364 /* struct {
5365 int ivar_count;
5366 struct _objc_ivar ivar_list[nIvars];
5367 };
5368 */
5369 Result += "\nstatic struct {\n";
5370 Result += "\tint ivar_count;\n";
5371 Result += "\tstruct _objc_ivar ivar_list[";
5372 Result += utostr(NumIvars);
5373 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5374 Result += IDecl->getNameAsString();
5375 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5376 "{\n\t";
5377 Result += utostr(NumIvars);
5378 Result += "\n";
5379
5380 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5381 SmallVector<ObjCIvarDecl *, 8> IVars;
5382 if (!IDecl->ivar_empty()) {
Aaron Ballmand6d25de2014-03-14 15:16:45 +00005383 for (auto *IV : IDecl->ivars())
5384 IVars.push_back(IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005385 IVI = IDecl->ivar_begin();
5386 IVE = IDecl->ivar_end();
5387 } else {
5388 IVI = CDecl->ivar_begin();
5389 IVE = CDecl->ivar_end();
5390 }
5391 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005392 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005393 Result += "\", \"";
5394 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005395 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005396 QuoteDoublequotes(TmpString, StrEncoding);
5397 Result += StrEncoding;
5398 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005399 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005400 Result += "}\n";
5401 for (++IVI; IVI != IVE; ++IVI) {
5402 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005403 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005404 Result += "\", \"";
5405 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005406 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005407 QuoteDoublequotes(TmpString, StrEncoding);
5408 Result += StrEncoding;
5409 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005410 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005411 Result += "}\n";
5412 }
5413
5414 Result += "\t }\n};\n";
5415 }
5416
5417 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005418 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005419
5420 // If any of our property implementations have associated getters or
5421 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005422 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005423 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005424 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005425 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005426 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005427 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005428 if (!PD)
5429 continue;
5430 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5431 if (!Getter->isDefined())
5432 InstanceMethods.push_back(Getter);
5433 if (PD->isReadOnly())
5434 continue;
5435 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5436 if (!Setter->isDefined())
5437 InstanceMethods.push_back(Setter);
5438 }
5439 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5440 true, "", IDecl->getName(), Result);
5441
5442 // Build _objc_method_list for class's class methods if needed
5443 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5444 false, "", IDecl->getName(), Result);
5445
5446 // Protocols referenced in class declaration?
5447 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5448 "CLASS", CDecl->getName(), Result);
5449
5450 // Declaration of class/meta-class metadata
5451 /* struct _objc_class {
5452 struct _objc_class *isa; // or const char *root_class_name when metadata
5453 const char *super_class_name;
5454 char *name;
5455 long version;
5456 long info;
5457 long instance_size;
5458 struct _objc_ivar_list *ivars;
5459 struct _objc_method_list *methods;
5460 struct objc_cache *cache;
5461 struct objc_protocol_list *protocols;
5462 const char *ivar_layout;
5463 struct _objc_class_ext *ext;
5464 };
5465 */
5466 static bool objc_class = false;
5467 if (!objc_class) {
5468 Result += "\nstruct _objc_class {\n";
5469 Result += "\tstruct _objc_class *isa;\n";
5470 Result += "\tconst char *super_class_name;\n";
5471 Result += "\tchar *name;\n";
5472 Result += "\tlong version;\n";
5473 Result += "\tlong info;\n";
5474 Result += "\tlong instance_size;\n";
5475 Result += "\tstruct _objc_ivar_list *ivars;\n";
5476 Result += "\tstruct _objc_method_list *methods;\n";
5477 Result += "\tstruct objc_cache *cache;\n";
5478 Result += "\tstruct _objc_protocol_list *protocols;\n";
5479 Result += "\tconst char *ivar_layout;\n";
5480 Result += "\tstruct _objc_class_ext *ext;\n";
5481 Result += "};\n";
5482 objc_class = true;
5483 }
5484
5485 // Meta-class metadata generation.
5486 ObjCInterfaceDecl *RootClass = 0;
5487 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5488 while (SuperClass) {
5489 RootClass = SuperClass;
5490 SuperClass = SuperClass->getSuperClass();
5491 }
5492 SuperClass = CDecl->getSuperClass();
5493
5494 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5495 Result += CDecl->getNameAsString();
5496 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5497 "{\n\t(struct _objc_class *)\"";
5498 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5499 Result += "\"";
5500
5501 if (SuperClass) {
5502 Result += ", \"";
5503 Result += SuperClass->getNameAsString();
5504 Result += "\", \"";
5505 Result += CDecl->getNameAsString();
5506 Result += "\"";
5507 }
5508 else {
5509 Result += ", 0, \"";
5510 Result += CDecl->getNameAsString();
5511 Result += "\"";
5512 }
5513 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5514 // 'info' field is initialized to CLS_META(2) for metaclass
5515 Result += ", 0,2, sizeof(struct _objc_class), 0";
5516 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5517 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5518 Result += IDecl->getNameAsString();
5519 Result += "\n";
5520 }
5521 else
5522 Result += ", 0\n";
5523 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5524 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5525 Result += CDecl->getNameAsString();
5526 Result += ",0,0\n";
5527 }
5528 else
5529 Result += "\t,0,0,0,0\n";
5530 Result += "};\n";
5531
5532 // class metadata generation.
5533 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5534 Result += CDecl->getNameAsString();
5535 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5536 "{\n\t&_OBJC_METACLASS_";
5537 Result += CDecl->getNameAsString();
5538 if (SuperClass) {
5539 Result += ", \"";
5540 Result += SuperClass->getNameAsString();
5541 Result += "\", \"";
5542 Result += CDecl->getNameAsString();
5543 Result += "\"";
5544 }
5545 else {
5546 Result += ", 0, \"";
5547 Result += CDecl->getNameAsString();
5548 Result += "\"";
5549 }
5550 // 'info' field is initialized to CLS_CLASS(1) for class
5551 Result += ", 0,1";
5552 if (!ObjCSynthesizedStructs.count(CDecl))
5553 Result += ",0";
5554 else {
5555 // class has size. Must synthesize its size.
5556 Result += ",sizeof(struct ";
5557 Result += CDecl->getNameAsString();
5558 if (LangOpts.MicrosoftExt)
5559 Result += "_IMPL";
5560 Result += ")";
5561 }
5562 if (NumIvars > 0) {
5563 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5564 Result += CDecl->getNameAsString();
5565 Result += "\n\t";
5566 }
5567 else
5568 Result += ",0";
5569 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5570 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5571 Result += CDecl->getNameAsString();
5572 Result += ", 0\n\t";
5573 }
5574 else
5575 Result += ",0,0";
5576 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5577 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5578 Result += CDecl->getNameAsString();
5579 Result += ", 0,0\n";
5580 }
5581 else
5582 Result += ",0,0,0\n";
5583 Result += "};\n";
5584}
5585
5586void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5587 int ClsDefCount = ClassImplementation.size();
5588 int CatDefCount = CategoryImplementation.size();
5589
5590 // For each implemented class, write out all its meta data.
5591 for (int i = 0; i < ClsDefCount; i++)
5592 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5593
5594 // For each implemented category, write out all its meta data.
5595 for (int i = 0; i < CatDefCount; i++)
5596 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5597
5598 // Write objc_symtab metadata
5599 /*
5600 struct _objc_symtab
5601 {
5602 long sel_ref_cnt;
5603 SEL *refs;
5604 short cls_def_cnt;
5605 short cat_def_cnt;
5606 void *defs[cls_def_cnt + cat_def_cnt];
5607 };
5608 */
5609
5610 Result += "\nstruct _objc_symtab {\n";
5611 Result += "\tlong sel_ref_cnt;\n";
5612 Result += "\tSEL *refs;\n";
5613 Result += "\tshort cls_def_cnt;\n";
5614 Result += "\tshort cat_def_cnt;\n";
5615 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5616 Result += "};\n\n";
5617
5618 Result += "static struct _objc_symtab "
5619 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5620 Result += "\t0, 0, " + utostr(ClsDefCount)
5621 + ", " + utostr(CatDefCount) + "\n";
5622 for (int i = 0; i < ClsDefCount; i++) {
5623 Result += "\t,&_OBJC_CLASS_";
5624 Result += ClassImplementation[i]->getNameAsString();
5625 Result += "\n";
5626 }
5627
5628 for (int i = 0; i < CatDefCount; i++) {
5629 Result += "\t,&_OBJC_CATEGORY_";
5630 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5631 Result += "_";
5632 Result += CategoryImplementation[i]->getNameAsString();
5633 Result += "\n";
5634 }
5635
5636 Result += "};\n\n";
5637
5638 // Write objc_module metadata
5639
5640 /*
5641 struct _objc_module {
5642 long version;
5643 long size;
5644 const char *name;
5645 struct _objc_symtab *symtab;
5646 }
5647 */
5648
5649 Result += "\nstruct _objc_module {\n";
5650 Result += "\tlong version;\n";
5651 Result += "\tlong size;\n";
5652 Result += "\tconst char *name;\n";
5653 Result += "\tstruct _objc_symtab *symtab;\n";
5654 Result += "};\n\n";
5655 Result += "static struct _objc_module "
5656 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5657 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5658 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5659 Result += "};\n\n";
5660
5661 if (LangOpts.MicrosoftExt) {
5662 if (ProtocolExprDecls.size()) {
5663 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5664 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5665 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5666 E = ProtocolExprDecls.end(); I != E; ++I) {
5667 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5668 Result += (*I)->getNameAsString();
5669 Result += " = &_OBJC_PROTOCOL_";
5670 Result += (*I)->getNameAsString();
5671 Result += ";\n";
5672 }
5673 Result += "#pragma data_seg(pop)\n\n";
5674 }
5675 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5676 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5677 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5678 Result += "&_OBJC_MODULES;\n";
5679 Result += "#pragma data_seg(pop)\n\n";
5680 }
5681}
5682
5683/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5684/// implementation.
5685void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5686 std::string &Result) {
5687 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5688 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005689 ObjCCategoryDecl *CDecl
5690 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005691
5692 std::string FullCategoryName = ClassDecl->getNameAsString();
5693 FullCategoryName += '_';
5694 FullCategoryName += IDecl->getNameAsString();
5695
5696 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005697 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005698
5699 // If any of our property implementations have associated getters or
5700 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005701 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005702 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005703 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005704 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005705 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005706 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005707 if (!PD)
5708 continue;
5709 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5710 InstanceMethods.push_back(Getter);
5711 if (PD->isReadOnly())
5712 continue;
5713 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5714 InstanceMethods.push_back(Setter);
5715 }
5716 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5717 true, "CATEGORY_", FullCategoryName.c_str(),
5718 Result);
5719
5720 // Build _objc_method_list for class's class methods if needed
5721 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5722 false, "CATEGORY_", FullCategoryName.c_str(),
5723 Result);
5724
5725 // Protocols referenced in class declaration?
5726 // Null CDecl is case of a category implementation with no category interface
5727 if (CDecl)
5728 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5729 FullCategoryName, Result);
5730 /* struct _objc_category {
5731 char *category_name;
5732 char *class_name;
5733 struct _objc_method_list *instance_methods;
5734 struct _objc_method_list *class_methods;
5735 struct _objc_protocol_list *protocols;
5736 // Objective-C 1.0 extensions
5737 uint32_t size; // sizeof (struct _objc_category)
5738 struct _objc_property_list *instance_properties; // category's own
5739 // @property decl.
5740 };
5741 */
5742
5743 static bool objc_category = false;
5744 if (!objc_category) {
5745 Result += "\nstruct _objc_category {\n";
5746 Result += "\tchar *category_name;\n";
5747 Result += "\tchar *class_name;\n";
5748 Result += "\tstruct _objc_method_list *instance_methods;\n";
5749 Result += "\tstruct _objc_method_list *class_methods;\n";
5750 Result += "\tstruct _objc_protocol_list *protocols;\n";
5751 Result += "\tunsigned int size;\n";
5752 Result += "\tstruct _objc_property_list *instance_properties;\n";
5753 Result += "};\n";
5754 objc_category = true;
5755 }
5756 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5757 Result += FullCategoryName;
5758 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5759 Result += IDecl->getNameAsString();
5760 Result += "\"\n\t, \"";
5761 Result += ClassDecl->getNameAsString();
5762 Result += "\"\n";
5763
5764 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5765 Result += "\t, (struct _objc_method_list *)"
5766 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5767 Result += FullCategoryName;
5768 Result += "\n";
5769 }
5770 else
5771 Result += "\t, 0\n";
5772 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5773 Result += "\t, (struct _objc_method_list *)"
5774 "&_OBJC_CATEGORY_CLASS_METHODS_";
5775 Result += FullCategoryName;
5776 Result += "\n";
5777 }
5778 else
5779 Result += "\t, 0\n";
5780
5781 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5782 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5783 Result += FullCategoryName;
5784 Result += "\n";
5785 }
5786 else
5787 Result += "\t, 0\n";
5788 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5789}
5790
5791// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5792/// class methods.
5793template<typename MethodIterator>
5794void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5795 MethodIterator MethodEnd,
5796 bool IsInstanceMethod,
5797 StringRef prefix,
5798 StringRef ClassName,
5799 std::string &Result) {
5800 if (MethodBegin == MethodEnd) return;
5801
5802 if (!objc_impl_method) {
5803 /* struct _objc_method {
5804 SEL _cmd;
5805 char *method_types;
5806 void *_imp;
5807 }
5808 */
5809 Result += "\nstruct _objc_method {\n";
5810 Result += "\tSEL _cmd;\n";
5811 Result += "\tchar *method_types;\n";
5812 Result += "\tvoid *_imp;\n";
5813 Result += "};\n";
5814
5815 objc_impl_method = true;
5816 }
5817
5818 // Build _objc_method_list for class's methods if needed
5819
5820 /* struct {
5821 struct _objc_method_list *next_method;
5822 int method_count;
5823 struct _objc_method method_list[];
5824 }
5825 */
5826 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5827 Result += "\nstatic struct {\n";
5828 Result += "\tstruct _objc_method_list *next_method;\n";
5829 Result += "\tint method_count;\n";
5830 Result += "\tstruct _objc_method method_list[";
5831 Result += utostr(NumMethods);
5832 Result += "];\n} _OBJC_";
5833 Result += prefix;
5834 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5835 Result += "_METHODS_";
5836 Result += ClassName;
5837 Result += " __attribute__ ((used, section (\"__OBJC, __";
5838 Result += IsInstanceMethod ? "inst" : "cls";
5839 Result += "_meth\")))= ";
5840 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5841
5842 Result += "\t,{{(SEL)\"";
5843 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5844 std::string MethodTypeString;
5845 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5846 Result += "\", \"";
5847 Result += MethodTypeString;
5848 Result += "\", (void *)";
5849 Result += MethodInternalNames[*MethodBegin];
5850 Result += "}\n";
5851 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5852 Result += "\t ,{(SEL)\"";
5853 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5854 std::string MethodTypeString;
5855 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5856 Result += "\", \"";
5857 Result += MethodTypeString;
5858 Result += "\", (void *)";
5859 Result += MethodInternalNames[*MethodBegin];
5860 Result += "}\n";
5861 }
5862 Result += "\t }\n};\n";
5863}
5864
5865Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5866 SourceRange OldRange = IV->getSourceRange();
5867 Expr *BaseExpr = IV->getBase();
5868
5869 // Rewrite the base, but without actually doing replaces.
5870 {
5871 DisableReplaceStmtScope S(*this);
5872 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5873 IV->setBase(BaseExpr);
5874 }
5875
5876 ObjCIvarDecl *D = IV->getDecl();
5877
5878 Expr *Replacement = IV;
5879 if (CurMethodDef) {
5880 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5881 const ObjCInterfaceType *iFaceDecl =
5882 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5883 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5884 // lookup which class implements the instance variable.
5885 ObjCInterfaceDecl *clsDeclared = 0;
5886 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5887 clsDeclared);
5888 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5889
5890 // Synthesize an explicit cast to gain access to the ivar.
5891 std::string RecName = clsDeclared->getIdentifier()->getName();
5892 RecName += "_IMPL";
5893 IdentifierInfo *II = &Context->Idents.get(RecName);
5894 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5895 SourceLocation(), SourceLocation(),
5896 II);
5897 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5898 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5899 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5900 CK_BitCast,
5901 IV->getBase());
5902 // Don't forget the parens to enforce the proper binding.
5903 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5904 OldRange.getEnd(),
5905 castExpr);
5906 if (IV->isFreeIvar() &&
Douglas Gregor0b144e12011-12-15 00:29:59 +00005907 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005908 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5909 IV->getLocation(),
5910 D->getType(),
5911 VK_LValue, OK_Ordinary);
5912 Replacement = ME;
5913 } else {
5914 IV->setBase(PE);
5915 }
5916 }
5917 } else { // we are outside a method.
5918 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5919
5920 // Explicit ivar refs need to have a cast inserted.
5921 // FIXME: consider sharing some of this code with the code above.
5922 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5923 const ObjCInterfaceType *iFaceDecl =
5924 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5925 // lookup which class implements the instance variable.
5926 ObjCInterfaceDecl *clsDeclared = 0;
5927 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5928 clsDeclared);
5929 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5930
5931 // Synthesize an explicit cast to gain access to the ivar.
5932 std::string RecName = clsDeclared->getIdentifier()->getName();
5933 RecName += "_IMPL";
5934 IdentifierInfo *II = &Context->Idents.get(RecName);
5935 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5936 SourceLocation(), SourceLocation(),
5937 II);
5938 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5939 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5940 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5941 CK_BitCast,
5942 IV->getBase());
5943 // Don't forget the parens to enforce the proper binding.
5944 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5945 IV->getBase()->getLocEnd(), castExpr);
5946 // Cannot delete IV->getBase(), since PE points to it.
5947 // Replace the old base with the cast. This is important when doing
5948 // embedded rewrites. For example, [newInv->_container addObject:0].
5949 IV->setBase(PE);
5950 }
5951 }
5952
5953 ReplaceStmtWithRange(IV, Replacement, OldRange);
5954 return Replacement;
5955}