blob: e96ff78c604db8bb08226b776eb9080489a2c0c2 [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
Alp Toker0621cb22014-07-16 16:48:33 +000032#ifdef CLANG_ENABLE_OBJC_REWRITER
33
Chris Lattnere99c8322007-10-11 00:43:27 +000034using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000035using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000036
Chris Lattnere99c8322007-10-11 00:43:27 +000037namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian83077422011-12-08 18:25:15 +000039 protected:
40
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000041 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000042 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000043 block, ... */
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
46 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000047 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000048 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000049 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000050 support routines */
51 BLOCK_BYREF_CURRENT_MAX = 256
52 };
53
54 enum {
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
61 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000062 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000063
Chris Lattner0bd1c972007-10-16 21:07:07 +000064 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000065 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000066 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000067 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000068 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000069 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000070 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000071 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000072 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000074 std::string InFileName;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000085
Fariborz Jahanian8efef602011-12-05 19:50:04 +000086 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
Fariborz Jahanian83077422011-12-08 18:25:15 +000089 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000090 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000109 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000120
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000127
John McCall113bee02012-03-10 09:33:50 +0000128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff22216db2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000145
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000146 // Needed for header files being rewritten
147 bool IsHeader;
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
150
Steve Naroff08628db2008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000152 class DisableReplaceStmtScope {
153 RewriteObjC &R;
154 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000155
John McCallfe96e0b2011-11-06 09:01:30 +0000156 public:
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
160 }
161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
163 }
164 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000165 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattnere99c8322007-10-11 00:43:27 +0000167 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000168
Chris Lattner3c799d72007-10-24 17:06:59 +0000169 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000170 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000172 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173 if (!Class->isThisDeclarationADefinition()) {
174 RewriteForwardClassDecl(D);
175 break;
176 }
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000177 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000178
Douglas Gregorf6102672012-01-01 21:23:57 +0000179 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
182 break;
183 }
184 }
185
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000186 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000187 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000188 return true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000189 }
190 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000191 void HandleDeclInMainFile(Decl *D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000192 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000193 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000194 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000195
196 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000197
Craig Topperfb6b25b2014-03-15 04:29:04 +0000198 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump11289f42009-09-09 15:08:12 +0000199
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000200 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000201 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000202
Steve Naroff22216db2008-12-04 23:50:32 +0000203 if (ReplacingStmt)
204 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000205
Steve Naroff08628db2008-12-09 12:56:34 +0000206 if (DisableReplaceStmt)
John McCallfe96e0b2011-11-06 09:01:30 +0000207 return;
Steve Naroff08628db2008-12-09 12:56:34 +0000208
Steve Naroff22216db2008-12-04 23:50:32 +0000209 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000210 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000211 ReplacedNodes[Old] = New;
212 return;
213 }
214 if (SilenceRewriteMacroWarning)
215 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000218 }
Steve Naroff08628db2008-12-09 12:56:34 +0000219
220 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000221 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
John McCallfe96e0b2011-11-06 09:01:30 +0000222 if (DisableReplaceStmt)
223 return;
224
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000225 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000226 int Size = Rewrite.getRangeSize(SrcRange);
227 if (Size == -1) {
228 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
229 << Old->getSourceRange();
230 return;
231 }
232 // Get the new text.
233 std::string SStr;
234 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000235 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000236 const std::string &Str = S.str();
237
238 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000239 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000240 ReplacedNodes[Old] = New;
241 return;
242 }
243 if (SilenceRewriteMacroWarning)
244 return;
245 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
246 << Old->getSourceRange();
247 }
248
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000249 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000250 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000251 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000252 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000253 SilenceRewriteMacroWarning)
254 return;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattner1780a852008-01-31 19:42:41 +0000256 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Chris Lattner9cc55f52008-01-31 19:51:04 +0000259 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000260 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000261 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000262 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000263 SilenceRewriteMacroWarning)
264 return;
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chris Lattner9cc55f52008-01-31 19:51:04 +0000266 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
267 }
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattner3c799d72007-10-24 17:06:59 +0000269 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000270 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000271 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000272 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000273 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000274 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000275 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000276 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000277 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
278 ObjCImplementationDecl *IMD,
279 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000280 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000281 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000282 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
283 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000284 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
285 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000286 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000287 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000288 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
289 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000290 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000291 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000292 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000293 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000294 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000295 void RewriteBlockPointerType(std::string& Str, QualType Type);
296 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000297 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000299 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000300 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000301
Chris Lattner3c799d72007-10-24 17:06:59 +0000302 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000303 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000304 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000305 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
306 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000307 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000308 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000309 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000310 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000311 void RewriteTryReturnStmts(Stmt *S);
312 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000313 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000314 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000315 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000316 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
317 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000320 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000321
Steve Naroff677ab3a2008-10-27 17:20:55 +0000322 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000323 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000324
Mike Stump11289f42009-09-09 15:08:12 +0000325 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000326 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000327 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000328 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000329 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000330 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000331
332 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
333 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000334
335 virtual void Initialize(ASTContext &context) override = 0;
336
Fariborz Jahanian83077422011-12-08 18:25:15 +0000337 // Metadata Rewriting.
338 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
339 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
340 StringRef prefix,
341 StringRef ClassName,
342 std::string &Result) = 0;
343 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
344 std::string &Result) = 0;
345 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
346 StringRef prefix,
347 StringRef ClassName,
348 std::string &Result) = 0;
349 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
350 std::string &Result) = 0;
351
352 // Rewriting ivar access
353 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
354 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
355 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000356
Benjamin Kramer474261a2012-06-02 10:20:41 +0000357 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000358 // rewriting routines on the new ASTs.
359 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
360 Expr **args, unsigned nargs,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000363 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
364 QualType msgSendType,
365 QualType returnType,
366 SmallVectorImpl<QualType> &ArgTypes,
367 SmallVectorImpl<Expr*> &MsgExprs,
368 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000369 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
370 SourceLocation StartLoc=SourceLocation(),
371 SourceLocation EndLoc=SourceLocation());
372
373 void SynthCountByEnumWithState(std::string &buf);
374 void SynthMsgSendFunctionDecl();
375 void SynthMsgSendSuperFunctionDecl();
376 void SynthMsgSendStretFunctionDecl();
377 void SynthMsgSendFpretFunctionDecl();
378 void SynthMsgSendSuperStretFunctionDecl();
379 void SynthGetClassFunctionDecl();
380 void SynthGetMetaClassFunctionDecl();
381 void SynthGetSuperClassFunctionDecl();
382 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000383 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000384
385 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000386 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000387 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000388 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000390 std::string SynthesizeBlockImpl(BlockExpr *CE,
391 std::string Tag, std::string Desc);
392 std::string SynthesizeBlockDescriptor(std::string DescTag,
393 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000394 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000395 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000396 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000398 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000399 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
400 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000401 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000403 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000404 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000405 void WarnAboutReturnGotoStmts(Stmt *S);
406 void HasReturnStmts(Stmt *S, bool &hasReturns);
407 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
408 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
409 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
410
411 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000412 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000413 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000414 void GetInnerBlockDeclRefExprs(Stmt *S,
415 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000416 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000417
Steve Naroff677ab3a2008-10-27 17:20:55 +0000418 // We avoid calling Type::isBlockPointerType(), since it operates on the
419 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000420 bool isTopLevelBlockPointerType(QualType T) {
421 return isa<BlockPointerType>(T);
422 }
Mike Stump11289f42009-09-09 15:08:12 +0000423
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000424 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
425 /// to a function pointer type and upon success, returns true; false
426 /// otherwise.
427 bool convertBlockPointerToFunctionPointer(QualType &T) {
428 if (isTopLevelBlockPointerType(T)) {
429 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
430 T = Context->getPointerType(BPT->getPointeeType());
431 return true;
432 }
433 return false;
434 }
435
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000436 bool needToScanForQualifiers(QualType T);
437 QualType getSuperStructType();
438 QualType getConstantStringStructType();
439 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
440 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
441
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000442 void convertToUnqualifiedObjCType(QualType &T) {
443 if (T->isObjCQualifiedIdType())
444 T = Context->getObjCIdType();
445 else if (T->isObjCQualifiedClassType())
446 T = Context->getObjCClassType();
447 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000448 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
449 if (const ObjCObjectPointerType * OBJPT =
450 T->getAsObjCInterfacePointerType()) {
451 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
452 T = QualType(IFaceT, 0);
453 T = Context->getPointerType(T);
454 }
455 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000456 }
457
Steve Naroff677ab3a2008-10-27 17:20:55 +0000458 // FIXME: This predicate seems like it would be useful to add to ASTContext.
459 bool isObjCType(QualType T) {
460 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
461 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000462
Steve Naroff677ab3a2008-10-27 17:20:55 +0000463 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000464
Steve Naroff677ab3a2008-10-27 17:20:55 +0000465 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
466 OCT == Context->getCanonicalType(Context->getObjCClassType()))
467 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000468
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000469 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000470 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000471 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000472 return true;
473 }
474 return false;
475 }
476 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000477 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000478 void GetExtentOfArgList(const char *Name, const char *&LParen,
479 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000480
Steve Naroffd9803712009-04-29 16:37:50 +0000481 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000482 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000483 if (From[i] == '"')
484 To += "\\\"";
485 else
486 To += From[i];
487 }
488 }
John McCalldb40c7f2010-12-14 08:05:40 +0000489
490 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000491 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000492 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000493 if (result == Context->getObjCInstanceType())
494 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000495 FunctionProtoType::ExtProtoInfo fpi;
496 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000497 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000498 }
John McCall97513962010-01-15 18:39:57 +0000499
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000500 // Helper function: create a CStyleCastExpr with trivial type source info.
501 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
502 CastKind Kind, Expr *E) {
503 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000504 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
505 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000506 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000507
508 StringLiteral *getStringLiteral(StringRef Str) {
509 QualType StrType = Context->getConstantArrayType(
510 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
511 0);
512 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
513 /*Pascal=*/false, StrType, SourceLocation());
514 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000515 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000516
517 class RewriteObjCFragileABI : public RewriteObjC {
518 public:
519
520 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
521 DiagnosticsEngine &D, const LangOptions &LOpts,
522 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
523 D, LOpts,
524 silenceMacroWarn) {}
525
526 ~RewriteObjCFragileABI() {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000527 virtual void Initialize(ASTContext &context) override;
528
Fariborz Jahanian83077422011-12-08 18:25:15 +0000529 // Rewriting metadata
530 template<typename MethodIterator>
531 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
532 MethodIterator MethodEnd,
533 bool IsInstanceMethod,
534 StringRef prefix,
535 StringRef ClassName,
536 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000537 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
538 StringRef prefix, StringRef ClassName,
539 std::string &Result) override;
540 void RewriteObjCProtocolListMetaData(
541 const ObjCList<ObjCProtocolDecl> &Prots,
542 StringRef prefix, StringRef ClassName, std::string &Result) override;
543 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
544 std::string &Result) override;
545 void RewriteMetaDataIntoBuffer(std::string &Result) override;
546 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
547 std::string &Result) override;
548
Fariborz Jahanian83077422011-12-08 18:25:15 +0000549 // Rewriting ivar
Craig Topperfb6b25b2014-03-15 04:29:04 +0000550 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
551 std::string &Result) override;
552 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahanian83077422011-12-08 18:25:15 +0000553 };
Chris Lattnere99c8322007-10-11 00:43:27 +0000554}
555
Mike Stump11289f42009-09-09 15:08:12 +0000556void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
557 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000558 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000559 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000560 for (const auto &I : fproto->param_types())
561 if (isTopLevelBlockPointerType(I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562 // All the args are checked/rewritten. Don't call twice!
563 RewriteBlockPointerDecl(D);
564 break;
565 }
566 }
567}
568
569void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000571 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000572 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000573}
574
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000575static bool IsHeaderFile(const std::string &Filename) {
576 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000577
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000578 if (DotPos == std::string::npos) {
579 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000580 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000583 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
584 // C header: .h
585 // C++ header: .hh or .H;
586 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000587}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000588
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000590 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000591 bool silenceMacroWarn)
592 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
593 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000594 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000595 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000596 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000601}
602
David Blaikie6beb6aa2014-08-10 19:56:51 +0000603std::unique_ptr<ASTConsumer>
604clang::CreateObjCRewriter(const std::string &InFile, raw_ostream *OS,
605 DiagnosticsEngine &Diags, const LangOptions &LOpts,
606 bool SilenceRewriteMacroWarning) {
607 return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
608 SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000609}
Chris Lattnere99c8322007-10-11 00:43:27 +0000610
Fariborz Jahanian83077422011-12-08 18:25:15 +0000611void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000612 Context = &context;
613 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000614 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000615 MsgSendFunctionDecl = nullptr;
616 MsgSendSuperFunctionDecl = nullptr;
617 MsgSendStretFunctionDecl = nullptr;
618 MsgSendSuperStretFunctionDecl = nullptr;
619 MsgSendFpretFunctionDecl = nullptr;
620 GetClassFunctionDecl = nullptr;
621 GetMetaClassFunctionDecl = nullptr;
622 GetSuperClassFunctionDecl = nullptr;
623 SelGetUidFunctionDecl = nullptr;
624 CFStringFunctionDecl = nullptr;
625 ConstantStringClassReference = nullptr;
626 NSStringRecord = nullptr;
627 CurMethodDef = nullptr;
628 CurFunctionDef = nullptr;
629 CurFunctionDeclToDeclareForBlock = nullptr;
630 GlobalVarDecl = nullptr;
631 SuperStructDecl = nullptr;
632 ProtocolTypeDecl = nullptr;
633 ConstantStringDecl = nullptr;
Chris Lattner187f6262008-01-31 19:38:44 +0000634 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000635 SuperConstructorFunctionDecl = nullptr;
Steve Naroffce8e8862008-03-15 00:55:56 +0000636 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000637 PropParentMap = nullptr;
638 CurrentBody = nullptr;
Steve Naroff08628db2008-12-09 12:56:34 +0000639 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000640 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000641
Chris Lattner187f6262008-01-31 19:38:44 +0000642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000647
David Blaikiebbafb8a2012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000649}
650
Chris Lattner3c799d72007-10-24 17:06:59 +0000651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000655void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000656 if (Diags.hasErrorOccurred())
657 return;
658
Chris Lattner0bd1c972007-10-16 21:07:07 +0000659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000663 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattner0bd1c972007-10-16 21:07:07 +0000665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000670 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000672 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000673 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000674 ConstantStringClassReference = FVD;
675 return;
676 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000677 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
678 if (ID->isThisDeclarationADefinition())
679 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000680 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000681 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000682 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000683 if (PD->isThisDeclarationADefinition())
684 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000685 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
686 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000687 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
688 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000689 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000690 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
691 if (!IFace->isThisDeclarationADefinition()) {
692 SmallVector<Decl *, 8> DG;
693 SourceLocation StartLoc = IFace->getLocStart();
694 do {
695 if (isa<ObjCInterfaceDecl>(*DI) &&
696 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
697 StartLoc == (*DI)->getLocStart())
698 DG.push_back(*DI);
699 else
700 break;
701
Douglas Gregordc9166c2011-12-15 20:29:51 +0000702 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000703 } while (DI != DIEnd);
704 RewriteForwardClassDecl(DG);
705 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000706 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000707 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000708
709 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
710 if (!Proto->isThisDeclarationADefinition()) {
711 SmallVector<Decl *, 8> DG;
712 SourceLocation StartLoc = Proto->getLocStart();
713 do {
714 if (isa<ObjCProtocolDecl>(*DI) &&
715 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
716 StartLoc == (*DI)->getLocStart())
717 DG.push_back(*DI);
718 else
719 break;
720
721 ++DI;
722 } while (DI != DIEnd);
723 RewriteForwardProtocolDecl(DG);
724 continue;
725 }
726 }
727
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000728 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000729 ++DI;
730 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000731 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000732 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000733 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000734 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000735}
736
Chris Lattner3c799d72007-10-24 17:06:59 +0000737//===----------------------------------------------------------------------===//
738// Syntactic (non-AST) Rewriting Code
739//===----------------------------------------------------------------------===//
740
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000741void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000742 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000743 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000744 const char *MainBufStart = MainBuf.begin();
745 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000746 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000747
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000748 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000749 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
750 if (*BufPtr == '#') {
751 if (++BufPtr == MainBufEnd)
752 return;
753 while (*BufPtr == ' ' || *BufPtr == '\t')
754 if (++BufPtr == MainBufEnd)
755 return;
756 if (!strncmp(BufPtr, "import", ImportLen)) {
757 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000758 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000759 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000760 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000761 BufPtr += ImportLen;
762 }
763 }
764 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000765}
766
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000767static std::string getIvarAccessString(ObjCIvarDecl *OID) {
768 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000769 std::string S;
770 S = "((struct ";
771 S += ClassDecl->getIdentifier()->getName();
772 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000773 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000774 return S;
775}
776
Steve Naroffc038b3a2008-12-02 17:36:43 +0000777void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
778 ObjCImplementationDecl *IMD,
779 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000780 static bool objcGetPropertyDefined = false;
781 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000782 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000783 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000784 const char *startBuf = SM->getCharacterData(startLoc);
785 assert((*startBuf == '@') && "bogus @synthesize location");
786 const char *semiBuf = strchr(startBuf, ';');
787 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000788 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000789 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000790
791 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
792 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000793
Steve Naroff9af94912008-12-02 15:48:25 +0000794 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000795 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000796 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000797
Steve Naroff003d00e2008-12-02 16:05:55 +0000798 if (!OID)
799 return;
Bill Wendling44426052012-12-20 19:22:21 +0000800 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000801 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000802 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
803 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000804 ObjCPropertyDecl::OBJC_PR_copy));
805 std::string Getr;
806 if (GenGetProperty && !objcGetPropertyDefined) {
807 objcGetPropertyDefined = true;
808 // FIXME. Is this attribute correct in all cases?
809 Getr = "\nextern \"C\" __declspec(dllimport) "
810 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000811 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000812 RewriteObjCMethodDecl(OID->getContainingInterface(),
813 PD->getGetterMethodDecl(), Getr);
814 Getr += "{ ";
815 // Synthesize an explicit cast to gain access to the ivar.
816 // See objc-act.c:objc_synthesize_new_getter() for details.
817 if (GenGetProperty) {
818 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
819 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000820 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000821 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000822 FPRetType);
823 Getr += " _TYPE";
824 if (FPRetType) {
825 Getr += ")"; // close the precedence "scope" for "*".
826
827 // Now, emit the argument types (if any).
828 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
829 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000830 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000831 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000832 std::string ParamStr =
833 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000834 Getr += ParamStr;
835 }
836 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000837 if (FT->getNumParams())
838 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000839 Getr += "...";
840 }
841 Getr += ")";
842 } else
843 Getr += "()";
844 }
845 Getr += ";\n";
846 Getr += "return (_TYPE)";
847 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000848 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000849 Getr += ", 1)";
850 }
851 else
852 Getr += "return " + getIvarAccessString(OID);
853 Getr += "; }";
854 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000856
857 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000858 return;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Steve Naroff9af94912008-12-02 15:48:25 +0000860 // Generate the 'setter' function.
861 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000862 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000863 ObjCPropertyDecl::OBJC_PR_copy);
864 if (GenSetProperty && !objcSetPropertyDefined) {
865 objcSetPropertyDefined = true;
866 // FIXME. Is this attribute correct in all cases?
867 Setr = "\nextern \"C\" __declspec(dllimport) "
868 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
869 }
870
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000871 RewriteObjCMethodDecl(OID->getContainingInterface(),
872 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000873 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000874 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000875 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000876 if (GenSetProperty) {
877 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000878 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000879 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000880 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000881 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000882 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 Setr += "0, ";
884 else
885 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000886 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000887 Setr += "1)";
888 else
889 Setr += "0)";
890 }
891 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000892 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000893 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000894 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000895 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000896 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000897}
Chris Lattner16a0de42007-10-11 18:38:32 +0000898
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000899static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
900 std::string &typedefString) {
901 typedefString += "#ifndef _REWRITER_typedef_";
902 typedefString += ForwardDecl->getNameAsString();
903 typedefString += "\n";
904 typedefString += "#define _REWRITER_typedef_";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += "\n";
907 typedefString += "typedef struct objc_object ";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += ";\n#endif\n";
910}
911
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000912void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000913 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000914 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000915 const char *startBuf = SM->getCharacterData(startLoc);
916 const char *semiPtr = strchr(startBuf, ';');
917 // Replace the @class with typedefs corresponding to the classes.
918 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
919}
920
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000922 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000923 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000924 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000925 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000926 // Translate to typedef's that forward reference structs with the same name
927 // as the class. As a convenience, we include the original declaration
928 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000929 typedefString += "// @class ";
930 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000931 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000932 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000933 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000934 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000935 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000936 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000937}
Mike Stump11289f42009-09-09 15:08:12 +0000938
Craig Topper5603df42013-07-05 19:34:19 +0000939void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000940 std::string typedefString;
941 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000942 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000943 if (i == 0) {
944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
946 typedefString += ";\n";
947 }
948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
949 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000950 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000951}
952
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000953void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000954 // When method is a synthesized one, such as a getter/setter there is
955 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000956 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000957 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 SourceLocation LocStart = Method->getLocStart();
959 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chandler Carruthd48db212011-07-25 21:09:52 +0000961 if (SM->getExpansionLineNumber(LocEnd) >
962 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000963 InsertText(LocStart, "#if 0\n");
964 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000965 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000966 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000967 }
968}
969
Mike Stump11289f42009-09-09 15:08:12 +0000970void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000971 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000973 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000974 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000975}
976
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000977void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000978 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000979
Steve Naroff5448cf62007-10-30 13:30:57 +0000980 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000982
Aaron Ballmand174edf2014-03-13 19:11:50 +0000983 for (auto *I : CatDecl->properties())
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000984 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000985 for (auto *I : CatDecl->instance_methods())
986 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000987 for (auto *I : CatDecl->class_methods())
988 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000989
Steve Naroff5448cf62007-10-30 13:30:57 +0000990 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000991 ReplaceText(CatDecl->getAtEndRange().getBegin(),
992 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000993}
994
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000995void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000996 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000997 assert(PDecl->isThisDeclarationADefinition());
998
Steve Narofff921385f2007-10-30 16:42:30 +0000999 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001000 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001001
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001002 for (auto *I : PDecl->instance_methods())
1003 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001004 for (auto *I : PDecl->class_methods())
1005 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001006 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001007 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001008
Steve Narofff921385f2007-10-30 16:42:30 +00001009 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001010 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001011 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001012
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001013 // Must comment out @optional/@required
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
1016 for (const char *p = startBuf; p < endBuf; p++) {
1017 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001018 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001019 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001021 }
1022 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001023 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001024 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001025
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001026 }
1027 }
Steve Narofff921385f2007-10-30 16:42:30 +00001028}
1029
Douglas Gregorf6102672012-01-01 21:23:57 +00001030void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1031 SourceLocation LocStart = (*D.begin())->getLocStart();
1032 if (LocStart.isInvalid())
1033 llvm_unreachable("Invalid SourceLocation");
1034 // FIXME: handle forward protocol that are declared across multiple lines.
1035 ReplaceText(LocStart, 0, "// ");
1036}
1037
1038void
Craig Topper5603df42013-07-05 19:34:19 +00001039RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001040 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001041 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001042 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001043 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001044 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001045}
1046
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001047void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1048 const FunctionType *&FPRetType) {
1049 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001050 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001051 else if (T->isFunctionPointerType() ||
1052 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001053 // needs special handling, since pointer-to-functions have special
1054 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001055 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001056 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001057 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001058 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001060 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001061 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001062 ResultStr +=
1063 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001064 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001065 }
1066 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001067 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001068}
1069
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001070void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1071 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001072 std::string &ResultStr) {
1073 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001074 const FunctionType *FPRetType = nullptr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001075 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001076 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001077 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001078
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001079 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001080 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregorffca3a22009-01-09 17:18:27 +00001082 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001083 NameStr += "_I_";
1084 else
1085 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001086
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001087 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001088 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001089
1090 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001091 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001093 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001094 }
Mike Stump11289f42009-09-09 15:08:12 +00001095 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001096 {
1097 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 int len = selString.size();
1099 for (int i = 0; i < len; i++)
1100 if (selString[i] == ':')
1101 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001102 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001103 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001104 // Remember this name for metadata emission
1105 MethodInternalNames[OMD] = NameStr;
1106 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001108 // Rewrite arguments
1109 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001110
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001111 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001112 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001113 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001114 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001115 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001116 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001117 ResultStr += "struct ";
1118 }
1119 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001120 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001121 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001122 }
1123 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001124 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001125 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001126
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001127 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001128 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001129 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001130
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001131 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001132 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001133 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001134 if (PDecl->getType()->isObjCQualifiedIdType()) {
1135 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001136 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001137 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001138 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001139 QualType QT = PDecl->getType();
1140 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001141 (void)convertBlockPointerToFunctionPointer(QT);
1142 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001143 ResultStr += Name;
1144 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001145 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001146 if (OMD->isVariadic())
1147 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001148 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001149
Steve Naroffb067bbd2008-07-16 14:40:40 +00001150 if (FPRetType) {
1151 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001152
Steve Naroffb067bbd2008-07-16 14:40:40 +00001153 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001154 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001155 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001156 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001157 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001158 std::string ParamStr =
1159 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001160 ResultStr += ParamStr;
1161 }
1162 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001163 if (FT->getNumParams())
1164 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001165 ResultStr += "...";
1166 }
1167 ResultStr += ")";
1168 } else {
1169 ResultStr += "()";
1170 }
1171 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001172}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001173void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001174 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1175 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001176
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001177 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001178
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001179 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001180 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001181 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001182 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001183 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001184
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185 const char *startBuf = SM->getCharacterData(LocStart);
1186 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001187 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001190 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001191 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001192 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001193 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001194 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001195
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001196 const char *startBuf = SM->getCharacterData(LocStart);
1197 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001198 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001199 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001200 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1201 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001202
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001203 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001204}
1205
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001206void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001207 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001208 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001209 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001210 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001211 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001212 ResultStr += "\n";
1213 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001214 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001215 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001216 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001217 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001218 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001219 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001220 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001221 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001222 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001223
Aaron Ballmand174edf2014-03-13 19:11:50 +00001224 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001225 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001226 for (auto *I : ClassDecl->instance_methods())
1227 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001228 for (auto *I : ClassDecl->class_methods())
1229 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +00001230
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001231 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001232 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1233 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001234}
1235
John McCallfe96e0b2011-11-06 09:01:30 +00001236Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1237 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001238
John McCallfe96e0b2011-11-06 09:01:30 +00001239 // We just magically know some things about the structure of this
1240 // expression.
1241 ObjCMessageExpr *OldMsg =
1242 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1243 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001244
John McCallfe96e0b2011-11-06 09:01:30 +00001245 // Because the rewriter doesn't allow us to rewrite rewritten code,
1246 // we need to suppress rewriting the sub-statements.
1247 Expr *Base, *RHS;
1248 {
1249 DisableReplaceStmtScope S(*this);
1250
1251 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001252 Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001253 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1254 Base = OldMsg->getInstanceReceiver();
1255 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1256 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1257 }
1258
1259 // Rebuild the RHS.
1260 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1261 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1262 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1263 }
1264
1265 // TODO: avoid this copy.
1266 SmallVector<SourceLocation, 1> SelLocs;
1267 OldMsg->getSelectorLocs(SelLocs);
1268
Craig Topper8ae12032014-05-07 06:21:57 +00001269 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001270 switch (OldMsg->getReceiverKind()) {
1271 case ObjCMessageExpr::Class:
1272 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1273 OldMsg->getValueKind(),
1274 OldMsg->getLeftLoc(),
1275 OldMsg->getClassReceiverTypeInfo(),
1276 OldMsg->getSelector(),
1277 SelLocs,
1278 OldMsg->getMethodDecl(),
1279 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001280 OldMsg->getRightLoc(),
1281 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001282 break;
1283
1284 case ObjCMessageExpr::Instance:
1285 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1286 OldMsg->getValueKind(),
1287 OldMsg->getLeftLoc(),
1288 Base,
1289 OldMsg->getSelector(),
1290 SelLocs,
1291 OldMsg->getMethodDecl(),
1292 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001293 OldMsg->getRightLoc(),
1294 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001295 break;
1296
1297 case ObjCMessageExpr::SuperClass:
1298 case ObjCMessageExpr::SuperInstance:
1299 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1300 OldMsg->getValueKind(),
1301 OldMsg->getLeftLoc(),
1302 OldMsg->getSuperLoc(),
1303 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1304 OldMsg->getSuperType(),
1305 OldMsg->getSelector(),
1306 SelLocs,
1307 OldMsg->getMethodDecl(),
1308 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001309 OldMsg->getRightLoc(),
1310 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001311 break;
1312 }
1313
1314 Stmt *Replacement = SynthMessageExpr(NewMsg);
1315 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1316 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001317}
1318
John McCallfe96e0b2011-11-06 09:01:30 +00001319Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1320 SourceRange OldRange = PseudoOp->getSourceRange();
1321
1322 // We just magically know some things about the structure of this
1323 // expression.
1324 ObjCMessageExpr *OldMsg =
1325 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1326
1327 // Because the rewriter doesn't allow us to rewrite rewritten code,
1328 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001329 Expr *Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001330 {
1331 DisableReplaceStmtScope S(*this);
1332
1333 // Rebuild the base expression if we have one.
1334 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1335 Base = OldMsg->getInstanceReceiver();
1336 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1337 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001338 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001339 }
Steve Narofff326f402008-12-03 00:56:33 +00001340
John McCallfe96e0b2011-11-06 09:01:30 +00001341 // Intentionally empty.
1342 SmallVector<SourceLocation, 1> SelLocs;
1343 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001344
Craig Topper8ae12032014-05-07 06:21:57 +00001345 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001346 switch (OldMsg->getReceiverKind()) {
1347 case ObjCMessageExpr::Class:
1348 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1349 OldMsg->getValueKind(),
1350 OldMsg->getLeftLoc(),
1351 OldMsg->getClassReceiverTypeInfo(),
1352 OldMsg->getSelector(),
1353 SelLocs,
1354 OldMsg->getMethodDecl(),
1355 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001356 OldMsg->getRightLoc(),
1357 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001358 break;
1359
1360 case ObjCMessageExpr::Instance:
1361 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1362 OldMsg->getValueKind(),
1363 OldMsg->getLeftLoc(),
1364 Base,
1365 OldMsg->getSelector(),
1366 SelLocs,
1367 OldMsg->getMethodDecl(),
1368 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001369 OldMsg->getRightLoc(),
1370 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001371 break;
1372
1373 case ObjCMessageExpr::SuperClass:
1374 case ObjCMessageExpr::SuperInstance:
1375 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1376 OldMsg->getValueKind(),
1377 OldMsg->getLeftLoc(),
1378 OldMsg->getSuperLoc(),
1379 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1380 OldMsg->getSuperType(),
1381 OldMsg->getSelector(),
1382 SelLocs,
1383 OldMsg->getMethodDecl(),
1384 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001385 OldMsg->getRightLoc(),
1386 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001387 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001388 }
John McCallfe96e0b2011-11-06 09:01:30 +00001389
1390 Stmt *Replacement = SynthMessageExpr(NewMsg);
1391 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1392 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001393}
1394
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395/// SynthCountByEnumWithState - To print:
1396/// ((unsigned int (*)
1397/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001398/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001399/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001400/// "countByEnumeratingWithState:objects:count:"),
1401/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001402/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001403///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001404void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001405 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1406 "id *, unsigned int))(void *)objc_msgSend)";
1407 buf += "\n\t\t";
1408 buf += "((id)l_collection,\n\t\t";
1409 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1410 buf += "\n\t\t";
1411 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001412 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001414
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001415/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1416/// statement to exit to its outer synthesized loop.
1417///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001418Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001419 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1420 return S;
1421 // replace break with goto __break_label
1422 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001423
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001424 SourceLocation startLoc = S->getLocStart();
1425 buf = "goto __break_label_";
1426 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001427 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001428
Craig Topper8ae12032014-05-07 06:21:57 +00001429 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001430}
1431
1432/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1433/// statement to continue with its inner synthesized loop.
1434///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001435Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001436 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1437 return S;
1438 // replace continue with goto __continue_label
1439 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001440
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001441 SourceLocation startLoc = S->getLocStart();
1442 buf = "goto __continue_label_";
1443 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001444 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001445
Craig Topper8ae12032014-05-07 06:21:57 +00001446 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001447}
1448
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001449/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001450/// It rewrites:
1451/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001453/// Into:
1454/// {
Mike Stump11289f42009-09-09 15:08:12 +00001455/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001457/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001459/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001460/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001461/// if (limit) {
1462/// unsigned long startMutations = *enumState.mutationsPtr;
1463/// do {
1464/// unsigned long counter = 0;
1465/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001466/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001468/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001469/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001470/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001471/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001472/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001473/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001475/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001476/// }
1477/// else
1478/// elem = nil;
1479/// }
1480///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001481Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001482 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001483 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001484 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001485 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001486 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001487 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001488
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001489 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001491 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001492 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001493 std::string buf;
1494 buf = "\n{\n\t";
1495 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1496 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001497 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001498 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001499 if (ElementType->isObjCQualifiedIdType() ||
1500 ElementType->isObjCQualifiedInterfaceType())
1501 // Simply use 'id' for all qualified types.
1502 elementTypeAsString = "id";
1503 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001504 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001505 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001506 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001507 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001508 buf += elementName;
1509 buf += ";\n\t";
1510 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001511 else {
1512 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001513 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001514 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1515 if (VD->getType()->isObjCQualifiedIdType() ||
1516 VD->getType()->isObjCQualifiedInterfaceType())
1517 // Simply use 'id' for all qualified types.
1518 elementTypeAsString = "id";
1519 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001520 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001523 // struct __objcFastEnumerationState enumState = { 0 };
1524 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001525 // id __rw_items[16];
1526 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001527 // id l_collection = (id)
1528 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001529 // Find start location of 'collection' the hard way!
1530 const char *startCollectionBuf = startBuf;
1531 startCollectionBuf += 3; // skip 'for'
1532 startCollectionBuf = strchr(startCollectionBuf, '(');
1533 startCollectionBuf++; // skip '('
1534 // find 'in' and skip it.
1535 while (*startCollectionBuf != ' ' ||
1536 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1537 (*(startCollectionBuf+3) != ' ' &&
1538 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1539 startCollectionBuf++;
1540 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001541
1542 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001543 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001544 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001545 SourceLocation rightParenLoc = S->getRParenLoc();
1546 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001547 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001549
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001551 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001552 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001553 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554 // ((unsigned int (*)
1555 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001556 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001557 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001558 // "countByEnumeratingWithState:objects:count:"),
1559 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001560 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001561 buf += "unsigned long limit =\n\t\t";
1562 SynthCountByEnumWithState(buf);
1563 buf += ";\n\t";
1564 /// if (limit) {
1565 /// unsigned long startMutations = *enumState.mutationsPtr;
1566 /// do {
1567 /// unsigned long counter = 0;
1568 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001569 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001570 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001571 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001572 buf += "if (limit) {\n\t";
1573 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1574 buf += "do {\n\t\t";
1575 buf += "unsigned long counter = 0;\n\t\t";
1576 buf += "do {\n\t\t\t";
1577 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1578 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1579 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001580 buf += " = (";
1581 buf += elementTypeAsString;
1582 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001583 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001584 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001585
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001586 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001587 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001588 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001589 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001590 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001591 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001592 /// }
1593 /// else
1594 /// elem = nil;
1595 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001596 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001597 buf = ";\n\t";
1598 buf += "__continue_label_";
1599 buf += utostr(ObjCBcLabelNo.back());
1600 buf += ": ;";
1601 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001602 buf += "} while (counter < limit);\n\t";
1603 buf += "} while (limit = ";
1604 SynthCountByEnumWithState(buf);
1605 buf += ");\n\t";
1606 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001607 buf += " = ((";
1608 buf += elementTypeAsString;
1609 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001610 buf += "__break_label_";
1611 buf += utostr(ObjCBcLabelNo.back());
1612 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 buf += "}\n\t";
1614 buf += "else\n\t\t";
1615 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001616 buf += " = ((";
1617 buf += elementTypeAsString;
1618 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001619 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001620
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001621 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001622 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001623 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001624 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001625 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001626 } else {
1627 /* Need to treat single statements specially. For example:
1628 *
1629 * for (A *a in b) if (stuff()) break;
1630 * for (A *a in b) xxxyy;
1631 *
1632 * The following code simply scans ahead to the semi to find the actual end.
1633 */
1634 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1635 const char *semiBuf = strchr(stmtBuf, ';');
1636 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001637 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001638 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001639 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001640 Stmts.pop_back();
1641 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001642 return nullptr;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001643}
1644
Mike Stump11289f42009-09-09 15:08:12 +00001645/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001646/// This routine rewrites @synchronized(expr) stmt;
1647/// into:
1648/// objc_sync_enter(expr);
1649/// @try stmt @finally { objc_sync_exit(expr); }
1650///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001651Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001652 // Get the start location and compute the semi location.
1653 SourceLocation startLoc = S->getLocStart();
1654 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001655
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001656 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001657
1658 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001659 buf = "objc_sync_enter((id)";
1660 const char *lparenBuf = startBuf;
1661 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001662 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001663 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1664 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001665 // been rewritten! (which implies the SourceLocation's are invalid).
1666 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001667 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001668 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001669 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001670 buf = ");\n";
1671 // declare a new scope with two variables, _stack and _rethrow.
1672 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1673 buf += "int buf[18/*32-bit i386*/];\n";
1674 buf += "char *pointers[4];} _stack;\n";
1675 buf += "id volatile _rethrow = 0;\n";
1676 buf += "objc_exception_try_enter(&_stack);\n";
1677 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001678 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001679 startLoc = S->getSynchBody()->getLocEnd();
1680 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001681
Steve Naroffad7013b2008-08-19 13:04:19 +00001682 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001683 SourceLocation lastCurlyLoc = startLoc;
1684 buf = "}\nelse {\n";
1685 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001686 buf += "}\n";
1687 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001688 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001689
1690 std::string syncBuf;
1691 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001692
1693 Expr *syncExpr = S->getSynchExpr();
1694 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1695 ? CK_BitCast :
1696 syncExpr->getType()->isBlockPointerType()
1697 ? CK_BlockPointerToObjCPointerCast
1698 : CK_CPointerToObjCPointerCast;
1699 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1700 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001701 std::string syncExprBufS;
1702 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Trieuddd01ce2014-06-09 22:53:25 +00001703 assert(syncExpr != nullptr && "Expected non-null Expr");
Craig Topper8ae12032014-05-07 06:21:57 +00001704 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001705 syncBuf += syncExprBuf.str();
1706 syncBuf += ");";
1707
1708 buf += syncBuf;
1709 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001710 buf += "}\n";
1711 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001712
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001713 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001714
1715 bool hasReturns = false;
1716 HasReturnStmts(S->getSynchBody(), hasReturns);
1717 if (hasReturns)
1718 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1719
Craig Topper8ae12032014-05-07 06:21:57 +00001720 return nullptr;
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001721}
1722
Steve Naroffec60b432009-12-05 21:43:12 +00001723void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1724{
Steve Naroff6d6da252008-12-05 17:03:39 +00001725 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001726 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001727 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001728 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001729
Steve Naroffec60b432009-12-05 21:43:12 +00001730 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001731 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001732 TryFinallyContainsReturnDiag);
1733 }
1734 return;
1735}
1736
Steve Naroffec60b432009-12-05 21:43:12 +00001737void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1738{
1739 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001740 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001741 if (*CI)
1742 HasReturnStmts(*CI, hasReturns);
1743
1744 if (isa<ReturnStmt>(S))
1745 hasReturns = true;
1746 return;
1747}
1748
1749void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1750 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001751 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001752 if (*CI) {
1753 RewriteTryReturnStmts(*CI);
1754 }
1755 if (isa<ReturnStmt>(S)) {
1756 SourceLocation startLoc = S->getLocStart();
1757 const char *startBuf = SM->getCharacterData(startLoc);
1758
1759 const char *semiBuf = strchr(startBuf, ';');
1760 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001761 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001762
1763 std::string buf;
1764 buf = "{ objc_exception_try_exit(&_stack); return";
1765
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001766 ReplaceText(startLoc, 6, buf);
1767 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001768 }
1769 return;
1770}
1771
1772void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1773 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001774 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001775 if (*CI) {
1776 RewriteSyncReturnStmts(*CI, syncExitBuf);
1777 }
1778 if (isa<ReturnStmt>(S)) {
1779 SourceLocation startLoc = S->getLocStart();
1780 const char *startBuf = SM->getCharacterData(startLoc);
1781
1782 const char *semiBuf = strchr(startBuf, ';');
1783 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001784 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001785
1786 std::string buf;
1787 buf = "{ objc_exception_try_exit(&_stack);";
1788 buf += syncExitBuf;
1789 buf += " return";
1790
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001791 ReplaceText(startLoc, 6, buf);
1792 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001793 }
1794 return;
1795}
1796
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001797Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798 // Get the start location and compute the semi location.
1799 SourceLocation startLoc = S->getLocStart();
1800 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 assert((*startBuf == '@') && "bogus @try location");
1803
1804 std::string buf;
1805 // declare a new scope with two variables, _stack and _rethrow.
1806 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1807 buf += "int buf[18/*32-bit i386*/];\n";
1808 buf += "char *pointers[4];} _stack;\n";
1809 buf += "id volatile _rethrow = 0;\n";
1810 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001811 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001812
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001813 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001814
Steve Naroffbf478ec2007-11-07 04:08:17 +00001815 startLoc = S->getTryBody()->getLocEnd();
1816 startBuf = SM->getCharacterData(startLoc);
1817
1818 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001819
Steve Naroffbf478ec2007-11-07 04:08:17 +00001820 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001821 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001822 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001823 buf = " /* @catch begin */ else {\n";
1824 buf += " id _caught = objc_exception_extract(&_stack);\n";
1825 buf += " objc_exception_try_enter (&_stack);\n";
1826 buf += " if (_setjmp(_stack.buf))\n";
1827 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1828 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001829
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001830 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001831 } else { /* no catch list */
1832 buf = "}\nelse {\n";
1833 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1834 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001835 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001836 }
Craig Topper8ae12032014-05-07 06:21:57 +00001837 Stmt *lastCatchBody = nullptr;
Douglas Gregor96c79492010-04-23 22:50:49 +00001838 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1839 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001840 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001841
Douglas Gregor96c79492010-04-23 22:50:49 +00001842 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001843 buf = "if ("; // we are generating code for the first catch clause
1844 else
1845 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001846 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001847 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001848
Steve Naroffbf478ec2007-11-07 04:08:17 +00001849 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001850
Steve Naroffbf478ec2007-11-07 04:08:17 +00001851 const char *lParenLoc = strchr(startBuf, '(');
1852
Douglas Gregor96c79492010-04-23 22:50:49 +00001853 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001854 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001855 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001856 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1857 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001858 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001859 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001860 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001861
Steve Naroffedb5bc62008-02-01 20:02:07 +00001862 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001863 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001864 } else if (catchDecl) {
1865 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001866 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001867 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001868 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001869 } else if (const ObjCObjectPointerType *Ptr =
1870 t->getAs<ObjCObjectPointerType>()) {
1871 // Should be a pointer to a class.
1872 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1873 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001874 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001875 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001876 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001877 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001878 }
1879 }
1880 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001881 lastCatchBody = Catch->getCatchBody();
1882 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001883 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1884 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1885 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1886 assert((*rParenBuf == ')') && "bogus @catch paren location");
1887 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001888
Mike Stump11289f42009-09-09 15:08:12 +00001889 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001890 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001891 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001892 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001893 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001894 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001895 }
1896 // Complete the catch list...
1897 if (lastCatchBody) {
1898 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001899 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1900 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001901
Steve Naroff4adbe312008-09-11 15:29:03 +00001902 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001903 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001904 buf = "} /* last catch end */\n";
1905 buf += "else {\n";
1906 buf += " _rethrow = _caught;\n";
1907 buf += " objc_exception_try_exit(&_stack);\n";
1908 buf += "} } /* @catch end */\n";
1909 if (!S->getFinallyStmt())
1910 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001911 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Steve Naroffbf478ec2007-11-07 04:08:17 +00001913 // Set lastCurlyLoc
1914 lastCurlyLoc = lastCatchBody->getLocEnd();
1915 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001916 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001917 startLoc = finalStmt->getLocStart();
1918 startBuf = SM->getCharacterData(startLoc);
1919 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001920
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001922
Steve Naroffbf478ec2007-11-07 04:08:17 +00001923 Stmt *body = finalStmt->getFinallyBody();
1924 SourceLocation startLoc = body->getLocStart();
1925 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001926 assert(*SM->getCharacterData(startLoc) == '{' &&
1927 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001928 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001929 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001930
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001931 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001932 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001933 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001934 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroffbf478ec2007-11-07 04:08:17 +00001936 // Set lastCurlyLoc
1937 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroff6d6da252008-12-05 17:03:39 +00001939 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001940 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001941 } else { /* no finally clause - make sure we synthesize an implicit one */
1942 buf = "{ /* implicit finally clause */\n";
1943 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1944 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1945 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001946 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001947
1948 // Now check for any return/continue/go statements within the @try.
1949 // The implicit finally clause won't called if the @try contains any
1950 // jump statements.
1951 bool hasReturns = false;
1952 HasReturnStmts(S->getTryBody(), hasReturns);
1953 if (hasReturns)
1954 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001955 }
1956 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001957 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001958 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001959 return nullptr;
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001960}
1961
Mike Stump11289f42009-09-09 15:08:12 +00001962// This can't be done with ReplaceStmt(S, ThrowExpr), since
1963// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001964// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001965Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001966 // Get the start location and compute the semi location.
1967 SourceLocation startLoc = S->getLocStart();
1968 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Steve Naroffa733c7f2007-11-07 15:32:26 +00001970 assert((*startBuf == '@') && "bogus @throw location");
1971
1972 std::string buf;
1973 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001974 if (S->getThrowExpr())
1975 buf = "objc_exception_throw(";
1976 else // add an implicit argument
1977 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001978
Steve Naroff29788342008-07-25 15:41:30 +00001979 // handle "@ throw" correctly.
1980 const char *wBuf = strchr(startBuf, 'w');
1981 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001982 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Steve Naroffa733c7f2007-11-07 15:32:26 +00001984 const char *semiBuf = strchr(startBuf, ';');
1985 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001986 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001987 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00001988 return nullptr;
Steve Naroffa733c7f2007-11-07 15:32:26 +00001989}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001990
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001991Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001992 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00001993 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001994 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00001995 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001996 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Chris Lattner4431a1b2007-11-30 22:53:43 +00001998 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001999 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002000 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002001}
2002
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002003Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002004 if (!SelGetUidFunctionDecl)
2005 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002006 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2007 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002008 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002009 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002010 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2011 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002012 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002013 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002014 return SelExp;
2015}
2016
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002017CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002018 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2019 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002020 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002021 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002023 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002024 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2025 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002026
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002027 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002028 QualType pToFunc = Context->getPointerType(msgSendType);
Craig Topper8ae12032014-05-07 06:21:57 +00002029 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002030 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002031 DRE, nullptr, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCall9dd450b2009-09-21 23:43:11 +00002033 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002034
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002035 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002036 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCall7decc9e2010-11-18 06:31:45 +00002037 FT->getCallResultType(*Context),
2038 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002039 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002040}
2041
Steve Naroff50d42052007-11-01 13:24:47 +00002042static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2043 const char *&startRef, const char *&endRef) {
2044 while (startBuf < endBuf) {
2045 if (*startBuf == '<')
2046 startRef = startBuf; // mark the start.
2047 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002048 if (startRef && *startRef == '<') {
2049 endRef = startBuf; // mark the end.
2050 return true;
2051 }
2052 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002053 }
2054 startBuf++;
2055 }
2056 return false;
2057}
2058
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002059static void scanToNextArgument(const char *&argRef) {
2060 int angle = 0;
2061 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2062 if (*argRef == '<')
2063 angle++;
2064 else if (*argRef == '>')
2065 angle--;
2066 argRef++;
2067 }
2068 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2069}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002070
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002071bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002072 if (T->isObjCQualifiedIdType())
2073 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002074 if (const PointerType *PT = T->getAs<PointerType>()) {
2075 if (PT->getPointeeType()->isObjCQualifiedIdType())
2076 return true;
2077 }
2078 if (T->isObjCObjectPointerType()) {
2079 T = T->getPointeeType();
2080 return T->isObjCQualifiedInterfaceType();
2081 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002082 if (T->isArrayType()) {
2083 QualType ElemTy = Context->getBaseElementType(T);
2084 return needToScanForQualifiers(ElemTy);
2085 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002086 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002087}
2088
Steve Naroff873bd842008-07-29 18:15:38 +00002089void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2090 QualType Type = E->getType();
2091 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002092 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002093
Steve Naroffdbfc6932008-11-19 21:15:47 +00002094 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2095 Loc = ECE->getLParenLoc();
2096 EndLoc = ECE->getRParenLoc();
2097 } else {
2098 Loc = E->getLocStart();
2099 EndLoc = E->getLocEnd();
2100 }
2101 // This will defend against trying to rewrite synthesized expressions.
2102 if (Loc.isInvalid() || EndLoc.isInvalid())
2103 return;
2104
Steve Naroff873bd842008-07-29 18:15:38 +00002105 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002106 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002107 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff873bd842008-07-29 18:15:38 +00002108 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2109 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002110 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2111 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002112 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002113 InsertText(LessLoc, "/*");
2114 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002115 }
2116 }
2117}
2118
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002119void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002120 SourceLocation Loc;
2121 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002122 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002123 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2124 Loc = VD->getLocation();
2125 Type = VD->getType();
2126 }
2127 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2128 Loc = FD->getLocation();
2129 // Check for ObjC 'id' and class types that have been adorned with protocol
2130 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002131 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002132 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002133 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002134 if (!proto)
2135 return;
Alp Toker314cc812014-01-25 16:55:45 +00002136 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002137 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002138 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2139 Loc = FD->getLocation();
2140 Type = FD->getType();
2141 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002142 else
2143 return;
Mike Stump11289f42009-09-09 15:08:12 +00002144
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002145 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002146 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002147
Steve Naroff50d42052007-11-01 13:24:47 +00002148 const char *endBuf = SM->getCharacterData(Loc);
2149 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002150 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002151 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002152 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002153 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2154 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002155 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2156 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002157 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002158 InsertText(LessLoc, "/*");
2159 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002160 }
2161 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002162 if (!proto)
2163 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002164 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002165 const char *startBuf = SM->getCharacterData(Loc);
2166 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002167 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2168 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002169 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002170
Steve Naroff50d42052007-11-01 13:24:47 +00002171 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002172 // scan forward (from the decl location) for argument types.
2173 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002174 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002177 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002178 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002179 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002180 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002181 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002184 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002185 startBuf = ++endBuf;
2186 }
2187 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002188 // If the function name is derived from a macro expansion, then the
2189 // argument buffer will not follow the name. Need to speak with Chris.
2190 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002191 startBuf++; // scan forward (from the decl location) for argument types.
2192 startBuf++;
2193 }
Steve Naroff50d42052007-11-01 13:24:47 +00002194 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002195}
2196
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002197void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2198 QualType QT = ND->getType();
2199 const Type* TypePtr = QT->getAs<Type>();
2200 if (!isa<TypeOfExprType>(TypePtr))
2201 return;
2202 while (isa<TypeOfExprType>(TypePtr)) {
2203 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2204 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2205 TypePtr = QT->getAs<Type>();
2206 }
2207 // FIXME. This will not work for multiple declarators; as in:
2208 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002209 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002210 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2211 const char *startBuf = SM->getCharacterData(DeclLoc);
2212 if (ND->getInit()) {
2213 std::string Name(ND->getNameAsString());
2214 TypeAsString += " " + Name + " = ";
2215 Expr *E = ND->getInit();
2216 SourceLocation startLoc;
2217 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2218 startLoc = ECE->getLParenLoc();
2219 else
2220 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002221 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002222 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002223 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002224 }
2225 else {
2226 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002227 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002228 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002229 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002230 }
2231}
2232
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002233// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002234void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002235 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002236 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002237 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002238 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002239 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002240 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002241 SourceLocation(),
2242 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002243 SelGetUidIdent, getFuncType,
2244 nullptr, SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002245}
2246
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002247void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002248 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002249 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002250 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002251 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002252 return;
2253 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002254 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002255}
2256
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002257void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002258 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002259 const char *argPtr = TypeString.c_str();
2260 if (!strchr(argPtr, '^')) {
2261 Str += TypeString;
2262 return;
2263 }
2264 while (*argPtr) {
2265 Str += (*argPtr == '^' ? '*' : *argPtr);
2266 argPtr++;
2267 }
2268}
2269
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002270// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002271void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2272 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002273 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002274 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002275 const char *argPtr = TypeString.c_str();
2276 int paren = 0;
2277 while (*argPtr) {
2278 switch (*argPtr) {
2279 case '(':
2280 Str += *argPtr;
2281 paren++;
2282 break;
2283 case ')':
2284 Str += *argPtr;
2285 paren--;
2286 break;
2287 case '^':
2288 Str += '*';
2289 if (paren == 1)
2290 Str += VD->getNameAsString();
2291 break;
2292 default:
2293 Str += *argPtr;
2294 break;
2295 }
2296 argPtr++;
2297 }
2298}
2299
2300
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002301void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2302 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2303 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2304 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2305 if (!proto)
2306 return;
Alp Toker314cc812014-01-25 16:55:45 +00002307 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002308 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002309 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002310 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002311 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002313 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002314 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002315 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002316 if (i+1 < numArgs)
2317 FdStr += ", ";
2318 }
2319 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002320 InsertText(FunLocStart, FdStr);
Craig Topper8ae12032014-05-07 06:21:57 +00002321 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002322}
2323
Benjamin Kramer60509af2013-09-09 14:48:42 +00002324// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2325void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2326 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002327 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002328 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002329 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002330 QualType argT = Context->getObjCIdType();
2331 assert(!argT.isNull() && "Can't find 'id' type");
2332 ArgTys.push_back(argT);
2333 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002334 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002335 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002336 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002337 SourceLocation(),
2338 SourceLocation(),
2339 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002340 nullptr, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002341}
2342
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002343// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002344void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002345 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002346 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002347 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002348 assert(!argT.isNull() && "Can't find 'id' type");
2349 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002350 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002351 assert(!argT.isNull() && "Can't find 'SEL' type");
2352 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002353 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002354 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002355 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002356 SourceLocation(),
2357 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002358 msgSendIdent, msgSendType,
2359 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002360}
2361
Steve Naroff7fa2f042007-11-15 10:28:18 +00002362// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002363void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002364 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002365 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002366 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002367 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002368 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002369 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2370 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2371 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002372 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002375 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002376 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002377 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002378 SourceLocation(),
2379 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002380 msgSendIdent, msgSendType,
2381 nullptr, SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002382}
2383
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002384// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002385void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002386 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002387 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002388 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002389 assert(!argT.isNull() && "Can't find 'id' type");
2390 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002391 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002392 assert(!argT.isNull() && "Can't find 'SEL' type");
2393 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002394 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002395 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002396 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002397 SourceLocation(),
2398 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002399 msgSendIdent, msgSendType,
2400 nullptr, SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002401}
2402
Mike Stump11289f42009-09-09 15:08:12 +00002403// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002404// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002405void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002406 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002407 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002408 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002409 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002410 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002411 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002412 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2413 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2414 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002415 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002416 assert(!argT.isNull() && "Can't find 'SEL' type");
2417 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002418 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002419 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002420 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002421 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002422 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002423 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002424 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002425 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002426}
2427
Steve Naroff2e4e3852008-05-08 22:02:18 +00002428// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002429void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002430 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002431 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002432 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002433 assert(!argT.isNull() && "Can't find 'id' type");
2434 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002435 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002436 assert(!argT.isNull() && "Can't find 'SEL' type");
2437 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002438 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002439 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002440 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002441 SourceLocation(),
2442 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002443 msgSendIdent, msgSendType,
2444 nullptr, SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002445}
2446
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002447// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002448void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002449 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002450 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002451 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002452 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002453 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002454 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002455 SourceLocation(),
2456 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002457 getClassIdent, getClassType,
2458 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002459}
2460
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002461// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2462void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2463 IdentifierInfo *getSuperClassIdent =
2464 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002465 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002466 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002467 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002469 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002470 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002471 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002472 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002473 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002474 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002475}
2476
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002477// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002478void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002479 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002480 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002481 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002482 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002483 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002484 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002485 SourceLocation(),
2486 SourceLocation(),
2487 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002488 nullptr, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002489}
2490
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002491Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002492 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffce8e8862008-03-15 00:55:56 +00002493 QualType strType = getConstantStringStructType();
2494
2495 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002496
2497 std::string tmpName = InFileName;
2498 unsigned i;
2499 for (i=0; i < tmpName.length(); i++) {
2500 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002501 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002502 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002503 tmpName[i] = '_';
2504 }
2505 S += tmpName;
2506 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002507 S += utostr(NumObjCStringLiterals++);
2508
Steve Naroff00a31762008-03-27 22:29:16 +00002509 Preamble += "static __NSConstantStringImpl " + S;
2510 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2511 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002512 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002513 std::string prettyBufS;
2514 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002515 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002516 Preamble += prettyBuf.str();
2517 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002518 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002519
2520 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002521 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002522 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002523 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002524 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002525 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002526 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002527 VK_RValue, OK_Ordinary,
2528 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002529 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002530 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002531 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002532 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002533 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002534 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002535}
2536
Steve Naroff7fa2f042007-11-15 10:28:18 +00002537// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002538QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002539 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002540 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002541 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002542 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002543 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002544
Steve Naroff7fa2f042007-11-15 10:28:18 +00002545 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002546 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002547 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002548 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002549
Steve Naroff7fa2f042007-11-15 10:28:18 +00002550 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002551 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002552 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002553 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002554 SourceLocation(), nullptr,
2555 FieldTypes[i], nullptr,
2556 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002557 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002558 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregord5058122010-02-11 01:19:42 +00002561 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002562 }
2563 return Context->getTagDeclType(SuperStructDecl);
2564}
2565
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002566QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002567 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002568 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002569 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002570 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002571 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002572
Steve Naroffce8e8862008-03-15 00:55:56 +00002573 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002574 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002575 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002576 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002577 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002578 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002579 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002580 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002581
Steve Naroffce8e8862008-03-15 00:55:56 +00002582 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002583 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002584 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2585 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002586 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002587 SourceLocation(), nullptr,
2588 FieldTypes[i], nullptr,
2589 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002590 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002591 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002592 }
2593
Douglas Gregord5058122010-02-11 01:19:42 +00002594 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002595 }
2596 return Context->getTagDeclType(ConstantStringDecl);
2597}
2598
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002599CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2600 QualType msgSendType,
2601 QualType returnType,
2602 SmallVectorImpl<QualType> &ArgTypes,
2603 SmallVectorImpl<Expr*> &MsgExprs,
2604 ObjCMethodDecl *Method) {
2605 // Create a reference to the objc_msgSend_stret() declaration.
2606 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2607 false, msgSendType,
2608 VK_LValue, SourceLocation());
2609 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2610 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2611 Context->getPointerType(Context->VoidTy),
2612 CK_BitCast, STDRE);
2613 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002614 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2615 Method ? Method->isVariadic()
2616 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002617 castType = Context->getPointerType(castType);
2618 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2619 cast);
2620
2621 // Don't forget the parens to enforce the proper binding.
2622 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2623
2624 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002625 CallExpr *STCE = new (Context) CallExpr(
2626 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002627 return STCE;
2628
2629}
2630
2631
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002632Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2633 SourceLocation StartLoc,
2634 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002635 if (!SelGetUidFunctionDecl)
2636 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002637 if (!MsgSendFunctionDecl)
2638 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002639 if (!MsgSendSuperFunctionDecl)
2640 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002641 if (!MsgSendStretFunctionDecl)
2642 SynthMsgSendStretFunctionDecl();
2643 if (!MsgSendSuperStretFunctionDecl)
2644 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002645 if (!MsgSendFpretFunctionDecl)
2646 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002647 if (!GetClassFunctionDecl)
2648 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002649 if (!GetSuperClassFunctionDecl)
2650 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002651 if (!GetMetaClassFunctionDecl)
2652 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002653
Steve Naroff7fa2f042007-11-15 10:28:18 +00002654 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002655 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2656 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00002657 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroffd9803712009-04-29 16:37:50 +00002658 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002659 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002660 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002661 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002662 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002663 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002664 }
Mike Stump11289f42009-09-09 15:08:12 +00002665
Steve Naroff574440f2007-10-24 22:48:43 +00002666 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002667 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002668 switch (Exp->getReceiverKind()) {
2669 case ObjCMessageExpr::SuperClass: {
2670 MsgSendFlavor = MsgSendSuperFunctionDecl;
2671 if (MsgSendStretFlavor)
2672 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2673 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002674
Douglas Gregor9a129192010-04-21 00:45:42 +00002675 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002676
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002677 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002678
Douglas Gregor9a129192010-04-21 00:45:42 +00002679 // set the receiver to self, the first argument to all methods.
2680 InitExprs.push_back(
2681 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002682 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002683 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002684 false,
John McCall7decc9e2010-11-18 06:31:45 +00002685 Context->getObjCIdType(),
2686 VK_RValue,
2687 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002688 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002689
Douglas Gregor9a129192010-04-21 00:45:42 +00002690 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002692 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002693 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2694 &ClsExprs[0],
2695 ClsExprs.size(),
2696 StartLoc,
2697 EndLoc);
2698 // (Class)objc_getClass("CurrentClass")
2699 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2700 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002701 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002702 ClsExprs.clear();
2703 ClsExprs.push_back(ArgExpr);
2704 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2705 &ClsExprs[0], ClsExprs.size(),
2706 StartLoc, EndLoc);
2707
2708 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2709 // To turn off a warning, type-cast to 'id'
2710 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2711 NoTypeInfoCStyleCastExpr(Context,
2712 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002713 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002714 // struct objc_super
2715 QualType superType = getSuperStructType();
2716 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002717
Francois Pichet0706d202011-09-17 17:15:52 +00002718 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002719 SynthSuperConstructorFunctionDecl();
2720 // Simulate a constructor call...
2721 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002722 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002723 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002724 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002725 superType, VK_LValue,
2726 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002727 // The code for super is a little tricky to prevent collision with
2728 // the structure definition in the header. The rewriter has it's own
2729 // internal definition (__rw_objc_super) that is uses. This is why
2730 // we need the cast below. For example:
2731 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2732 //
John McCalle3027922010-08-25 11:45:40 +00002733 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002734 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002735 VK_RValue, OK_Ordinary,
2736 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002737 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2738 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002739 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002740 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 // (struct objc_super) { <exprs from above> }
2742 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002743 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002744 SourceLocation());
2745 TypeSourceInfo *superTInfo
2746 = Context->getTrivialTypeSourceInfo(superType);
2747 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002748 superType, VK_LValue,
2749 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002750 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002751 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002752 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002753 VK_RValue, OK_Ordinary,
2754 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002755 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002756 MsgExprs.push_back(SuperRep);
2757 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002758 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002759
2760 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002761 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002762 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002763 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002764 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002765 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2767 &ClsExprs[0],
2768 ClsExprs.size(),
2769 StartLoc, EndLoc);
2770 MsgExprs.push_back(Cls);
2771 break;
2772 }
2773
2774 case ObjCMessageExpr::SuperInstance:{
2775 MsgSendFlavor = MsgSendSuperFunctionDecl;
2776 if (MsgSendStretFlavor)
2777 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2778 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2779 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002780 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002781
2782 InitExprs.push_back(
2783 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002784 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002786 false,
John McCall7decc9e2010-11-18 06:31:45 +00002787 Context->getObjCIdType(),
2788 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002789 ); // set the 'receiver'.
2790
2791 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002792 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002793 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002794 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2795 &ClsExprs[0],
2796 ClsExprs.size(),
2797 StartLoc, EndLoc);
2798 // (Class)objc_getClass("CurrentClass")
2799 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2800 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002801 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002802 ClsExprs.clear();
2803 ClsExprs.push_back(ArgExpr);
2804 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2805 &ClsExprs[0], ClsExprs.size(),
2806 StartLoc, EndLoc);
2807
2808 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2809 // To turn off a warning, type-cast to 'id'
2810 InitExprs.push_back(
2811 // set 'super class', using class_getSuperclass().
2812 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002813 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002814 // struct objc_super
2815 QualType superType = getSuperStructType();
2816 Expr *SuperRep;
2817
Francois Pichet0706d202011-09-17 17:15:52 +00002818 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002819 SynthSuperConstructorFunctionDecl();
2820 // Simulate a constructor call...
2821 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002822 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002823 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002824 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002825 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002826 // The code for super is a little tricky to prevent collision with
2827 // the structure definition in the header. The rewriter has it's own
2828 // internal definition (__rw_objc_super) that is uses. This is why
2829 // we need the cast below. For example:
2830 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2831 //
John McCalle3027922010-08-25 11:45:40 +00002832 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002833 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002834 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002835 SourceLocation());
2836 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2837 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002838 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 } else {
2840 // (struct objc_super) { <exprs from above> }
2841 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002842 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002843 SourceLocation());
2844 TypeSourceInfo *superTInfo
2845 = Context->getTrivialTypeSourceInfo(superType);
2846 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002847 superType, VK_RValue, ILE,
2848 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002849 }
2850 MsgExprs.push_back(SuperRep);
2851 break;
2852 }
2853
2854 case ObjCMessageExpr::Instance: {
2855 // Remove all type-casts because it may contain objc-style types; e.g.
2856 // Foo<Proto> *.
2857 Expr *recExpr = Exp->getInstanceReceiver();
2858 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2859 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002860 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2861 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2862 ? CK_BlockPointerToObjCPointerCast
2863 : CK_CPointerToObjCPointerCast;
2864
Douglas Gregor9a129192010-04-21 00:45:42 +00002865 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002866 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002867 MsgExprs.push_back(recExpr);
2868 break;
2869 }
2870 }
2871
Steve Naroffa397efd2007-11-03 11:27:19 +00002872 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002873 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002874 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002875 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002876 &SelExprs[0], SelExprs.size(),
2877 StartLoc,
2878 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002879 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002880
Steve Naroff574440f2007-10-24 22:48:43 +00002881 // Now push any user supplied arguments.
2882 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002883 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002884 // Make all implicit casts explicit...ICE comes in handy:-)
2885 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2886 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002887 QualType type = ICE->getType();
2888 if (needToScanForQualifiers(type))
2889 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002890 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002891 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002892 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002893 CastKind CK;
2894 if (SubExpr->getType()->isIntegralType(*Context) &&
2895 type->isBooleanType()) {
2896 CK = CK_IntegralToBoolean;
2897 } else if (type->isObjCObjectPointerType()) {
2898 if (SubExpr->getType()->isBlockPointerType()) {
2899 CK = CK_BlockPointerToObjCPointerCast;
2900 } else if (SubExpr->getType()->isPointerType()) {
2901 CK = CK_CPointerToObjCPointerCast;
2902 } else {
2903 CK = CK_BitCast;
2904 }
2905 } else {
2906 CK = CK_BitCast;
2907 }
2908
2909 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002910 }
2911 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002912 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002913 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002914 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002915 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002916 CastKind CK;
2917 if (userExpr->getType()->isIntegralType(*Context)) {
2918 CK = CK_IntegralToPointer;
2919 } else if (userExpr->getType()->isBlockPointerType()) {
2920 CK = CK_BlockPointerToObjCPointerCast;
2921 } else if (userExpr->getType()->isPointerType()) {
2922 CK = CK_CPointerToObjCPointerCast;
2923 } else {
2924 CK = CK_BitCast;
2925 }
John McCall97513962010-01-15 18:39:57 +00002926 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002927 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002930 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002931 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2932 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002933 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002934 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002935 }
Steve Narofff36987c2007-11-04 22:37:50 +00002936 // Generate the funky cast.
2937 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002938 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002939 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002940
Steve Narofff36987c2007-11-04 22:37:50 +00002941 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002942 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2943 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2944 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002945 ArgTypes.push_back(Context->getObjCIdType());
2946 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002947 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002948 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002949 for (const auto *PI : OMD->params()) {
2950 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002951 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002952 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002953 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002954 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002955 ArgTypes.push_back(t);
2956 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002957 returnType = Exp->getType();
2958 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002959 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002960 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002961 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002962 }
2963 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002964 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Narofff36987c2007-11-04 22:37:50 +00002966 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002967 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002968 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002969
Mike Stump11289f42009-09-09 15:08:12 +00002970 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002971 // If we don't do this cast, we get the following bizarre warning/note:
2972 // xx.m:13: warning: function called through a non-compatible type
2973 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002974 cast = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002976 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002977
Steve Narofff36987c2007-11-04 22:37:50 +00002978 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002979 // If we don't have a method decl, force a variadic cast.
2980 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002981 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002982 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002983 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002984 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002985 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002986
2987 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002988 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002989
John McCall9dd450b2009-09-21 23:43:11 +00002990 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002991 CallExpr *CE = new (Context)
2992 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002993 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002994 if (MsgSendStretFlavor) {
2995 // We have the method which returns a struct/union. Must also generate
2996 // call to objc_msgSend_stret and hang both varieties on a conditional
2997 // expression which dictate which one to envoke depending on size of
2998 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002999
3000 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3001 msgSendType, returnType,
3002 ArgTypes, MsgExprs,
3003 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003004
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003005 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003006 UnaryExprOrTypeTraitExpr *sizeofExpr =
3007 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3008 Context->getTrivialTypeSourceInfo(returnType),
3009 Context->getSizeType(), SourceLocation(),
3010 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003011 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3012 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3013 // For X86 it is more complicated and some kind of target specific routine
3014 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003015 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003016 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003017 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3018 llvm::APInt(IntSize, 8),
3019 Context->IntTy,
3020 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003021 BinaryOperator *lessThanExpr =
3022 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003023 VK_RValue, OK_Ordinary, SourceLocation(),
3024 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003025 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003026 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003027 new (Context) ConditionalOperator(lessThanExpr,
3028 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003029 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003030 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003031 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3032 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003033 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003034 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003035 return ReplacingStmt;
3036}
3037
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003038Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003039 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3040 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003041
Steve Naroff574440f2007-10-24 22:48:43 +00003042 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003043 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003044
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003045 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003046 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003047}
3048
Steve Naroffd9803712009-04-29 16:37:50 +00003049// typedef struct objc_object Protocol;
3050QualType RewriteObjC::getProtocolType() {
3051 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003052 TypeSourceInfo *TInfo
3053 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003054 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003055 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003056 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003057 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003058 }
3059 return Context->getTypeDeclType(ProtocolTypeDecl);
3060}
3061
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003062/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003063/// a synthesized/forward data reference (to the protocol's metadata).
3064/// The forward references (and metadata) are generated in
3065/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003066Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003067 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3068 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003069 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003070 SourceLocation(), ID, getProtocolType(),
3071 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003072 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3073 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003074 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003075 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003076 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003077 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003078 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003079 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003080 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003081 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003082 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003083 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003084
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003085}
3086
Mike Stump11289f42009-09-09 15:08:12 +00003087bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003088 const char *endBuf) {
3089 while (startBuf < endBuf) {
3090 if (*startBuf == '#') {
3091 // Skip whitespace.
3092 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3093 ;
3094 if (!strncmp(startBuf, "if", strlen("if")) ||
3095 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3096 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3097 !strncmp(startBuf, "define", strlen("define")) ||
3098 !strncmp(startBuf, "undef", strlen("undef")) ||
3099 !strncmp(startBuf, "else", strlen("else")) ||
3100 !strncmp(startBuf, "elif", strlen("elif")) ||
3101 !strncmp(startBuf, "endif", strlen("endif")) ||
3102 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3103 !strncmp(startBuf, "include", strlen("include")) ||
3104 !strncmp(startBuf, "import", strlen("import")) ||
3105 !strncmp(startBuf, "include_next", strlen("include_next")))
3106 return true;
3107 }
3108 startBuf++;
3109 }
3110 return false;
3111}
3112
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003113/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003114/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003115void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003116 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003117 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003118 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003119 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003120 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003121 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003122 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003123 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003124 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003125 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003126 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003127
Steve Naroffdde78982007-11-14 19:25:57 +00003128 const char *startBuf = SM->getCharacterData(LocStart);
3129 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003130
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003131 // If no ivars and no root or if its root, directly or indirectly,
3132 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003133 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003134 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003135 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003136 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003137 return;
3138 }
Mike Stump11289f42009-09-09 15:08:12 +00003139
3140 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003141 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003142 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003143 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003144 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003145 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003146
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003147 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003148 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003149 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003150 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003151 // If the buffer contains preprocessor directives, we do more fine-grained
3152 // rewrites. This is intended to fix code that looks like (which occurs in
3153 // NSURL.h, for example):
3154 //
3155 // #ifdef XYZ
3156 // @interface Foo : NSObject
3157 // #else
3158 // @interface FooBar : NSObject
3159 // #endif
3160 // {
3161 // int i;
3162 // }
3163 // @end
3164 //
3165 // This clause is segregated to avoid breaking the common case.
3166 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003167 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003168 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003169 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003170 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003171
Chris Lattnerf5b77512009-02-20 18:18:36 +00003172 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003173 // advance to the end of the referenced protocols.
3174 while (endHeader < cursor && *endHeader != '>') endHeader++;
3175 endHeader++;
3176 }
3177 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003178 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003179 } else {
3180 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003181 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003182 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003183 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003184 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003185 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003186 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003187 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003188 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003189
Steve Naroffdde78982007-11-14 19:25:57 +00003190 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003191 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003192 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003193 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003194 }
3195 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003196
Steve Naroffdde78982007-11-14 19:25:57 +00003197 // Now comment out any visibility specifiers.
3198 while (cursor < endBuf) {
3199 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003200 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003201 // Skip whitespace.
3202 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3203 /*scan*/;
3204
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003205 // FIXME: presence of @public, etc. inside comment results in
3206 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003207 if (!strncmp(cursor, "public", strlen("public")) ||
3208 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003209 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003210 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003211 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003212 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003213 // FIXME: If there are cases where '<' is used in ivar declaration part
3214 // of user code, then scan the ivar list and use needToScanForQualifiers
3215 // for type checking.
3216 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003217 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003218 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003219 cursor = strchr(cursor, '>');
3220 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003221 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003222 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003223 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003224 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003225 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003226 }
Steve Naroffdde78982007-11-14 19:25:57 +00003227 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003228 }
Steve Naroffdde78982007-11-14 19:25:57 +00003229 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003230 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003231 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003232 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003233 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003235 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003236 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003237 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003238 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003239 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003240 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003241 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikie83d382b2011-09-23 05:06:16 +00003242 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003243}
3244
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003245//===----------------------------------------------------------------------===//
3246// Meta Data Emission
3247//===----------------------------------------------------------------------===//
3248
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003249
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003250/// RewriteImplementations - This routine rewrites all method implementations
3251/// and emits meta-data.
3252
Steve Narofff8cfd162008-11-13 20:07:04 +00003253void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003254 int ClsDefCount = ClassImplementation.size();
3255 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003256
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003257 // Rewrite implemented methods
3258 for (int i = 0; i < ClsDefCount; i++)
3259 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003260
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003261 for (int i = 0; i < CatDefCount; i++)
3262 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003263}
Mike Stump11289f42009-09-09 15:08:12 +00003264
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003265void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3266 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003267 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003268 assert(BlockByRefDeclNo.count(VD) &&
3269 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003270 if (def)
3271 ResultStr += "struct ";
3272 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003273 "_" + utostr(BlockByRefDeclNo[VD]) ;
3274}
3275
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003276static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3277 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3278 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3279 return false;
3280}
3281
Steve Naroff677ab3a2008-10-27 17:20:55 +00003282std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003283 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003284 std::string Tag) {
3285 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003286 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003287 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003288 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003289 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003290
Steve Naroff677ab3a2008-10-27 17:20:55 +00003291 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003292
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003293 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003294 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003295 // block (to reference imported block decl refs).
3296 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003297 } else if (BD->param_empty()) {
3298 S += "(" + StructRef + " *__cself)";
3299 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003300 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003301 assert(FT && "SynthesizeBlockFunc: No function proto");
3302 S += '(';
3303 // first add the implicit argument.
3304 S += StructRef + " *__cself, ";
3305 std::string ParamStr;
3306 for (BlockDecl::param_iterator AI = BD->param_begin(),
3307 E = BD->param_end(); AI != E; ++AI) {
3308 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003309 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003310 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003311 (void)convertBlockPointerToFunctionPointer(QT);
3312 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003313 S += ParamStr;
3314 }
3315 if (FT->isVariadic()) {
3316 if (!BD->param_empty()) S += ", ";
3317 S += "...";
3318 }
3319 S += ')';
3320 }
3321 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003322
Steve Naroff677ab3a2008-10-27 17:20:55 +00003323 // Create local declarations to avoid rewriting all closure decl ref exprs.
3324 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003325 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003326 E = BlockByRefDecls.end(); I != E; ++I) {
3327 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003328 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003329 std::string TypeString;
3330 RewriteByRefString(TypeString, Name, (*I));
3331 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003332 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003333 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003334 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003335 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003336 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003337 E = BlockByCopyDecls.end(); I != E; ++I) {
3338 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003339 // Handle nested closure invocation. For example:
3340 //
3341 // void (^myImportedClosure)(void);
3342 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003343 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003344 // void (^anotherClosure)(void);
3345 // anotherClosure = ^(void) {
3346 // myImportedClosure(); // import and invoke the closure
3347 // };
3348 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003349 if (isTopLevelBlockPointerType((*I)->getType())) {
3350 RewriteBlockPointerTypeVariable(S, (*I));
3351 S += " = (";
3352 RewriteBlockPointerType(S, (*I)->getType());
3353 S += ")";
3354 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3355 }
3356 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003357 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003358 QualType QT = (*I)->getType();
3359 if (HasLocalVariableExternalStorage(*I))
3360 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003361 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003362 S += Name + " = __cself->" +
3363 (*I)->getNameAsString() + "; // bound by copy\n";
3364 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003365 }
3366 std::string RewrittenStr = RewrittenBlockExprs[CE];
3367 const char *cstr = RewrittenStr.c_str();
3368 while (*cstr++ != '{') ;
3369 S += cstr;
3370 S += "\n";
3371 return S;
3372}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003373
Steve Naroff677ab3a2008-10-27 17:20:55 +00003374std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003375 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003376 std::string Tag) {
3377 std::string StructRef = "struct " + Tag;
3378 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003379
Steve Naroff677ab3a2008-10-27 17:20:55 +00003380 S += funcName;
3381 S += "_block_copy_" + utostr(i);
3382 S += "(" + StructRef;
3383 S += "*dst, " + StructRef;
3384 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003385 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003386 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003387 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003388 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003389 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003390 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003391 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003392 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003393 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003394 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003395 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003396 else
3397 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003398 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003399 S += "}\n";
3400
Steve Naroff677ab3a2008-10-27 17:20:55 +00003401 S += "\nstatic void __";
3402 S += funcName;
3403 S += "_block_dispose_" + utostr(i);
3404 S += "(" + StructRef;
3405 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003406 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003407 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003408 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003409 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003410 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003411 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003412 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003413 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003414 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003415 else
3416 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003417 }
Mike Stump11289f42009-09-09 15:08:12 +00003418 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003419 return S;
3420}
3421
Steve Naroff30484702009-12-06 21:14:13 +00003422std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3423 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003424 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003425 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003426
Steve Naroff677ab3a2008-10-27 17:20:55 +00003427 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003428 S += " struct " + Desc;
3429 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003430
Steve Naroff30484702009-12-06 21:14:13 +00003431 Constructor += "(void *fp, "; // Invoke function pointer.
3432 Constructor += "struct " + Desc; // Descriptor pointer.
3433 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003434
Steve Naroff677ab3a2008-10-27 17:20:55 +00003435 if (BlockDeclRefs.size()) {
3436 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003437 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003438 E = BlockByCopyDecls.end(); I != E; ++I) {
3439 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003440 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003441 std::string ArgName = "_" + FieldName;
3442 // Handle nested closure invocation. For example:
3443 //
3444 // void (^myImportedBlock)(void);
3445 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003446 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003447 // void (^anotherBlock)(void);
3448 // anotherBlock = ^(void) {
3449 // myImportedBlock(); // import and invoke the closure
3450 // };
3451 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003452 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003453 S += "struct __block_impl *";
3454 Constructor += ", void *" + ArgName;
3455 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003456 QualType QT = (*I)->getType();
3457 if (HasLocalVariableExternalStorage(*I))
3458 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003459 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3460 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003461 Constructor += ", " + ArgName;
3462 }
3463 S += FieldName + ";\n";
3464 }
3465 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003466 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003467 E = BlockByRefDecls.end(); I != E; ++I) {
3468 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003469 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003470 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003471 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003472 std::string TypeString;
3473 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003474 TypeString += " *";
3475 FieldName = TypeString + FieldName;
3476 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003477 Constructor += ", " + ArgName;
3478 }
3479 S += FieldName + "; // by ref\n";
3480 }
3481 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003482 Constructor += ", int flags=0)";
3483 // Initialize all "by copy" arguments.
3484 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003485 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003486 E = BlockByCopyDecls.end(); I != E; ++I) {
3487 std::string Name = (*I)->getNameAsString();
3488 if (firsTime) {
3489 Constructor += " : ";
3490 firsTime = false;
3491 }
3492 else
3493 Constructor += ", ";
3494 if (isTopLevelBlockPointerType((*I)->getType()))
3495 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3496 else
3497 Constructor += Name + "(_" + Name + ")";
3498 }
3499 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003500 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003501 E = BlockByRefDecls.end(); I != E; ++I) {
3502 std::string Name = (*I)->getNameAsString();
3503 if (firsTime) {
3504 Constructor += " : ";
3505 firsTime = false;
3506 }
3507 else
3508 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003509 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003510 }
3511
3512 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003513 if (GlobalVarDecl)
3514 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3515 else
3516 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003517 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003518
Steve Naroff30484702009-12-06 21:14:13 +00003519 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003520 } else {
3521 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003522 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003523 if (GlobalVarDecl)
3524 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3525 else
3526 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003527 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3528 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003529 }
3530 Constructor += " ";
3531 Constructor += "}\n";
3532 S += Constructor;
3533 S += "};\n";
3534 return S;
3535}
3536
Steve Naroff30484702009-12-06 21:14:13 +00003537std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3538 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003539 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003540 unsigned hasCopy) {
3541 std::string S = "\nstatic struct " + DescTag;
3542
3543 S += " {\n unsigned long reserved;\n";
3544 S += " unsigned long Block_size;\n";
3545 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003546 S += " void (*copy)(struct ";
3547 S += ImplTag; S += "*, struct ";
3548 S += ImplTag; S += "*);\n";
3549
3550 S += " void (*dispose)(struct ";
3551 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003552 }
3553 S += "} ";
3554
3555 S += DescTag + "_DATA = { 0, sizeof(struct ";
3556 S += ImplTag + ")";
3557 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003558 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3559 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003560 }
3561 S += "};\n";
3562 return S;
3563}
3564
Steve Naroff677ab3a2008-10-27 17:20:55 +00003565void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003566 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003567 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003568 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003569 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003570 bool RewriteSC = (GlobalVarDecl &&
3571 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003572 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003573 GlobalVarDecl->getType().getCVRQualifiers());
3574 if (RewriteSC) {
3575 std::string SC(" void __");
3576 SC += GlobalVarDecl->getNameAsString();
3577 SC += "() {}";
3578 InsertText(FunLocStart, SC);
3579 }
3580
Steve Naroff677ab3a2008-10-27 17:20:55 +00003581 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003582 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3583 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003584 // Need to copy-in the inner copied-in variables not actually used in this
3585 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003586 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003587 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003588 ValueDecl *VD = Exp->getDecl();
3589 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003590 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003591 BlockByCopyDeclsPtrSet.insert(VD);
3592 BlockByCopyDecls.push_back(VD);
3593 }
John McCall113bee02012-03-10 09:33:50 +00003594 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003595 BlockByRefDeclsPtrSet.insert(VD);
3596 BlockByRefDecls.push_back(VD);
3597 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003598 // imported objects in the inner blocks not used in the outer
3599 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003600 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003601 VD->getType()->isObjCObjectPointerType() ||
3602 VD->getType()->isBlockPointerType())
3603 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003604 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003605
Daniel Dunbar56df9772010-08-17 22:39:59 +00003606 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3607 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003608
Steve Naroff30484702009-12-06 21:14:13 +00003609 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003610
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003611 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003612
Steve Naroff30484702009-12-06 21:14:13 +00003613 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003614
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003615 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003616
3617 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003618 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003619 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003620 }
Steve Naroff30484702009-12-06 21:14:13 +00003621 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3622 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003623 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003624
Steve Naroff677ab3a2008-10-27 17:20:55 +00003625 BlockDeclRefs.clear();
3626 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003627 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003628 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003629 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003630 ImportedBlockDecls.clear();
3631 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003632 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003633 // Must insert any 'const/volatile/static here. Since it has been
3634 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003635 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003636 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003637 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003638 if (GlobalVarDecl->getType().isConstQualified())
3639 SC += "const ";
3640 if (GlobalVarDecl->getType().isVolatileQualified())
3641 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003642 if (GlobalVarDecl->getType().isRestrictQualified())
3643 SC += "restrict ";
3644 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003645 }
3646
Steve Naroff677ab3a2008-10-27 17:20:55 +00003647 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003648 InnerDeclRefsCount.clear();
3649 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003650 RewrittenBlockExprs.clear();
3651}
3652
3653void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3654 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003655 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003656
Steve Naroff677ab3a2008-10-27 17:20:55 +00003657 SynthesizeBlockLiterals(FunLocStart, FuncName);
3658}
3659
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003660static void BuildUniqueMethodName(std::string &Name,
3661 ObjCMethodDecl *MD) {
3662 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003663 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003664 Name += "__" + MD->getSelector().getAsString();
3665 // Convert colons to underscores.
3666 std::string::size_type loc = 0;
3667 while ((loc = Name.find(":", loc)) != std::string::npos)
3668 Name.replace(loc, 1, "_");
3669}
3670
Steve Naroff677ab3a2008-10-27 17:20:55 +00003671void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003672 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3673 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003674 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003675 std::string FuncName;
3676 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003677 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003678}
3679
3680void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00003681 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00003682 if (*CI) {
3683 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3684 GetBlockDeclRefExprs(CBE->getBody());
3685 else
3686 GetBlockDeclRefExprs(*CI);
3687 }
3688 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003689 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3690 if (DRE->refersToEnclosingLocal()) {
3691 // FIXME: Handle enums.
3692 if (!isa<FunctionDecl>(DRE->getDecl()))
3693 BlockDeclRefs.push_back(DRE);
3694 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3695 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003696 }
John McCall113bee02012-03-10 09:33:50 +00003697 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003698
Steve Naroff677ab3a2008-10-27 17:20:55 +00003699 return;
3700}
3701
Craig Topper5603df42013-07-05 19:34:19 +00003702void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3703 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00003704 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00003705 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003706 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003707 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3708 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003709 GetInnerBlockDeclRefExprs(CBE->getBody(),
3710 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003711 InnerContexts);
3712 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003713 else
3714 GetInnerBlockDeclRefExprs(*CI,
3715 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003716 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003717
3718 }
3719 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003720 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3721 if (DRE->refersToEnclosingLocal()) {
3722 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3723 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3724 InnerBlockDeclRefs.push_back(DRE);
3725 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3726 if (Var->isFunctionOrMethodVarDecl())
3727 ImportedLocalExternalDecls.insert(Var);
3728 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003729 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003730
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003731 return;
3732}
3733
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003734/// convertFunctionTypeOfBlocks - This routine converts a function type
3735/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003736/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003737/// all block pointers to function pointers.
3738QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3739 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3740 // FTP will be null for closures that don't take arguments.
3741 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003742 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003743 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003744 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003745
3746 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003747 for (auto &I : FTP->param_types()) {
3748 QualType t = I;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003749 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003750 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003751 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003752 ArgTypes.push_back(t);
3753 }
3754 }
3755 QualType FuncType;
3756 // FIXME. Does this work if block takes no argument but has a return type
3757 // which is of block type?
3758 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003759 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003760 else FuncType = QualType(FT, 0);
3761 return FuncType;
3762}
3763
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003764Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003765 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00003766 const BlockPointerType *CPT = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003767
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003768 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003769 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003770 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003772 }
3773 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3774 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3775 }
3776 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3777 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3778 else if (const ConditionalOperator *CEXPR =
3779 dyn_cast<ConditionalOperator>(BlockExp)) {
3780 Expr *LHSExp = CEXPR->getLHS();
3781 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3782 Expr *RHSExp = CEXPR->getRHS();
3783 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3784 Expr *CONDExp = CEXPR->getCond();
3785 ConditionalOperator *CondExpr =
3786 new (Context) ConditionalOperator(CONDExp,
3787 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003788 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003789 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003790 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003791 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3792 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003793 } else if (const PseudoObjectExpr *POE
3794 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3795 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003796 } else {
3797 assert(1 && "RewriteBlockClass: Bad type");
3798 }
3799 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003800 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003802 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003803 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003804
Abramo Bagnara6150c882010-05-11 21:36:43 +00003805 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003806 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003807 &Context->Idents.get("__block_impl"));
3808 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003809
Steve Naroff350b6652008-10-30 10:07:53 +00003810 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003811 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003812
Steve Naroff350b6652008-10-30 10:07:53 +00003813 // Push the block argument type.
3814 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003815 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003816 for (auto &I : FTP->param_types()) {
3817 QualType t = I;
Steve Naroff350b6652008-10-30 10:07:53 +00003818 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003819 if (!convertBlockPointerToFunctionPointer(t))
3820 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003821 ArgTypes.push_back(t);
3822 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003823 }
Steve Naroff350b6652008-10-30 10:07:53 +00003824 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003825 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003826
Steve Naroff350b6652008-10-30 10:07:53 +00003827 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003828
John McCall97513962010-01-15 18:39:57 +00003829 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003830 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003831 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003832 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003833 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3834 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003835 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003836
Craig Topper8ae12032014-05-07 06:21:57 +00003837 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003838 SourceLocation(),
3839 &Context->Idents.get("FuncPtr"),
Craig Topper8ae12032014-05-07 06:21:57 +00003840 Context->VoidPtrTy, nullptr,
3841 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003842 ICIS_NoInit);
Ted Kremenek5a201952009-02-07 01:47:29 +00003843 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003844 FD->getType(), VK_LValue,
3845 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00003846
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003847
John McCall97513962010-01-15 18:39:57 +00003848 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00003849 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00003850 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003851
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003852 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003853 // Add the implicit argument.
3854 BlkExprs.push_back(BlkCast);
3855 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003856 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003857 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003858 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003860 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003861 Exp->getType(), VK_RValue,
3862 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003863 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003864}
3865
Steve Naroffd9803712009-04-29 16:37:50 +00003866// We need to return the rewritten expression to handle cases where the
3867// BlockDeclRefExpr is embedded in another expression being rewritten.
3868// For example:
3869//
3870// int main() {
3871// __block Foo *f;
3872// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003873//
Steve Naroffd9803712009-04-29 16:37:50 +00003874// void (^myblock)() = ^() {
3875// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3876// i = 77;
3877// };
3878//}
John McCall113bee02012-03-10 09:33:50 +00003879Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003880 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003881 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003882 ValueDecl *VD = DeclRefExp->getDecl();
3883 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Craig Topper8ae12032014-05-07 06:21:57 +00003884
3885 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003886 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003887 &Context->Idents.get("__forwarding"),
Craig Topper8ae12032014-05-07 06:21:57 +00003888 Context->VoidPtrTy, nullptr,
3889 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003890 ICIS_NoInit);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003891 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3892 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003893 FD->getType(), VK_LValue,
3894 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003895
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003896 StringRef Name = VD->getName();
Craig Topper8ae12032014-05-07 06:21:57 +00003897 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003898 &Context->Idents.get(Name),
Craig Topper8ae12032014-05-07 06:21:57 +00003899 Context->VoidPtrTy, nullptr,
3900 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003901 ICIS_NoInit);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003902 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003903 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003904
3905
3906
Steve Narofff26a1d42009-02-02 17:19:26 +00003907 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00003908 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3909 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003910 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003911 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003912 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913}
3914
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003915// Rewrites the imported local variable V with external storage
3916// (static, extern, etc.) as *V
3917//
3918Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3919 ValueDecl *VD = DRE->getDecl();
3920 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3921 if (!ImportedLocalExternalDecls.count(Var))
3922 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003923 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3924 VK_LValue, OK_Ordinary,
3925 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003926 // Need parens to enforce precedence.
3927 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3928 Exp);
3929 ReplaceStmt(DRE, PE);
3930 return PE;
3931}
3932
Steve Naroffc989a7b2008-11-03 23:29:32 +00003933void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3934 SourceLocation LocStart = CE->getLParenLoc();
3935 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003936
3937 // Need to avoid trying to rewrite synthesized casts.
3938 if (LocStart.isInvalid())
3939 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003940 // Need to avoid trying to rewrite casts contained in macros.
3941 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3942 return;
Mike Stump11289f42009-09-09 15:08:12 +00003943
Steve Naroff677ab3a2008-10-27 17:20:55 +00003944 const char *startBuf = SM->getCharacterData(LocStart);
3945 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003946 QualType QT = CE->getType();
3947 const Type* TypePtr = QT->getAs<Type>();
3948 if (isa<TypeOfExprType>(TypePtr)) {
3949 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3950 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3951 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003952 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003953 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003954 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003955 return;
3956 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003957 // advance the location to startArgList.
3958 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003959
Steve Naroff677ab3a2008-10-27 17:20:55 +00003960 while (*argPtr++ && (argPtr < endBuf)) {
3961 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003962 case '^':
3963 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003964 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003965 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003966 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 }
3968 }
3969 return;
3970}
3971
3972void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3973 SourceLocation DeclLoc = FD->getLocation();
3974 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003975
Steve Naroff677ab3a2008-10-27 17:20:55 +00003976 // We have 1 or more arguments that have closure pointers.
3977 const char *startBuf = SM->getCharacterData(DeclLoc);
3978 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003979
Steve Naroff677ab3a2008-10-27 17:20:55 +00003980 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003981
Steve Naroff677ab3a2008-10-27 17:20:55 +00003982 parenCount++;
3983 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003984 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00003986
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00003988
Steve Naroff677ab3a2008-10-27 17:20:55 +00003989 while (*argPtr++ && parenCount) {
3990 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003991 case '^':
3992 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003993 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003994 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003995 break;
3996 case '(':
3997 parenCount++;
3998 break;
3999 case ')':
4000 parenCount--;
4001 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004002 }
4003 }
4004 return;
4005}
4006
4007bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004008 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004009 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004010 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004011 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004012 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004013 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004015 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004016 }
4017 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004018 for (const auto &I : FTP->param_types())
4019 if (isTopLevelBlockPointerType(I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 return true;
4021 }
4022 return false;
4023}
4024
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004025bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4026 const FunctionProtoType *FTP;
4027 const PointerType *PT = QT->getAs<PointerType>();
4028 if (PT) {
4029 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4030 } else {
4031 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4032 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4033 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4034 }
4035 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004036 for (const auto &I : FTP->param_types()) {
4037 if (I->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004038 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004039 if (I->isObjCObjectPointerType() &&
4040 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004041 return true;
4042 }
4043
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004044 }
4045 return false;
4046}
4047
Ted Kremenek5a201952009-02-07 01:47:29 +00004048void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4049 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 const char *argPtr = strchr(Name, '(');
4051 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004052
Steve Naroff677ab3a2008-10-27 17:20:55 +00004053 LParen = argPtr; // output the start.
4054 argPtr++; // skip past the left paren.
4055 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004056
Steve Naroff677ab3a2008-10-27 17:20:55 +00004057 while (*argPtr && parenCount) {
4058 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004059 case '(': parenCount++; break;
4060 case ')': parenCount--; break;
4061 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 }
4063 if (parenCount) argPtr++;
4064 }
4065 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4066 RParen = argPtr; // output the end
4067}
4068
4069void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4071 RewriteBlockPointerFunctionArgs(FD);
4072 return;
Mike Stump11289f42009-09-09 15:08:12 +00004073 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004074 // Handle Variables and Typedefs.
4075 SourceLocation DeclLoc = ND->getLocation();
4076 QualType DeclT;
4077 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4078 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004079 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 DeclT = TDD->getUnderlyingType();
4081 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4082 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004083 else
David Blaikie83d382b2011-09-23 05:06:16 +00004084 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004085
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086 const char *startBuf = SM->getCharacterData(DeclLoc);
4087 const char *endBuf = startBuf;
4088 // scan backward (from the decl location) for the end of the previous decl.
4089 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4090 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004091 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004092 std::string buf;
4093 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004094 // *startBuf != '^' if we are dealing with a pointer to function that
4095 // may take block argument types (which will be handled below).
4096 if (*startBuf == '^') {
4097 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004098 buf = '*';
4099 startBuf++;
4100 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004102 while (*startBuf != ')') {
4103 buf += *startBuf;
4104 startBuf++;
4105 OrigLength++;
4106 }
4107 buf += ')';
4108 OrigLength++;
4109
4110 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4111 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004113 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004114 DeclLoc = ND->getLocation();
4115 startBuf = SM->getCharacterData(DeclLoc);
4116 const char *argListBegin, *argListEnd;
4117 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4118 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004119 if (*argListBegin == '^')
4120 buf += '*';
4121 else if (*argListBegin == '<') {
4122 buf += "/*";
4123 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004124 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004125 while (*argListBegin != '>') {
4126 buf += *argListBegin++;
4127 OrigLength++;
4128 }
4129 buf += *argListBegin;
4130 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004132 else
4133 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004135 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004137 buf += ')';
4138 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004140 ReplaceText(Start, OrigLength, buf);
4141
Steve Naroff677ab3a2008-10-27 17:20:55 +00004142 return;
4143}
4144
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004145
4146/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4147/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4148/// struct Block_byref_id_object *src) {
4149/// _Block_object_assign (&_dest->object, _src->object,
4150/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4151/// [|BLOCK_FIELD_IS_WEAK]) // object
4152/// _Block_object_assign(&_dest->object, _src->object,
4153/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4154/// [|BLOCK_FIELD_IS_WEAK]) // block
4155/// }
4156/// And:
4157/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4158/// _Block_object_dispose(_src->object,
4159/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4160/// [|BLOCK_FIELD_IS_WEAK]) // object
4161/// _Block_object_dispose(_src->object,
4162/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4163/// [|BLOCK_FIELD_IS_WEAK]) // block
4164/// }
4165
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004166std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4167 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004168 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004169 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004170 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004171 CopyDestroyCache.insert(flag);
4172 S = "static void __Block_byref_id_object_copy_";
4173 S += utostr(flag);
4174 S += "(void *dst, void *src) {\n";
4175
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004176 // offset into the object pointer is computed as:
4177 // void * + void* + int + int + void* + void *
4178 unsigned IntSize =
4179 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4180 unsigned VoidPtrSize =
4181 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4182
Ken Dyckd9c83e62011-04-30 16:08:27 +00004183 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004184 S += " _Block_object_assign((char*)dst + ";
4185 S += utostr(offset);
4186 S += ", *(void * *) ((char*)src + ";
4187 S += utostr(offset);
4188 S += "), ";
4189 S += utostr(flag);
4190 S += ");\n}\n";
4191
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004192 S += "static void __Block_byref_id_object_dispose_";
4193 S += utostr(flag);
4194 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004195 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4196 S += utostr(offset);
4197 S += "), ";
4198 S += utostr(flag);
4199 S += ");\n}\n";
4200 return S;
4201}
4202
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004203/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4204/// the declaration into:
4205/// struct __Block_byref_ND {
4206/// void *__isa; // NULL for everything except __weak pointers
4207/// struct __Block_byref_ND *__forwarding;
4208/// int32_t __flags;
4209/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004210/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4211/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004212/// typex ND;
4213/// };
4214///
4215/// It then replaces declaration of ND variable with:
4216/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4217/// __size=sizeof(struct __Block_byref_ND),
4218/// ND=initializer-if-any};
4219///
4220///
4221void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004222 // Insert declaration for the function in which block literal is
4223 // used.
4224 if (CurFunctionDeclToDeclareForBlock)
4225 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004226 int flag = 0;
4227 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004228 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004229 if (DeclLoc.isInvalid())
4230 // If type location is missing, it is because of missing type (a warning).
4231 // Use variable's location which is good for this case.
4232 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004233 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004234 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004235 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004236 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004237 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004238 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004239 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004240 ByrefType += " {\n";
4241 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004242 RewriteByRefString(ByrefType, Name, ND);
4243 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004244 ByrefType += " int __flags;\n";
4245 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004246 // Add void *__Block_byref_id_object_copy;
4247 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004248 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004249 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004250 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004251 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4252 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004253 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004254
4255 QualType T = Ty;
4256 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004257 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004258
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004259 ByrefType += " " + Name + ";\n";
4260 ByrefType += "};\n";
4261 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004262 SourceLocation FunLocStart;
4263 if (CurFunctionDef)
4264 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4265 else {
4266 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4267 FunLocStart = CurMethodDef->getLocStart();
4268 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004269 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004270 if (Ty.isObjCGCWeak()) {
4271 flag |= BLOCK_FIELD_IS_WEAK;
4272 isa = 1;
4273 }
4274
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004275 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004276 flag = BLOCK_BYREF_CALLER;
4277 QualType Ty = ND->getType();
4278 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4279 if (Ty->isBlockPointerType())
4280 flag |= BLOCK_FIELD_IS_BLOCK;
4281 else
4282 flag |= BLOCK_FIELD_IS_OBJECT;
4283 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004284 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004285 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004286 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004287
4288 // struct __Block_byref_ND ND =
4289 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4290 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00004291 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004292 unsigned flags = 0;
4293 if (HasCopyAndDispose)
4294 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004295 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004296 ByrefType.clear();
4297 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004298 std::string ForwardingCastType("(");
4299 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004300 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004301 ByrefType += " " + Name + " = {(void*)";
4302 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004303 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004304 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004305 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004306 ByrefType += "sizeof(";
4307 RewriteByRefString(ByrefType, Name, ND);
4308 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004309 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004310 ByrefType += ", __Block_byref_id_object_copy_";
4311 ByrefType += utostr(flag);
4312 ByrefType += ", __Block_byref_id_object_dispose_";
4313 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004314 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004315 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004316 unsigned nameSize = Name.size();
4317 // for block or function pointer declaration. Name is aleady
4318 // part of the declaration.
4319 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4320 nameSize = 1;
4321 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004322 }
4323 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004324 SourceLocation startLoc;
4325 Expr *E = ND->getInit();
4326 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4327 startLoc = ECE->getLParenLoc();
4328 else
4329 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004330 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004331 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004332 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004333 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004334 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004335 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004336 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004337 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004338 ByrefType += "sizeof(";
4339 RewriteByRefString(ByrefType, Name, ND);
4340 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004341 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004342 ByrefType += "__Block_byref_id_object_copy_";
4343 ByrefType += utostr(flag);
4344 ByrefType += ", __Block_byref_id_object_dispose_";
4345 ByrefType += utostr(flag);
4346 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004347 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004348 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004349
4350 // Complete the newly synthesized compound expression by inserting a right
4351 // curly brace before the end of the declaration.
4352 // FIXME: This approach avoids rewriting the initializer expression. It
4353 // also assumes there is only one declarator. For example, the following
4354 // isn't currently supported by this routine (in general):
4355 //
4356 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4357 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004358 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4359 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004360 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4361 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004362 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004363
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004364 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004365 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004366 return;
4367}
4368
Mike Stump11289f42009-09-09 15:08:12 +00004369void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004370 // Add initializers for any closure decl refs.
4371 GetBlockDeclRefExprs(Exp->getBody());
4372 if (BlockDeclRefs.size()) {
4373 // Unique all "by copy" declarations.
4374 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004375 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004376 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4377 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4378 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4379 }
4380 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381 // Unique all "by ref" declarations.
4382 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004383 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004384 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4385 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4386 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4387 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004388 }
4389 // Find any imported blocks...they will need special attention.
4390 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004391 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004392 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004393 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004394 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004395 }
4396}
4397
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004398FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004399 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004400 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004401 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00004402 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004403 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004404}
4405
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004406Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004407 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004408 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004409 Blocks.push_back(Exp);
4410
4411 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004412
4413 // Add inner imported variables now used in current block.
4414 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004415 if (!InnerBlockDeclRefs.empty()) {
4416 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004417 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004418 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004419 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004420 // We need to save the copied-in variables in nested
4421 // blocks because it is needed at the end for some of the API generations.
4422 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004423 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4424 BlockDeclRefs.push_back(Exp);
4425 BlockByCopyDeclsPtrSet.insert(VD);
4426 BlockByCopyDecls.push_back(VD);
4427 }
John McCall113bee02012-03-10 09:33:50 +00004428 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004429 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4430 BlockDeclRefs.push_back(Exp);
4431 BlockByRefDeclsPtrSet.insert(VD);
4432 BlockByRefDecls.push_back(VD);
4433 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004434 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004435 // Find any imported blocks...they will need special attention.
4436 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004437 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004438 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4439 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4440 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004441 }
4442 InnerDeclRefsCount.push_back(countOfInnerDecls);
4443
Steve Narofff4b992a2008-10-28 20:29:00 +00004444 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004445
Steve Narofff4b992a2008-10-28 20:29:00 +00004446 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004447 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004448 else if (CurMethodDef)
4449 BuildUniqueMethodName(FuncName, CurMethodDef);
4450 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004451 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004452
Steve Narofff4b992a2008-10-28 20:29:00 +00004453 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004454
Steve Narofff4b992a2008-10-28 20:29:00 +00004455 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4456 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004457
Steve Narofff4b992a2008-10-28 20:29:00 +00004458 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004459 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4460 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004461
4462 FunctionDecl *FD;
4463 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004464
Benjamin Kramer60509af2013-09-09 14:48:42 +00004465 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004466 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004467 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004468 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004470 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004471
Steve Naroffe2514232008-10-29 21:23:59 +00004472 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004473 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004474 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4475 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004476 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004477 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004478 InitExprs.push_back(castExpr);
4479
Steve Naroff30484702009-12-06 21:14:13 +00004480 // Initialize the block descriptor.
4481 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004482
Abramo Bagnaradff19302011-03-08 08:55:46 +00004483 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4484 SourceLocation(), SourceLocation(),
4485 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00004486 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004487 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004488 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004489 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004490 Context->VoidPtrTy,
4491 VK_LValue,
4492 SourceLocation()),
4493 UO_AddrOf,
4494 Context->getPointerType(Context->VoidPtrTy),
4495 VK_RValue, OK_Ordinary,
4496 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004497 InitExprs.push_back(DescRefExpr);
4498
Steve Narofff4b992a2008-10-28 20:29:00 +00004499 // Add initializers for any closure decl refs.
4500 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004501 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004502 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004503 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004504 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004505 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004506 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004507 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004508 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004509 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004510 if (HasLocalVariableExternalStorage(*I)) {
4511 QualType QT = (*I)->getType();
4512 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004513 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4514 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004515 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004516 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004517 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004518 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004519 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004520 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004521 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004522 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004523 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004524 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004525 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004526 if (HasLocalVariableExternalStorage(*I)) {
4527 QualType QT = (*I)->getType();
4528 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004529 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4530 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004531 }
4532
Steve Narofff4b992a2008-10-28 20:29:00 +00004533 }
Mike Stump11289f42009-09-09 15:08:12 +00004534 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004535 }
4536 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004537 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004538 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004539 ValueDecl *ND = (*I);
4540 std::string Name(ND->getNameAsString());
4541 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004542 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004543 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4544 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004545 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004546 SourceLocation(), SourceLocation(),
4547 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004548 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4549 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4550
Daniel Dunbar56df9772010-08-17 22:39:59 +00004551 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004552 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004553 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004554 bool isNestedCapturedVar = false;
4555 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00004556 for (const auto &CI : block->captures()) {
4557 const VarDecl *variable = CI.getVariable();
4558 if (variable == ND && CI.isNested()) {
4559 assert (CI.isByRef() &&
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004560 "SynthBlockInitExpr - captured block variable is not byref");
4561 isNestedCapturedVar = true;
4562 break;
4563 }
4564 }
4565 // captured nested byref variable has its address passed. Do not take
4566 // its address again.
4567 if (!isNestedCapturedVar)
4568 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004569 Context->getPointerType(Exp->getType()),
4570 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004571 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004572 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004573 }
4574 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004575 if (ImportedBlockDecls.size()) {
4576 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4577 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004578 unsigned IntSize =
4579 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004580 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4581 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004582 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004583 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004584 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004585 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004586 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004587 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004588 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004589 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004590 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004591 BlockDeclRefs.clear();
4592 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004593 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004594 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004595 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 ImportedBlockDecls.clear();
4597 return NewRep;
4598}
4599
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004600bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4601 if (const ObjCForCollectionStmt * CS =
4602 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4603 return CS->getElement() == DS;
4604 return false;
4605}
4606
Steve Narofff4b992a2008-10-28 20:29:00 +00004607//===----------------------------------------------------------------------===//
4608// Function Body / Expression rewriting
4609//===----------------------------------------------------------------------===//
4610
4611Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004612 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004613 isa<DoStmt>(S) || isa<ForStmt>(S))
4614 Stmts.push_back(S);
4615 else if (isa<ObjCForCollectionStmt>(S)) {
4616 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004617 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 }
Mike Stump11289f42009-09-09 15:08:12 +00004619
John McCallfe96e0b2011-11-06 09:01:30 +00004620 // Pseudo-object operations and ivar references need special
4621 // treatment because we're going to recursively rewrite them.
4622 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4623 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4624 return RewritePropertyOrImplicitSetter(PseudoOp);
4625 } else {
4626 return RewritePropertyOrImplicitGetter(PseudoOp);
4627 }
4628 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4629 return RewriteObjCIvarRefExpr(IvarRefExpr);
4630 }
4631
Steve Narofff4b992a2008-10-28 20:29:00 +00004632 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004633
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00004635 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00004636 if (*CI) {
John McCallfe96e0b2011-11-06 09:01:30 +00004637 Stmt *childStmt = (*CI);
4638 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004639 if (newStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004640 *CI = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004641 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004642 }
Mike Stump11289f42009-09-09 15:08:12 +00004643
Steve Narofff4b992a2008-10-28 20:29:00 +00004644 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004645 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004646 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4647 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004648 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004649 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004650 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004652 Stmt *SaveCurrentBody = CurrentBody;
4653 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00004654 PropParentMap = nullptr;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004655 // block literal on rhs of a property-dot-sytax assignment
4656 // must be replaced by its synthesize ast so getRewrittenText
4657 // works as expected. In this case, what actually ends up on RHS
4658 // is the blockTranscribed which is the helper function for the
4659 // block literal; as in: self.c = ^() {[ace ARR];};
4660 bool saveDisableReplaceStmt = DisableReplaceStmt;
4661 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004662 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004663 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004664 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00004665 PropParentMap = nullptr;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004666 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004667 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004668 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004669 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004670
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004671 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4672
Steve Narofff4b992a2008-10-28 20:29:00 +00004673 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004674 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004675 return blockTranscribed;
4676 }
4677 // Handle specific things.
4678 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4679 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004680
Steve Narofff4b992a2008-10-28 20:29:00 +00004681 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4682 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004683
Steve Narofff4b992a2008-10-28 20:29:00 +00004684 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4685 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004688#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004689 // Before we rewrite it, put the original message expression in a comment.
4690 SourceLocation startLoc = MessExpr->getLocStart();
4691 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004692
Steve Narofff4b992a2008-10-28 20:29:00 +00004693 const char *startBuf = SM->getCharacterData(startLoc);
4694 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004695
Steve Narofff4b992a2008-10-28 20:29:00 +00004696 std::string messString;
4697 messString += "// ";
4698 messString.append(startBuf, endBuf-startBuf+1);
4699 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004700
4701 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004702 // InsertText(clang::SourceLocation, char const*, unsigned int).
4703 // InsertText(startLoc, messString.c_str(), messString.size());
4704 // Tried this, but it didn't work either...
4705 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004706#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 return RewriteMessageExpr(MessExpr);
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4711 return RewriteObjCTryStmt(StmtTry);
4712
4713 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4714 return RewriteObjCSynchronizedStmt(StmtTry);
4715
4716 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4717 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004718
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4720 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004721
4722 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004723 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004724 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 OrigStmtRange.getEnd());
4726 if (BreakStmt *StmtBreakStmt =
4727 dyn_cast<BreakStmt>(S))
4728 return RewriteBreakStmt(StmtBreakStmt);
4729 if (ContinueStmt *StmtContinueStmt =
4730 dyn_cast<ContinueStmt>(S))
4731 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004732
4733 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004734 // and cast exprs.
4735 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4736 // FIXME: What we're doing here is modifying the type-specifier that
4737 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004738 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004739 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4740 // the context of an ObjCForCollectionStmt. For example:
4741 // NSArray *someArray;
4742 // for (id <FooProtocol> index in someArray) ;
4743 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4744 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004745 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004746 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004747
Steve Narofff4b992a2008-10-28 20:29:00 +00004748 // Blocks rewrite rules.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004749 for (auto *SD : DS->decls()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004750 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004751 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004752 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004753 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004754 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004755 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004756 if (VD->hasAttr<BlocksAttr>()) {
4757 static unsigned uniqueByrefDeclCount = 0;
4758 assert(!BlockByRefDeclNo.count(ND) &&
4759 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4760 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004761 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004762 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004763 else
4764 RewriteTypeOfDecl(VD);
4765 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 }
Richard Smithdda56e42011-04-15 14:24:37 +00004767 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004768 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004769 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004770 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004771 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4772 }
4773 }
4774 }
Mike Stump11289f42009-09-09 15:08:12 +00004775
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4777 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004778
4779 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4781 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004782 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4783 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004784 && "Statement stack mismatch");
4785 Stmts.pop_back();
4786 }
4787 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004788 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4789 ValueDecl *VD = DRE->getDecl();
4790 if (VD->hasAttr<BlocksAttr>())
4791 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004792 if (HasLocalVariableExternalStorage(VD))
4793 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004794 }
4795
Steve Narofff4b992a2008-10-28 20:29:00 +00004796 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004797 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004798 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004799 ReplaceStmt(S, BlockCall);
4800 return BlockCall;
4801 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004802 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004803 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004804 RewriteCastExpr(CE);
4805 }
4806#if 0
4807 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004808 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4809 ICE->getSubExpr(),
4810 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004811 // Get the new text.
4812 std::string SStr;
4813 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004814 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004815 const std::string &Str = Buf.str();
4816
4817 printf("CAST = %s\n", &Str[0]);
4818 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4819 delete S;
4820 return Replacement;
4821 }
4822#endif
4823 // Return this stmt unmodified.
4824 return S;
4825}
4826
Steve Naroffe70a52a2009-12-05 15:55:59 +00004827void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004828 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004829 if (isTopLevelBlockPointerType(FD->getType()))
4830 RewriteBlockPointerDecl(FD);
4831 if (FD->getType()->isObjCQualifiedIdType() ||
4832 FD->getType()->isObjCQualifiedInterfaceType())
4833 RewriteObjCQualifiedInterfaceTypes(FD);
4834 }
4835}
4836
Steve Narofff4b992a2008-10-28 20:29:00 +00004837/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4838/// main file of the input.
4839void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004840 switch (D->getKind()) {
4841 case Decl::Function: {
4842 FunctionDecl *FD = cast<FunctionDecl>(D);
4843 if (FD->isOverloadedOperator())
4844 return;
Mike Stump11289f42009-09-09 15:08:12 +00004845
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004846 // Since function prototypes don't have ParmDecl's, we check the function
4847 // prototype. This enables us to rewrite function declarations and
4848 // definitions using the same code.
4849 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004850
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004851 if (!FD->isThisDeclarationADefinition())
4852 break;
4853
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004854 // FIXME: If this should support Obj-C++, support CXXTryStmt
4855 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4856 CurFunctionDef = FD;
4857 CurFunctionDeclToDeclareForBlock = FD;
4858 CurrentBody = Body;
4859 Body =
4860 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4861 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004862 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004863 if (PropParentMap) {
4864 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004865 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004866 }
4867 // This synthesizes and inserts the block "impl" struct, invoke function,
4868 // and any copy/dispose helper functions.
4869 InsertBlockLiteralsWithinFunction(FD);
Craig Topper8ae12032014-05-07 06:21:57 +00004870 CurFunctionDef = nullptr;
4871 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004872 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004873 break;
Mike Stump11289f42009-09-09 15:08:12 +00004874 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004875 case Decl::ObjCMethod: {
4876 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4877 if (CompoundStmt *Body = MD->getCompoundBody()) {
4878 CurMethodDef = MD;
4879 CurrentBody = Body;
4880 Body =
4881 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4882 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004883 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004884 if (PropParentMap) {
4885 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004886 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004887 }
4888 InsertBlockLiteralsWithinMethod(MD);
Craig Topper8ae12032014-05-07 06:21:57 +00004889 CurMethodDef = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004890 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004891 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004893 case Decl::ObjCImplementation: {
4894 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4895 ClassImplementation.push_back(CI);
4896 break;
4897 }
4898 case Decl::ObjCCategoryImpl: {
4899 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4900 CategoryImplementation.push_back(CI);
4901 break;
4902 }
4903 case Decl::Var: {
4904 VarDecl *VD = cast<VarDecl>(D);
4905 RewriteObjCQualifiedInterfaceTypes(VD);
4906 if (isTopLevelBlockPointerType(VD->getType()))
4907 RewriteBlockPointerDecl(VD);
4908 else if (VD->getType()->isFunctionPointerType()) {
4909 CheckFunctionPointerDecl(VD->getType(), VD);
4910 if (VD->getInit()) {
4911 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4912 RewriteCastExpr(CE);
4913 }
4914 }
4915 } else if (VD->getType()->isRecordType()) {
4916 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4917 if (RD->isCompleteDefinition())
4918 RewriteRecordBody(RD);
4919 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004920 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004921 GlobalVarDecl = VD;
4922 CurrentBody = VD->getInit();
4923 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00004924 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004925 if (PropParentMap) {
4926 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004927 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004928 }
4929 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00004930 GlobalVarDecl = nullptr;
4931
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004932 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004933 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004934 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 }
4936 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004937 break;
4938 }
4939 case Decl::TypeAlias:
4940 case Decl::Typedef: {
4941 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4942 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4943 RewriteBlockPointerDecl(TD);
4944 else if (TD->getUnderlyingType()->isFunctionPointerType())
4945 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4946 }
4947 break;
4948 }
4949 case Decl::CXXRecord:
4950 case Decl::Record: {
4951 RecordDecl *RD = cast<RecordDecl>(D);
4952 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004953 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004954 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004955 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004956 default:
4957 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004958 }
4959 // Nothing yet.
4960}
4961
Chris Lattnercf169832009-03-28 04:11:33 +00004962void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004963 if (Diags.hasErrorOccurred())
4964 return;
Mike Stump11289f42009-09-09 15:08:12 +00004965
Steve Narofff4b992a2008-10-28 20:29:00 +00004966 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004967
Steve Naroffd9803712009-04-29 16:37:50 +00004968 // Here's a great place to add any extra declarations that may be needed.
4969 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004970 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004971 E = ProtocolExprDecls.end(); I != E; ++I)
4972 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4973
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004974 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004975 if (ClassImplementation.size() || CategoryImplementation.size())
4976 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004977
Steve Narofff4b992a2008-10-28 20:29:00 +00004978 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4979 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004980 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004981 Rewrite.getRewriteBufferFor(MainFileID)) {
4982 //printf("Changed:\n");
4983 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4984 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004985 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004987
Steve Naroffd9803712009-04-29 16:37:50 +00004988 if (ClassImplementation.size() || CategoryImplementation.size() ||
4989 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004990 // Rewrite Objective-c meta data*
4991 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00004992 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004993 // Emit metadata.
4994 *OutFile << ResultStr;
4995 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004996 OutFile->flush();
4997}
Fariborz Jahanian83077422011-12-08 18:25:15 +00004998
4999void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5000 InitializeCommon(context);
5001
5002 // declaring objc_selector outside the parameter list removes a silly
5003 // scope related warning...
5004 if (IsHeader)
5005 Preamble = "#pragma once\n";
5006 Preamble += "struct objc_selector; struct objc_class;\n";
5007 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5008 Preamble += "struct objc_object *superClass; ";
5009 if (LangOpts.MicrosoftExt) {
5010 // Add a constructor for creating temporary objects.
5011 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5012 ": ";
5013 Preamble += "object(o), superClass(s) {} ";
5014 }
5015 Preamble += "};\n";
5016 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5017 Preamble += "typedef struct objc_object Protocol;\n";
5018 Preamble += "#define _REWRITER_typedef_Protocol\n";
5019 Preamble += "#endif\n";
5020 if (LangOpts.MicrosoftExt) {
5021 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5022 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5023 } else
5024 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5025 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5026 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5027 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5028 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5029 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5030 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5031 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5032 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5034 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5036 Preamble += "(const char *);\n";
5037 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5038 Preamble += "(struct objc_class *);\n";
5039 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5040 Preamble += "(const char *);\n";
5041 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5042 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5043 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5044 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5045 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5046 Preamble += "(struct objc_class *, struct objc_object *);\n";
5047 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005048 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5049 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005050 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5051 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5052 Preamble += "struct __objcFastEnumerationState {\n\t";
5053 Preamble += "unsigned long state;\n\t";
5054 Preamble += "void **itemsPtr;\n\t";
5055 Preamble += "unsigned long *mutationsPtr;\n\t";
5056 Preamble += "unsigned long extra[5];\n};\n";
5057 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5058 Preamble += "#define __FASTENUMERATIONSTATE\n";
5059 Preamble += "#endif\n";
5060 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5061 Preamble += "struct __NSConstantStringImpl {\n";
5062 Preamble += " int *isa;\n";
5063 Preamble += " int flags;\n";
5064 Preamble += " char *str;\n";
5065 Preamble += " long length;\n";
5066 Preamble += "};\n";
5067 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5068 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5069 Preamble += "#else\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5071 Preamble += "#endif\n";
5072 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5073 Preamble += "#endif\n";
5074 // Blocks preamble.
5075 Preamble += "#ifndef BLOCK_IMPL\n";
5076 Preamble += "#define BLOCK_IMPL\n";
5077 Preamble += "struct __block_impl {\n";
5078 Preamble += " void *isa;\n";
5079 Preamble += " int Flags;\n";
5080 Preamble += " int Reserved;\n";
5081 Preamble += " void *FuncPtr;\n";
5082 Preamble += "};\n";
5083 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5084 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5085 Preamble += "extern \"C\" __declspec(dllexport) "
5086 "void _Block_object_assign(void *, const void *, const int);\n";
5087 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5088 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5089 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5090 Preamble += "#else\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5095 Preamble += "#endif\n";
5096 Preamble += "#endif\n";
5097 if (LangOpts.MicrosoftExt) {
5098 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5099 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5100 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5101 Preamble += "#define __attribute__(X)\n";
5102 Preamble += "#endif\n";
5103 Preamble += "#define __weak\n";
5104 }
5105 else {
5106 Preamble += "#define __block\n";
5107 Preamble += "#define __weak\n";
5108 }
5109 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5110 // as this avoids warning in any 64bit/32bit compilation model.
5111 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5112}
5113
5114/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5115/// ivar offset.
5116void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5117 std::string &Result) {
5118 if (ivar->isBitField()) {
5119 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5120 // place all bitfields at offset 0.
5121 Result += "0";
5122 } else {
5123 Result += "__OFFSETOFIVAR__(struct ";
5124 Result += ivar->getContainingInterface()->getNameAsString();
5125 if (LangOpts.MicrosoftExt)
5126 Result += "_IMPL";
5127 Result += ", ";
5128 Result += ivar->getNameAsString();
5129 Result += ")";
5130 }
5131}
5132
5133/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5134void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5135 ObjCProtocolDecl *PDecl, StringRef prefix,
5136 StringRef ClassName, std::string &Result) {
5137 static bool objc_protocol_methods = false;
5138
5139 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005140 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005141 /* struct protocol_methods {
5142 SEL _cmd;
5143 char *method_types;
5144 }
5145 */
5146 Result += "\nstruct _protocol_methods {\n";
5147 Result += "\tstruct objc_selector *_cmd;\n";
5148 Result += "\tchar *method_types;\n";
5149 Result += "};\n";
5150
5151 objc_protocol_methods = true;
5152 }
5153 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005154 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005155 return;
5156
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005157 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5158 PDecl = Def;
5159
Fariborz Jahanian83077422011-12-08 18:25:15 +00005160 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5161 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5162 PDecl->instmeth_end());
5163 /* struct _objc_protocol_method_list {
5164 int protocol_method_count;
5165 struct protocol_methods protocols[];
5166 }
5167 */
5168 Result += "\nstatic struct {\n";
5169 Result += "\tint protocol_method_count;\n";
5170 Result += "\tstruct _protocol_methods protocol_methods[";
5171 Result += utostr(NumMethods);
5172 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5173 Result += PDecl->getNameAsString();
5174 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5175 "{\n\t" + utostr(NumMethods) + "\n";
5176
5177 // Output instance methods declared in this protocol.
5178 for (ObjCProtocolDecl::instmeth_iterator
5179 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5180 I != E; ++I) {
5181 if (I == PDecl->instmeth_begin())
5182 Result += "\t ,{{(struct objc_selector *)\"";
5183 else
5184 Result += "\t ,{(struct objc_selector *)\"";
5185 Result += (*I)->getSelector().getAsString();
5186 std::string MethodTypeString;
5187 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5188 Result += "\", \"";
5189 Result += MethodTypeString;
5190 Result += "\"}\n";
5191 }
5192 Result += "\t }\n};\n";
5193 }
5194
5195 // Output class methods declared in this protocol.
5196 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5197 PDecl->classmeth_end());
5198 if (NumMethods > 0) {
5199 /* struct _objc_protocol_method_list {
5200 int protocol_method_count;
5201 struct protocol_methods protocols[];
5202 }
5203 */
5204 Result += "\nstatic struct {\n";
5205 Result += "\tint protocol_method_count;\n";
5206 Result += "\tstruct _protocol_methods protocol_methods[";
5207 Result += utostr(NumMethods);
5208 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5209 Result += PDecl->getNameAsString();
5210 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5211 "{\n\t";
5212 Result += utostr(NumMethods);
5213 Result += "\n";
5214
5215 // Output instance methods declared in this protocol.
5216 for (ObjCProtocolDecl::classmeth_iterator
5217 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5218 I != E; ++I) {
5219 if (I == PDecl->classmeth_begin())
5220 Result += "\t ,{{(struct objc_selector *)\"";
5221 else
5222 Result += "\t ,{(struct objc_selector *)\"";
5223 Result += (*I)->getSelector().getAsString();
5224 std::string MethodTypeString;
5225 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5226 Result += "\", \"";
5227 Result += MethodTypeString;
5228 Result += "\"}\n";
5229 }
5230 Result += "\t }\n};\n";
5231 }
5232
5233 // Output:
5234 /* struct _objc_protocol {
5235 // Objective-C 1.0 extensions
5236 struct _objc_protocol_extension *isa;
5237 char *protocol_name;
5238 struct _objc_protocol **protocol_list;
5239 struct _objc_protocol_method_list *instance_methods;
5240 struct _objc_protocol_method_list *class_methods;
5241 };
5242 */
5243 static bool objc_protocol = false;
5244 if (!objc_protocol) {
5245 Result += "\nstruct _objc_protocol {\n";
5246 Result += "\tstruct _objc_protocol_extension *isa;\n";
5247 Result += "\tchar *protocol_name;\n";
5248 Result += "\tstruct _objc_protocol **protocol_list;\n";
5249 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5250 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5251 Result += "};\n";
5252
5253 objc_protocol = true;
5254 }
5255
5256 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5257 Result += PDecl->getNameAsString();
5258 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5259 "{\n\t0, \"";
5260 Result += PDecl->getNameAsString();
5261 Result += "\", 0, ";
5262 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5263 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5264 Result += PDecl->getNameAsString();
5265 Result += ", ";
5266 }
5267 else
5268 Result += "0, ";
5269 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5270 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5271 Result += PDecl->getNameAsString();
5272 Result += "\n";
5273 }
5274 else
5275 Result += "0\n";
5276 Result += "};\n";
5277
5278 // Mark this protocol as having been generated.
Douglas Gregor33b24292012-01-01 18:09:12 +00005279 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005280 llvm_unreachable("protocol already synthesized");
5281
5282}
5283
5284void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5285 const ObjCList<ObjCProtocolDecl> &Protocols,
5286 StringRef prefix, StringRef ClassName,
5287 std::string &Result) {
5288 if (Protocols.empty()) return;
5289
5290 for (unsigned i = 0; i != Protocols.size(); i++)
5291 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5292
5293 // Output the top lovel protocol meta-data for the class.
5294 /* struct _objc_protocol_list {
5295 struct _objc_protocol_list *next;
5296 int protocol_count;
5297 struct _objc_protocol *class_protocols[];
5298 }
5299 */
5300 Result += "\nstatic struct {\n";
5301 Result += "\tstruct _objc_protocol_list *next;\n";
5302 Result += "\tint protocol_count;\n";
5303 Result += "\tstruct _objc_protocol *class_protocols[";
5304 Result += utostr(Protocols.size());
5305 Result += "];\n} _OBJC_";
5306 Result += prefix;
5307 Result += "_PROTOCOLS_";
5308 Result += ClassName;
5309 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5310 "{\n\t0, ";
5311 Result += utostr(Protocols.size());
5312 Result += "\n";
5313
5314 Result += "\t,{&_OBJC_PROTOCOL_";
5315 Result += Protocols[0]->getNameAsString();
5316 Result += " \n";
5317
5318 for (unsigned i = 1; i != Protocols.size(); i++) {
5319 Result += "\t ,&_OBJC_PROTOCOL_";
5320 Result += Protocols[i]->getNameAsString();
5321 Result += "\n";
5322 }
5323 Result += "\t }\n};\n";
5324}
5325
5326void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5327 std::string &Result) {
5328 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5329
5330 // Explicitly declared @interface's are already synthesized.
5331 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005332 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005333 // produce correct synthesis as yet.
5334 RewriteObjCInternalStruct(CDecl, Result);
5335 }
5336
5337 // Build _objc_ivar_list metadata for classes ivars if needed
5338 unsigned NumIvars = !IDecl->ivar_empty()
5339 ? IDecl->ivar_size()
5340 : (CDecl ? CDecl->ivar_size() : 0);
5341 if (NumIvars > 0) {
5342 static bool objc_ivar = false;
5343 if (!objc_ivar) {
5344 /* struct _objc_ivar {
5345 char *ivar_name;
5346 char *ivar_type;
5347 int ivar_offset;
5348 };
5349 */
5350 Result += "\nstruct _objc_ivar {\n";
5351 Result += "\tchar *ivar_name;\n";
5352 Result += "\tchar *ivar_type;\n";
5353 Result += "\tint ivar_offset;\n";
5354 Result += "};\n";
5355
5356 objc_ivar = true;
5357 }
5358
5359 /* struct {
5360 int ivar_count;
5361 struct _objc_ivar ivar_list[nIvars];
5362 };
5363 */
5364 Result += "\nstatic struct {\n";
5365 Result += "\tint ivar_count;\n";
5366 Result += "\tstruct _objc_ivar ivar_list[";
5367 Result += utostr(NumIvars);
5368 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5369 Result += IDecl->getNameAsString();
5370 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5371 "{\n\t";
5372 Result += utostr(NumIvars);
5373 Result += "\n";
5374
5375 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5376 SmallVector<ObjCIvarDecl *, 8> IVars;
5377 if (!IDecl->ivar_empty()) {
Aaron Ballmand6d25de2014-03-14 15:16:45 +00005378 for (auto *IV : IDecl->ivars())
5379 IVars.push_back(IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005380 IVI = IDecl->ivar_begin();
5381 IVE = IDecl->ivar_end();
5382 } else {
5383 IVI = CDecl->ivar_begin();
5384 IVE = CDecl->ivar_end();
5385 }
5386 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005387 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005388 Result += "\", \"";
5389 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005390 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005391 QuoteDoublequotes(TmpString, StrEncoding);
5392 Result += StrEncoding;
5393 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005394 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005395 Result += "}\n";
5396 for (++IVI; IVI != IVE; ++IVI) {
5397 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005398 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005399 Result += "\", \"";
5400 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005401 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005402 QuoteDoublequotes(TmpString, StrEncoding);
5403 Result += StrEncoding;
5404 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005405 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005406 Result += "}\n";
5407 }
5408
5409 Result += "\t }\n};\n";
5410 }
5411
5412 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005413 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005414
5415 // If any of our property implementations have associated getters or
5416 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005417 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005418 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005419 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005420 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005421 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005422 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005423 if (!PD)
5424 continue;
5425 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5426 if (!Getter->isDefined())
5427 InstanceMethods.push_back(Getter);
5428 if (PD->isReadOnly())
5429 continue;
5430 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5431 if (!Setter->isDefined())
5432 InstanceMethods.push_back(Setter);
5433 }
5434 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5435 true, "", IDecl->getName(), Result);
5436
5437 // Build _objc_method_list for class's class methods if needed
5438 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5439 false, "", IDecl->getName(), Result);
5440
5441 // Protocols referenced in class declaration?
5442 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5443 "CLASS", CDecl->getName(), Result);
5444
5445 // Declaration of class/meta-class metadata
5446 /* struct _objc_class {
5447 struct _objc_class *isa; // or const char *root_class_name when metadata
5448 const char *super_class_name;
5449 char *name;
5450 long version;
5451 long info;
5452 long instance_size;
5453 struct _objc_ivar_list *ivars;
5454 struct _objc_method_list *methods;
5455 struct objc_cache *cache;
5456 struct objc_protocol_list *protocols;
5457 const char *ivar_layout;
5458 struct _objc_class_ext *ext;
5459 };
5460 */
5461 static bool objc_class = false;
5462 if (!objc_class) {
5463 Result += "\nstruct _objc_class {\n";
5464 Result += "\tstruct _objc_class *isa;\n";
5465 Result += "\tconst char *super_class_name;\n";
5466 Result += "\tchar *name;\n";
5467 Result += "\tlong version;\n";
5468 Result += "\tlong info;\n";
5469 Result += "\tlong instance_size;\n";
5470 Result += "\tstruct _objc_ivar_list *ivars;\n";
5471 Result += "\tstruct _objc_method_list *methods;\n";
5472 Result += "\tstruct objc_cache *cache;\n";
5473 Result += "\tstruct _objc_protocol_list *protocols;\n";
5474 Result += "\tconst char *ivar_layout;\n";
5475 Result += "\tstruct _objc_class_ext *ext;\n";
5476 Result += "};\n";
5477 objc_class = true;
5478 }
5479
5480 // Meta-class metadata generation.
Craig Topper8ae12032014-05-07 06:21:57 +00005481 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005482 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5483 while (SuperClass) {
5484 RootClass = SuperClass;
5485 SuperClass = SuperClass->getSuperClass();
5486 }
5487 SuperClass = CDecl->getSuperClass();
5488
5489 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5490 Result += CDecl->getNameAsString();
5491 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5492 "{\n\t(struct _objc_class *)\"";
5493 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5494 Result += "\"";
5495
5496 if (SuperClass) {
5497 Result += ", \"";
5498 Result += SuperClass->getNameAsString();
5499 Result += "\", \"";
5500 Result += CDecl->getNameAsString();
5501 Result += "\"";
5502 }
5503 else {
5504 Result += ", 0, \"";
5505 Result += CDecl->getNameAsString();
5506 Result += "\"";
5507 }
5508 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5509 // 'info' field is initialized to CLS_META(2) for metaclass
5510 Result += ", 0,2, sizeof(struct _objc_class), 0";
5511 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5512 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5513 Result += IDecl->getNameAsString();
5514 Result += "\n";
5515 }
5516 else
5517 Result += ", 0\n";
5518 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5519 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5520 Result += CDecl->getNameAsString();
5521 Result += ",0,0\n";
5522 }
5523 else
5524 Result += "\t,0,0,0,0\n";
5525 Result += "};\n";
5526
5527 // class metadata generation.
5528 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5529 Result += CDecl->getNameAsString();
5530 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5531 "{\n\t&_OBJC_METACLASS_";
5532 Result += CDecl->getNameAsString();
5533 if (SuperClass) {
5534 Result += ", \"";
5535 Result += SuperClass->getNameAsString();
5536 Result += "\", \"";
5537 Result += CDecl->getNameAsString();
5538 Result += "\"";
5539 }
5540 else {
5541 Result += ", 0, \"";
5542 Result += CDecl->getNameAsString();
5543 Result += "\"";
5544 }
5545 // 'info' field is initialized to CLS_CLASS(1) for class
5546 Result += ", 0,1";
5547 if (!ObjCSynthesizedStructs.count(CDecl))
5548 Result += ",0";
5549 else {
5550 // class has size. Must synthesize its size.
5551 Result += ",sizeof(struct ";
5552 Result += CDecl->getNameAsString();
5553 if (LangOpts.MicrosoftExt)
5554 Result += "_IMPL";
5555 Result += ")";
5556 }
5557 if (NumIvars > 0) {
5558 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5559 Result += CDecl->getNameAsString();
5560 Result += "\n\t";
5561 }
5562 else
5563 Result += ",0";
5564 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5565 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5566 Result += CDecl->getNameAsString();
5567 Result += ", 0\n\t";
5568 }
5569 else
5570 Result += ",0,0";
5571 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5572 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5573 Result += CDecl->getNameAsString();
5574 Result += ", 0,0\n";
5575 }
5576 else
5577 Result += ",0,0,0\n";
5578 Result += "};\n";
5579}
5580
5581void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5582 int ClsDefCount = ClassImplementation.size();
5583 int CatDefCount = CategoryImplementation.size();
5584
5585 // For each implemented class, write out all its meta data.
5586 for (int i = 0; i < ClsDefCount; i++)
5587 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5588
5589 // For each implemented category, write out all its meta data.
5590 for (int i = 0; i < CatDefCount; i++)
5591 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5592
5593 // Write objc_symtab metadata
5594 /*
5595 struct _objc_symtab
5596 {
5597 long sel_ref_cnt;
5598 SEL *refs;
5599 short cls_def_cnt;
5600 short cat_def_cnt;
5601 void *defs[cls_def_cnt + cat_def_cnt];
5602 };
5603 */
5604
5605 Result += "\nstruct _objc_symtab {\n";
5606 Result += "\tlong sel_ref_cnt;\n";
5607 Result += "\tSEL *refs;\n";
5608 Result += "\tshort cls_def_cnt;\n";
5609 Result += "\tshort cat_def_cnt;\n";
5610 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5611 Result += "};\n\n";
5612
5613 Result += "static struct _objc_symtab "
5614 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5615 Result += "\t0, 0, " + utostr(ClsDefCount)
5616 + ", " + utostr(CatDefCount) + "\n";
5617 for (int i = 0; i < ClsDefCount; i++) {
5618 Result += "\t,&_OBJC_CLASS_";
5619 Result += ClassImplementation[i]->getNameAsString();
5620 Result += "\n";
5621 }
5622
5623 for (int i = 0; i < CatDefCount; i++) {
5624 Result += "\t,&_OBJC_CATEGORY_";
5625 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5626 Result += "_";
5627 Result += CategoryImplementation[i]->getNameAsString();
5628 Result += "\n";
5629 }
5630
5631 Result += "};\n\n";
5632
5633 // Write objc_module metadata
5634
5635 /*
5636 struct _objc_module {
5637 long version;
5638 long size;
5639 const char *name;
5640 struct _objc_symtab *symtab;
5641 }
5642 */
5643
5644 Result += "\nstruct _objc_module {\n";
5645 Result += "\tlong version;\n";
5646 Result += "\tlong size;\n";
5647 Result += "\tconst char *name;\n";
5648 Result += "\tstruct _objc_symtab *symtab;\n";
5649 Result += "};\n\n";
5650 Result += "static struct _objc_module "
5651 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5652 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5653 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5654 Result += "};\n\n";
5655
5656 if (LangOpts.MicrosoftExt) {
5657 if (ProtocolExprDecls.size()) {
5658 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5659 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5660 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5661 E = ProtocolExprDecls.end(); I != E; ++I) {
5662 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5663 Result += (*I)->getNameAsString();
5664 Result += " = &_OBJC_PROTOCOL_";
5665 Result += (*I)->getNameAsString();
5666 Result += ";\n";
5667 }
5668 Result += "#pragma data_seg(pop)\n\n";
5669 }
5670 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5671 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5672 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5673 Result += "&_OBJC_MODULES;\n";
5674 Result += "#pragma data_seg(pop)\n\n";
5675 }
5676}
5677
5678/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5679/// implementation.
5680void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5681 std::string &Result) {
5682 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5683 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005684 ObjCCategoryDecl *CDecl
5685 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005686
5687 std::string FullCategoryName = ClassDecl->getNameAsString();
5688 FullCategoryName += '_';
5689 FullCategoryName += IDecl->getNameAsString();
5690
5691 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005692 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005693
5694 // If any of our property implementations have associated getters or
5695 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005696 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005697 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005698 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005699 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005700 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005701 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005702 if (!PD)
5703 continue;
5704 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5705 InstanceMethods.push_back(Getter);
5706 if (PD->isReadOnly())
5707 continue;
5708 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5709 InstanceMethods.push_back(Setter);
5710 }
5711 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5712 true, "CATEGORY_", FullCategoryName.c_str(),
5713 Result);
5714
5715 // Build _objc_method_list for class's class methods if needed
5716 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5717 false, "CATEGORY_", FullCategoryName.c_str(),
5718 Result);
5719
5720 // Protocols referenced in class declaration?
5721 // Null CDecl is case of a category implementation with no category interface
5722 if (CDecl)
5723 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5724 FullCategoryName, Result);
5725 /* struct _objc_category {
5726 char *category_name;
5727 char *class_name;
5728 struct _objc_method_list *instance_methods;
5729 struct _objc_method_list *class_methods;
5730 struct _objc_protocol_list *protocols;
5731 // Objective-C 1.0 extensions
5732 uint32_t size; // sizeof (struct _objc_category)
5733 struct _objc_property_list *instance_properties; // category's own
5734 // @property decl.
5735 };
5736 */
5737
5738 static bool objc_category = false;
5739 if (!objc_category) {
5740 Result += "\nstruct _objc_category {\n";
5741 Result += "\tchar *category_name;\n";
5742 Result += "\tchar *class_name;\n";
5743 Result += "\tstruct _objc_method_list *instance_methods;\n";
5744 Result += "\tstruct _objc_method_list *class_methods;\n";
5745 Result += "\tstruct _objc_protocol_list *protocols;\n";
5746 Result += "\tunsigned int size;\n";
5747 Result += "\tstruct _objc_property_list *instance_properties;\n";
5748 Result += "};\n";
5749 objc_category = true;
5750 }
5751 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5752 Result += FullCategoryName;
5753 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5754 Result += IDecl->getNameAsString();
5755 Result += "\"\n\t, \"";
5756 Result += ClassDecl->getNameAsString();
5757 Result += "\"\n";
5758
5759 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5760 Result += "\t, (struct _objc_method_list *)"
5761 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5762 Result += FullCategoryName;
5763 Result += "\n";
5764 }
5765 else
5766 Result += "\t, 0\n";
5767 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5768 Result += "\t, (struct _objc_method_list *)"
5769 "&_OBJC_CATEGORY_CLASS_METHODS_";
5770 Result += FullCategoryName;
5771 Result += "\n";
5772 }
5773 else
5774 Result += "\t, 0\n";
5775
5776 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5777 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5778 Result += FullCategoryName;
5779 Result += "\n";
5780 }
5781 else
5782 Result += "\t, 0\n";
5783 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5784}
5785
5786// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5787/// class methods.
5788template<typename MethodIterator>
5789void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5790 MethodIterator MethodEnd,
5791 bool IsInstanceMethod,
5792 StringRef prefix,
5793 StringRef ClassName,
5794 std::string &Result) {
5795 if (MethodBegin == MethodEnd) return;
5796
5797 if (!objc_impl_method) {
5798 /* struct _objc_method {
5799 SEL _cmd;
5800 char *method_types;
5801 void *_imp;
5802 }
5803 */
5804 Result += "\nstruct _objc_method {\n";
5805 Result += "\tSEL _cmd;\n";
5806 Result += "\tchar *method_types;\n";
5807 Result += "\tvoid *_imp;\n";
5808 Result += "};\n";
5809
5810 objc_impl_method = true;
5811 }
5812
5813 // Build _objc_method_list for class's methods if needed
5814
5815 /* struct {
5816 struct _objc_method_list *next_method;
5817 int method_count;
5818 struct _objc_method method_list[];
5819 }
5820 */
5821 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5822 Result += "\nstatic struct {\n";
5823 Result += "\tstruct _objc_method_list *next_method;\n";
5824 Result += "\tint method_count;\n";
5825 Result += "\tstruct _objc_method method_list[";
5826 Result += utostr(NumMethods);
5827 Result += "];\n} _OBJC_";
5828 Result += prefix;
5829 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5830 Result += "_METHODS_";
5831 Result += ClassName;
5832 Result += " __attribute__ ((used, section (\"__OBJC, __";
5833 Result += IsInstanceMethod ? "inst" : "cls";
5834 Result += "_meth\")))= ";
5835 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5836
5837 Result += "\t,{{(SEL)\"";
5838 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5839 std::string MethodTypeString;
5840 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5841 Result += "\", \"";
5842 Result += MethodTypeString;
5843 Result += "\", (void *)";
5844 Result += MethodInternalNames[*MethodBegin];
5845 Result += "}\n";
5846 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5847 Result += "\t ,{(SEL)\"";
5848 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5849 std::string MethodTypeString;
5850 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5851 Result += "\", \"";
5852 Result += MethodTypeString;
5853 Result += "\", (void *)";
5854 Result += MethodInternalNames[*MethodBegin];
5855 Result += "}\n";
5856 }
5857 Result += "\t }\n};\n";
5858}
5859
5860Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5861 SourceRange OldRange = IV->getSourceRange();
5862 Expr *BaseExpr = IV->getBase();
5863
5864 // Rewrite the base, but without actually doing replaces.
5865 {
5866 DisableReplaceStmtScope S(*this);
5867 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5868 IV->setBase(BaseExpr);
5869 }
5870
5871 ObjCIvarDecl *D = IV->getDecl();
5872
5873 Expr *Replacement = IV;
5874 if (CurMethodDef) {
5875 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5876 const ObjCInterfaceType *iFaceDecl =
5877 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5878 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5879 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005880 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005881 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5882 clsDeclared);
5883 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5884
5885 // Synthesize an explicit cast to gain access to the ivar.
5886 std::string RecName = clsDeclared->getIdentifier()->getName();
5887 RecName += "_IMPL";
5888 IdentifierInfo *II = &Context->Idents.get(RecName);
5889 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5890 SourceLocation(), SourceLocation(),
5891 II);
5892 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5893 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5894 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5895 CK_BitCast,
5896 IV->getBase());
5897 // Don't forget the parens to enforce the proper binding.
5898 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5899 OldRange.getEnd(),
5900 castExpr);
5901 if (IV->isFreeIvar() &&
Douglas Gregor0b144e12011-12-15 00:29:59 +00005902 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005903 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5904 IV->getLocation(),
5905 D->getType(),
5906 VK_LValue, OK_Ordinary);
5907 Replacement = ME;
5908 } else {
5909 IV->setBase(PE);
5910 }
5911 }
5912 } else { // we are outside a method.
5913 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5914
5915 // Explicit ivar refs need to have a cast inserted.
5916 // FIXME: consider sharing some of this code with the code above.
5917 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5918 const ObjCInterfaceType *iFaceDecl =
5919 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5920 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005921 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005922 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5923 clsDeclared);
5924 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5925
5926 // Synthesize an explicit cast to gain access to the ivar.
5927 std::string RecName = clsDeclared->getIdentifier()->getName();
5928 RecName += "_IMPL";
5929 IdentifierInfo *II = &Context->Idents.get(RecName);
5930 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5931 SourceLocation(), SourceLocation(),
5932 II);
5933 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5934 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5935 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5936 CK_BitCast,
5937 IV->getBase());
5938 // Don't forget the parens to enforce the proper binding.
5939 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5940 IV->getBase()->getLocEnd(), castExpr);
5941 // Cannot delete IV->getBase(), since PE points to it.
5942 // Replace the old base with the cast. This is important when doing
5943 // embedded rewrites. For example, [newInv->_container addObject:0].
5944 IV->setBase(PE);
5945 }
5946 }
5947
5948 ReplaceStmtWithRange(IV, Replacement, OldRange);
5949 return Replacement;
5950}
Alp Toker0621cb22014-07-16 16:48:33 +00005951
5952#endif