blob: 934d6aa34aa132eabf4f3e993174821519d3fbcc [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:
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000040 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000042 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000046 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000047 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000048 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000049 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000061 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000062
Chris Lattner0bd1c972007-10-16 21:07:07 +000063 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000064 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000065 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000066 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000067 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000068 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000069 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000070 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000071 Stmt *CurrentBody;
72 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000073 std::string InFileName;
Peter Collingbourne03f89072016-07-15 00:55:40 +000074 std::unique_ptr<raw_ostream> OutFile;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000075 std::string Preamble;
76
77 TypeDecl *ProtocolTypeDecl;
78 VarDecl *GlobalVarDecl;
79 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000080 // ObjC string constant support.
81 unsigned NumObjCStringLiterals;
82 VarDecl *ConstantStringClassReference;
83 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000084
Fariborz Jahanian8efef602011-12-05 19:50:04 +000085 // ObjC foreach break/continue generation support.
86 int BcLabelCount;
87
Fariborz Jahanian83077422011-12-08 18:25:15 +000088 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000089 // Needed for super.
90 ObjCMethodDecl *CurMethodDef;
91 RecordDecl *SuperStructDecl;
92 RecordDecl *ConstantStringDecl;
93
94 FunctionDecl *MsgSendFunctionDecl;
95 FunctionDecl *MsgSendSuperFunctionDecl;
96 FunctionDecl *MsgSendStretFunctionDecl;
97 FunctionDecl *MsgSendSuperStretFunctionDecl;
98 FunctionDecl *MsgSendFpretFunctionDecl;
99 FunctionDecl *GetClassFunctionDecl;
100 FunctionDecl *GetMetaClassFunctionDecl;
101 FunctionDecl *GetSuperClassFunctionDecl;
102 FunctionDecl *SelGetUidFunctionDecl;
103 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000104 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000105 FunctionDecl *CurFunctionDef;
106 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000107
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000108 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
114 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000115 SmallVector<Stmt *, 32> Stmts;
116 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000117 // Remember all the @protocol(<expr>) expressions.
118 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000119
120 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000121
122 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000123 SmallVector<BlockExpr *, 32> Blocks;
124 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000125 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000126
John McCall113bee02012-03-10 09:33:50 +0000127 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000128
Steve Naroff677ab3a2008-10-27 17:20:55 +0000129 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000130 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000132 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000133 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000134 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000135 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000136 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
137
Steve Naroff677ab3a2008-10-27 17:20:55 +0000138 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
139
Steve Naroff22216db2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000144
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000145 // Needed for header files being rewritten
146 bool IsHeader;
147 bool SilenceRewriteMacroWarning;
148 bool objc_impl_method;
149
Steve Naroff08628db2008-12-09 12:56:34 +0000150 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000151 class DisableReplaceStmtScope {
152 RewriteObjC &R;
153 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000154
John McCallfe96e0b2011-11-06 09:01:30 +0000155 public:
156 DisableReplaceStmtScope(RewriteObjC &R)
157 : R(R), SavedValue(R.DisableReplaceStmt) {
158 R.DisableReplaceStmt = true;
159 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000160
John McCallfe96e0b2011-11-06 09:01:30 +0000161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
163 }
164 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000165
Fariborz Jahanian83077422011-12-08 18:25:15 +0000166 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnere99c8322007-10-11 00:43:27 +0000168 public:
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 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000191 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000192 void HandleDeclInMainFile(Decl *D);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000193 RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000194 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000195 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000196
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000197 ~RewriteObjC() override {}
Mike Stump11289f42009-09-09 15:08:12 +0000198
Craig Topperfb6b25b2014-03-15 04:29:04 +0000199 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump11289f42009-09-09 15:08:12 +0000200
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000201 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000202 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Chris Lattner2e0d2602008-01-31 19:37:57 +0000203 }
Steve Naroff08628db2008-12-09 12:56:34 +0000204
205 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000206 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000207
208 Stmt *ReplacingStmt = ReplacedNodes[Old];
209 if (ReplacingStmt)
210 return; // We can't rewrite the same node twice.
211
John McCallfe96e0b2011-11-06 09:01:30 +0000212 if (DisableReplaceStmt)
213 return;
214
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000215 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000216 int Size = Rewrite.getRangeSize(SrcRange);
217 if (Size == -1) {
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 return;
221 }
222 // Get the new text.
223 std::string SStr;
224 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000225 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000226 const std::string &Str = S.str();
227
228 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000229 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000230 ReplacedNodes[Old] = New;
231 return;
232 }
233 if (SilenceRewriteMacroWarning)
234 return;
235 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
236 << Old->getSourceRange();
237 }
238
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000239 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000240 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000241 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000242 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000243 SilenceRewriteMacroWarning)
244 return;
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattner1780a852008-01-31 19:42:41 +0000246 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
247 }
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner9cc55f52008-01-31 19:51:04 +0000249 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000250 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000251 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000252 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000253 SilenceRewriteMacroWarning)
254 return;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattner9cc55f52008-01-31 19:51:04 +0000256 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Chris Lattner3c799d72007-10-24 17:06:59 +0000259 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000260 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000261 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000262 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000263 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000264 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000265 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000266 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000267 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
268 ObjCImplementationDecl *IMD,
269 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000270 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000271 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000272 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
273 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000274 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
275 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000276 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000277 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000278 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
279 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000280 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000281 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000282 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000283 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000284 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000285 void RewriteBlockPointerType(std::string& Str, QualType Type);
286 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000287 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000288 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000289 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000290 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000291
Chris Lattner3c799d72007-10-24 17:06:59 +0000292 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000293 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000294 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000295 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
296 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000297 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000298 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000299 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000300 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000301 void RewriteTryReturnStmts(Stmt *S);
302 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000303 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000304 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000305 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000306 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000310 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000311
Steve Naroff677ab3a2008-10-27 17:20:55 +0000312 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000313 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000314
Mike Stump11289f42009-09-09 15:08:12 +0000315 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000316 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000317 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000318 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000319 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000320 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000321
322 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
323 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000324
David Blaikie1cbb9712014-11-14 19:09:44 +0000325 void Initialize(ASTContext &context) override = 0;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000326
Fariborz Jahanian83077422011-12-08 18:25:15 +0000327 // Metadata Rewriting.
328 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
329 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
330 StringRef prefix,
331 StringRef ClassName,
332 std::string &Result) = 0;
333 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
334 std::string &Result) = 0;
335 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336 StringRef prefix,
337 StringRef ClassName,
338 std::string &Result) = 0;
339 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
340 std::string &Result) = 0;
341
342 // Rewriting ivar access
343 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
344 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
345 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000346
Benjamin Kramer474261a2012-06-02 10:20:41 +0000347 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000348 // rewriting routines on the new ASTs.
349 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000350 ArrayRef<Expr *> Args,
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000351 SourceLocation StartLoc=SourceLocation(),
352 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000353 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
354 QualType msgSendType,
355 QualType returnType,
356 SmallVectorImpl<QualType> &ArgTypes,
357 SmallVectorImpl<Expr*> &MsgExprs,
358 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000373 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000374
375 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000376 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000377 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000378 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000380 std::string SynthesizeBlockImpl(BlockExpr *CE,
381 std::string Tag, std::string Desc);
382 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000384 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000385 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000386 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000387 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000389 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000391 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000392
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000393 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000394 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000395 void WarnAboutReturnGotoStmts(Stmt *S);
396 void HasReturnStmts(Stmt *S, bool &hasReturns);
397 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000404 void GetInnerBlockDeclRefExprs(Stmt *S,
405 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000406 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Steve Naroff677ab3a2008-10-27 17:20:55 +0000408 // We avoid calling Type::isBlockPointerType(), since it operates on the
409 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000410 bool isTopLevelBlockPointerType(QualType T) {
411 return isa<BlockPointerType>(T);
412 }
Mike Stump11289f42009-09-09 15:08:12 +0000413
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000414 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415 /// to a function pointer type and upon success, returns true; false
416 /// otherwise.
417 bool convertBlockPointerToFunctionPointer(QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
419 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420 T = Context->getPointerType(BPT->getPointeeType());
421 return true;
422 }
423 return false;
424 }
425
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000426 bool needToScanForQualifiers(QualType T);
427 QualType getSuperStructType();
428 QualType getConstantStringStructType();
429 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000432 void convertToUnqualifiedObjCType(QualType &T) {
433 if (T->isObjCQualifiedIdType())
434 T = Context->getObjCIdType();
435 else if (T->isObjCQualifiedClassType())
436 T = Context->getObjCClassType();
437 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000438 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439 if (const ObjCObjectPointerType * OBJPT =
440 T->getAsObjCInterfacePointerType()) {
441 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442 T = QualType(IFaceT, 0);
443 T = Context->getPointerType(T);
444 }
445 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000446 }
447
Steve Naroff677ab3a2008-10-27 17:20:55 +0000448 // FIXME: This predicate seems like it would be useful to add to ASTContext.
449 bool isObjCType(QualType T) {
450 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
451 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000452
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000454
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
457 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000459 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000461 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000462 return true;
463 }
464 return false;
465 }
466 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000467 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000468 void GetExtentOfArgList(const char *Name, const char *&LParen,
469 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000470
Steve Naroffd9803712009-04-29 16:37:50 +0000471 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000472 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000473 if (From[i] == '"')
474 To += "\\\"";
475 else
476 To += From[i];
477 }
478 }
John McCalldb40c7f2010-12-14 08:05:40 +0000479
480 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000481 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000482 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000483 if (result == Context->getObjCInstanceType())
484 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000485 FunctionProtoType::ExtProtoInfo fpi;
486 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000487 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000488 }
John McCall97513962010-01-15 18:39:57 +0000489
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000490 // Helper function: create a CStyleCastExpr with trivial type source info.
491 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
492 CastKind Kind, Expr *E) {
493 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000494 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
495 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000496 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000497
498 StringLiteral *getStringLiteral(StringRef Str) {
499 QualType StrType = Context->getConstantArrayType(
500 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
501 0);
502 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
503 /*Pascal=*/false, StrType, SourceLocation());
504 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000505 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000506
507 class RewriteObjCFragileABI : public RewriteObjC {
508 public:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000509 RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn)
512 : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000513
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000514 ~RewriteObjCFragileABI() override {}
David Blaikie1cbb9712014-11-14 19:09:44 +0000515 void Initialize(ASTContext &context) override;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000516
Fariborz Jahanian83077422011-12-08 18:25:15 +0000517 // Rewriting metadata
518 template<typename MethodIterator>
519 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
520 MethodIterator MethodEnd,
521 bool IsInstanceMethod,
522 StringRef prefix,
523 StringRef ClassName,
524 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000525 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
526 StringRef prefix, StringRef ClassName,
527 std::string &Result) override;
528 void RewriteObjCProtocolListMetaData(
529 const ObjCList<ObjCProtocolDecl> &Prots,
530 StringRef prefix, StringRef ClassName, std::string &Result) override;
531 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
532 std::string &Result) override;
533 void RewriteMetaDataIntoBuffer(std::string &Result) override;
534 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
535 std::string &Result) override;
536
Fariborz Jahanian83077422011-12-08 18:25:15 +0000537 // Rewriting ivar
Craig Topperfb6b25b2014-03-15 04:29:04 +0000538 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
539 std::string &Result) override;
540 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahanian83077422011-12-08 18:25:15 +0000541 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000542} // end anonymous namespace
Chris Lattnere99c8322007-10-11 00:43:27 +0000543
Mike Stump11289f42009-09-09 15:08:12 +0000544void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
545 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000546 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000547 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000548 for (const auto &I : fproto->param_types())
549 if (isTopLevelBlockPointerType(I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000550 // All the args are checked/rewritten. Don't call twice!
551 RewriteBlockPointerDecl(D);
552 break;
553 }
554 }
555}
556
557void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000558 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000559 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000560 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000561}
562
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000563static bool IsHeaderFile(const std::string &Filename) {
564 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000565
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000566 if (DotPos == std::string::npos) {
567 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000568 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000569 }
Mike Stump11289f42009-09-09 15:08:12 +0000570
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000571 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
572 // C header: .h
573 // C++ header: .hh or .H;
574 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000575}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000576
Peter Collingbourne03f89072016-07-15 00:55:40 +0000577RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000578 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000579 bool silenceMacroWarn)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000580 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
581 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000582 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000583 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000584 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000585 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
586 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000587 "rewriter doesn't support user-specified control flow semantics "
588 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000589}
590
David Blaikie6beb6aa2014-08-10 19:56:51 +0000591std::unique_ptr<ASTConsumer>
Peter Collingbourne03f89072016-07-15 00:55:40 +0000592clang::CreateObjCRewriter(const std::string &InFile,
593 std::unique_ptr<raw_ostream> OS,
David Blaikie6beb6aa2014-08-10 19:56:51 +0000594 DiagnosticsEngine &Diags, const LangOptions &LOpts,
595 bool SilenceRewriteMacroWarning) {
Peter Collingbourne03f89072016-07-15 00:55:40 +0000596 return llvm::make_unique<RewriteObjCFragileABI>(
597 InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000598}
Chris Lattnere99c8322007-10-11 00:43:27 +0000599
Fariborz Jahanian83077422011-12-08 18:25:15 +0000600void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000601 Context = &context;
602 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000603 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000604 MsgSendFunctionDecl = nullptr;
605 MsgSendSuperFunctionDecl = nullptr;
606 MsgSendStretFunctionDecl = nullptr;
607 MsgSendSuperStretFunctionDecl = nullptr;
608 MsgSendFpretFunctionDecl = nullptr;
609 GetClassFunctionDecl = nullptr;
610 GetMetaClassFunctionDecl = nullptr;
611 GetSuperClassFunctionDecl = nullptr;
612 SelGetUidFunctionDecl = nullptr;
613 CFStringFunctionDecl = nullptr;
614 ConstantStringClassReference = nullptr;
615 NSStringRecord = nullptr;
616 CurMethodDef = nullptr;
617 CurFunctionDef = nullptr;
618 CurFunctionDeclToDeclareForBlock = nullptr;
619 GlobalVarDecl = nullptr;
620 SuperStructDecl = nullptr;
621 ProtocolTypeDecl = nullptr;
622 ConstantStringDecl = nullptr;
Chris Lattner187f6262008-01-31 19:38:44 +0000623 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000624 SuperConstructorFunctionDecl = nullptr;
Steve Naroffce8e8862008-03-15 00:55:56 +0000625 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000626 PropParentMap = nullptr;
627 CurrentBody = nullptr;
Steve Naroff08628db2008-12-09 12:56:34 +0000628 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000629 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner187f6262008-01-31 19:38:44 +0000631 // Get the ID and start/end of the main file.
632 MainFileID = SM->getMainFileID();
633 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634 MainFileStart = MainBuf->getBufferStart();
635 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000636
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000638}
639
Chris Lattner3c799d72007-10-24 17:06:59 +0000640//===----------------------------------------------------------------------===//
641// Top Level Driver Code
642//===----------------------------------------------------------------------===//
643
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000644void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000645 if (Diags.hasErrorOccurred())
646 return;
647
Chris Lattner0bd1c972007-10-16 21:07:07 +0000648 // Two cases: either the decl could be in the main file, or it could be in a
649 // #included file. If the former, rewrite it now. If the later, check to see
650 // if we rewrote the #include/#import.
651 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000652 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chris Lattner0bd1c972007-10-16 21:07:07 +0000654 // If this is for a builtin, ignore it.
655 if (Loc.isInvalid()) return;
656
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000657 // Look for built-in declarations that we need to refer during the rewrite.
658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000659 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000660 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000661 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000662 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000663 ConstantStringClassReference = FVD;
664 return;
665 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000666 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667 if (ID->isThisDeclarationADefinition())
668 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000669 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000670 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000671 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000674 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000676 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000678 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000679 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
682 SourceLocation StartLoc = IFace->getLocStart();
683 do {
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
687 DG.push_back(*DI);
688 else
689 break;
690
Douglas Gregordc9166c2011-12-15 20:29:51 +0000691 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000692 } while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
694 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000695 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000696 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000697
698 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
701 SourceLocation StartLoc = Proto->getLocStart();
702 do {
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
706 DG.push_back(*DI);
707 else
708 break;
709
710 ++DI;
711 } while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
713 continue;
714 }
715 }
716
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000717 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000718 ++DI;
719 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000720 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000721 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000722 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000723 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000724}
725
Chris Lattner3c799d72007-10-24 17:06:59 +0000726//===----------------------------------------------------------------------===//
727// Syntactic (non-AST) Rewriting Code
728//===----------------------------------------------------------------------===//
729
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000730void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000732 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000735 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000736
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000737 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000738 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr == '#') {
740 if (++BufPtr == MainBufEnd)
741 return;
742 while (*BufPtr == ' ' || *BufPtr == '\t')
743 if (++BufPtr == MainBufEnd)
744 return;
745 if (!strncmp(BufPtr, "import", ImportLen)) {
746 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000747 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000748 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000749 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000750 BufPtr += ImportLen;
751 }
752 }
753 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000754}
755
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000756static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000762 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000763 return S;
764}
765
Steve Naroffc038b3a2008-12-02 17:36:43 +0000766void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000771 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000772 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000777 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000778 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000782
Steve Naroff9af94912008-12-02 15:48:25 +0000783 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000786
Steve Naroff003d00e2008-12-02 16:05:55 +0000787 if (!OID)
788 return;
Bill Wendling44426052012-12-20 19:22:21 +0000789 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000790 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000793 ObjCPropertyDecl::OBJC_PR_copy));
794 std::string Getr;
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000800 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
803 Getr += "{ ";
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000809 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000811 FPRetType);
812 Getr += " _TYPE";
813 if (FPRetType) {
814 Getr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000819 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000820 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000821 std::string ParamStr =
822 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000823 Getr += ParamStr;
824 }
825 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000826 if (FT->getNumParams())
827 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000837 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000844 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000847 return;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Steve Naroff9af94912008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000867 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000870 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000872 Setr += "0, ";
873 else
874 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000886}
Chris Lattner16a0de42007-10-11 18:38:32 +0000887
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000888static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
899}
900
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000901void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000902 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000903 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000910void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000911 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000914 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000920 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000923 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000924 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000926}
Mike Stump11289f42009-09-09 15:08:12 +0000927
Craig Topper5603df42013-07-05 19:34:19 +0000928void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000929 std::string typedefString;
930 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000931 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000932 if (i == 0) {
933 typedefString += "// @class ";
934 typedefString += ForwardDecl->getNameAsString();
935 typedefString += ";\n";
936 }
937 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
938 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000939 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000940}
941
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000942void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000943 // When method is a synthesized one, such as a getter/setter there is
944 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000945 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000946 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000947 SourceLocation LocStart = Method->getLocStart();
948 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000949
Chandler Carruthd48db212011-07-25 21:09:52 +0000950 if (SM->getExpansionLineNumber(LocEnd) >
951 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000952 InsertText(LocStart, "#if 0\n");
953 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000954 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000955 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000956 }
957}
958
Mike Stump11289f42009-09-09 15:08:12 +0000959void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000960 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000961
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000962 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000963 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000964}
965
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000966void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000967 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000968
Steve Naroff5448cf62007-10-30 13:30:57 +0000969 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000970 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000971
Manman Rena7a8b1f2016-01-26 18:05:23 +0000972 for (auto *I : CatDecl->instance_properties())
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000973 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000974 for (auto *I : CatDecl->instance_methods())
975 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000976 for (auto *I : CatDecl->class_methods())
977 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000978
Steve Naroff5448cf62007-10-30 13:30:57 +0000979 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000980 ReplaceText(CatDecl->getAtEndRange().getBegin(),
981 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000982}
983
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000984void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000985 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000986 assert(PDecl->isThisDeclarationADefinition());
987
Steve Narofff921385f2007-10-30 16:42:30 +0000988 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000989 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000990
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000991 for (auto *I : PDecl->instance_methods())
992 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000993 for (auto *I : PDecl->class_methods())
994 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +0000995 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000996 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000997
Steve Narofff921385f2007-10-30 16:42:30 +0000998 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000999 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001000 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001001
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001002 // Must comment out @optional/@required
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
1005 for (const char *p = startBuf; p < endBuf; p++) {
1006 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001007 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001008 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001009
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001010 }
1011 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001012 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001013 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001014
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001015 }
1016 }
Steve Narofff921385f2007-10-30 16:42:30 +00001017}
1018
Douglas Gregorf6102672012-01-01 21:23:57 +00001019void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020 SourceLocation LocStart = (*D.begin())->getLocStart();
1021 if (LocStart.isInvalid())
1022 llvm_unreachable("Invalid SourceLocation");
1023 // FIXME: handle forward protocol that are declared across multiple lines.
1024 ReplaceText(LocStart, 0, "// ");
1025}
1026
1027void
Craig Topper5603df42013-07-05 19:34:19 +00001028RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001029 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001030 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001031 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001032 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001033 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001034}
1035
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001036void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037 const FunctionType *&FPRetType) {
1038 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001039 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001040 else if (T->isFunctionPointerType() ||
1041 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001042 // needs special handling, since pointer-to-functions have special
1043 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001044 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001045 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001046 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001047 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001048 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001049 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001050 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001051 ResultStr +=
1052 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001053 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001054 }
1055 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001056 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001057}
1058
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001059void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001061 std::string &ResultStr) {
1062 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001063 const FunctionType *FPRetType = nullptr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001064 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001065 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001066 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001067
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001068 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001069 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregorffca3a22009-01-09 17:18:27 +00001071 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001072 NameStr += "_I_";
1073 else
1074 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001075
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001076 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001077 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001078
1079 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001080 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001081 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001082 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001083 }
Mike Stump11289f42009-09-09 15:08:12 +00001084 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001085 {
1086 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 int len = selString.size();
1088 for (int i = 0; i < len; i++)
1089 if (selString[i] == ':')
1090 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001091 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001092 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001093 // Remember this name for metadata emission
1094 MethodInternalNames[OMD] = NameStr;
1095 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 // Rewrite arguments
1098 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001099
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001101 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001102 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001103 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001104 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001105 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001106 ResultStr += "struct ";
1107 }
1108 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001109 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001110 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001111 }
1112 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001113 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001114 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001115
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001116 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001117 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001118 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001119
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001120 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001121 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001122 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001123 if (PDecl->getType()->isObjCQualifiedIdType()) {
1124 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001125 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001126 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001127 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001128 QualType QT = PDecl->getType();
1129 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001130 (void)convertBlockPointerToFunctionPointer(QT);
1131 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001132 ResultStr += Name;
1133 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001134 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001137 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001138
Steve Naroffb067bbd2008-07-16 14:40:40 +00001139 if (FPRetType) {
1140 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroffb067bbd2008-07-16 14:40:40 +00001142 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001144 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001145 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001146 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001147 std::string ParamStr =
1148 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001149 ResultStr += ParamStr;
1150 }
1151 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001152 if (FT->getNumParams())
1153 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001154 ResultStr += "...";
1155 }
1156 ResultStr += ")";
1157 } else {
1158 ResultStr += "()";
1159 }
1160 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001161}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001162
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001163void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001164 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1165 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001166
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001167 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001168
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001169 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001170 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001171 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001172 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001173 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001174
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001175 const char *startBuf = SM->getCharacterData(LocStart);
1176 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001177 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001180 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001181 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001182 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001183 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001184 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001185
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001186 const char *startBuf = SM->getCharacterData(LocStart);
1187 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001188 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001189 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001190 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1191 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001192
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001193 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001194}
1195
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001196void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001197 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001198 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001199 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001200 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001201 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001202 ResultStr += "\n";
1203 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001204 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001205 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001206 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001207 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001208 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001209 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001210 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001211 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001212 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001213
Manman Rena7a8b1f2016-01-26 18:05:23 +00001214 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001215 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001216 for (auto *I : ClassDecl->instance_methods())
1217 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001218 for (auto *I : ClassDecl->class_methods())
1219 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +00001220
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001221 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001222 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1223 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001224}
1225
John McCallfe96e0b2011-11-06 09:01:30 +00001226Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1227 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001228
John McCallfe96e0b2011-11-06 09:01:30 +00001229 // We just magically know some things about the structure of this
1230 // expression.
1231 ObjCMessageExpr *OldMsg =
1232 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1233 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001234
John McCallfe96e0b2011-11-06 09:01:30 +00001235 // Because the rewriter doesn't allow us to rewrite rewritten code,
1236 // we need to suppress rewriting the sub-statements.
1237 Expr *Base, *RHS;
1238 {
1239 DisableReplaceStmtScope S(*this);
1240
1241 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001242 Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001243 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1244 Base = OldMsg->getInstanceReceiver();
1245 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1246 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1247 }
1248
1249 // Rebuild the RHS.
1250 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1251 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1252 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1253 }
1254
1255 // TODO: avoid this copy.
1256 SmallVector<SourceLocation, 1> SelLocs;
1257 OldMsg->getSelectorLocs(SelLocs);
1258
Craig Topper8ae12032014-05-07 06:21:57 +00001259 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001260 switch (OldMsg->getReceiverKind()) {
1261 case ObjCMessageExpr::Class:
1262 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1263 OldMsg->getValueKind(),
1264 OldMsg->getLeftLoc(),
1265 OldMsg->getClassReceiverTypeInfo(),
1266 OldMsg->getSelector(),
1267 SelLocs,
1268 OldMsg->getMethodDecl(),
1269 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001270 OldMsg->getRightLoc(),
1271 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001272 break;
1273
1274 case ObjCMessageExpr::Instance:
1275 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1276 OldMsg->getValueKind(),
1277 OldMsg->getLeftLoc(),
1278 Base,
1279 OldMsg->getSelector(),
1280 SelLocs,
1281 OldMsg->getMethodDecl(),
1282 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001283 OldMsg->getRightLoc(),
1284 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001285 break;
1286
1287 case ObjCMessageExpr::SuperClass:
1288 case ObjCMessageExpr::SuperInstance:
1289 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1290 OldMsg->getValueKind(),
1291 OldMsg->getLeftLoc(),
1292 OldMsg->getSuperLoc(),
1293 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1294 OldMsg->getSuperType(),
1295 OldMsg->getSelector(),
1296 SelLocs,
1297 OldMsg->getMethodDecl(),
1298 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001299 OldMsg->getRightLoc(),
1300 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001301 break;
1302 }
1303
1304 Stmt *Replacement = SynthMessageExpr(NewMsg);
1305 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1306 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001307}
1308
John McCallfe96e0b2011-11-06 09:01:30 +00001309Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1310 SourceRange OldRange = PseudoOp->getSourceRange();
1311
1312 // We just magically know some things about the structure of this
1313 // expression.
1314 ObjCMessageExpr *OldMsg =
1315 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1316
1317 // Because the rewriter doesn't allow us to rewrite rewritten code,
1318 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001319 Expr *Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001320 {
1321 DisableReplaceStmtScope S(*this);
1322
1323 // Rebuild the base expression if we have one.
1324 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1325 Base = OldMsg->getInstanceReceiver();
1326 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1327 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001328 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001329 }
Steve Narofff326f402008-12-03 00:56:33 +00001330
John McCallfe96e0b2011-11-06 09:01:30 +00001331 // Intentionally empty.
1332 SmallVector<SourceLocation, 1> SelLocs;
1333 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001334
Craig Topper8ae12032014-05-07 06:21:57 +00001335 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001336 switch (OldMsg->getReceiverKind()) {
1337 case ObjCMessageExpr::Class:
1338 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1339 OldMsg->getValueKind(),
1340 OldMsg->getLeftLoc(),
1341 OldMsg->getClassReceiverTypeInfo(),
1342 OldMsg->getSelector(),
1343 SelLocs,
1344 OldMsg->getMethodDecl(),
1345 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001346 OldMsg->getRightLoc(),
1347 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001348 break;
1349
1350 case ObjCMessageExpr::Instance:
1351 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1352 OldMsg->getValueKind(),
1353 OldMsg->getLeftLoc(),
1354 Base,
1355 OldMsg->getSelector(),
1356 SelLocs,
1357 OldMsg->getMethodDecl(),
1358 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001359 OldMsg->getRightLoc(),
1360 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001361 break;
1362
1363 case ObjCMessageExpr::SuperClass:
1364 case ObjCMessageExpr::SuperInstance:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 OldMsg->getSuperLoc(),
1369 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1370 OldMsg->getSuperType(),
1371 OldMsg->getSelector(),
1372 SelLocs,
1373 OldMsg->getMethodDecl(),
1374 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001375 OldMsg->getRightLoc(),
1376 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001377 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001378 }
John McCallfe96e0b2011-11-06 09:01:30 +00001379
1380 Stmt *Replacement = SynthMessageExpr(NewMsg);
1381 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1382 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001383}
1384
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001385/// SynthCountByEnumWithState - To print:
1386/// ((unsigned int (*)
1387/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001388/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001389/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001390/// "countByEnumeratingWithState:objects:count:"),
1391/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001392/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001394void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1396 "id *, unsigned int))(void *)objc_msgSend)";
1397 buf += "\n\t\t";
1398 buf += "((id)l_collection,\n\t\t";
1399 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1400 buf += "\n\t\t";
1401 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001402 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001403}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001404
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001405/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1406/// statement to exit to its outer synthesized loop.
1407///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001408Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001409 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1410 return S;
1411 // replace break with goto __break_label
1412 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001413
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001414 SourceLocation startLoc = S->getLocStart();
1415 buf = "goto __break_label_";
1416 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001417 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001418
Craig Topper8ae12032014-05-07 06:21:57 +00001419 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001420}
1421
1422/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1423/// statement to continue with its inner synthesized loop.
1424///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001425Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001426 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1427 return S;
1428 // replace continue with goto __continue_label
1429 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001430
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001431 SourceLocation startLoc = S->getLocStart();
1432 buf = "goto __continue_label_";
1433 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001434 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Craig Topper8ae12032014-05-07 06:21:57 +00001436 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001437}
1438
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001439/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001440/// It rewrites:
1441/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001443/// Into:
1444/// {
Mike Stump11289f42009-09-09 15:08:12 +00001445/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001446/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001447/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001448/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001449/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001450/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001451/// if (limit) {
1452/// unsigned long startMutations = *enumState.mutationsPtr;
1453/// do {
1454/// unsigned long counter = 0;
1455/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001456/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001457/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001458/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001459/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001460/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001461/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001462/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001463/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001465/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001466/// }
1467/// else
1468/// elem = nil;
1469/// }
1470///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001471Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001472 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001473 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001474 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001475 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001476 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001477 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001478
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001481 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001482 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483 std::string buf;
1484 buf = "\n{\n\t";
1485 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1486 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001487 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001488 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001489 if (ElementType->isObjCQualifiedIdType() ||
1490 ElementType->isObjCQualifiedInterfaceType())
1491 // Simply use 'id' for all qualified types.
1492 elementTypeAsString = "id";
1493 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001494 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001495 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001497 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001498 buf += elementName;
1499 buf += ";\n\t";
1500 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001501 else {
1502 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001503 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001504 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1505 if (VD->getType()->isObjCQualifiedIdType() ||
1506 VD->getType()->isObjCQualifiedInterfaceType())
1507 // Simply use 'id' for all qualified types.
1508 elementTypeAsString = "id";
1509 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001510 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001513 // struct __objcFastEnumerationState enumState = { 0 };
1514 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001515 // id __rw_items[16];
1516 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001517 // id l_collection = (id)
1518 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001519 // Find start location of 'collection' the hard way!
1520 const char *startCollectionBuf = startBuf;
1521 startCollectionBuf += 3; // skip 'for'
1522 startCollectionBuf = strchr(startCollectionBuf, '(');
1523 startCollectionBuf++; // skip '('
1524 // find 'in' and skip it.
1525 while (*startCollectionBuf != ' ' ||
1526 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1527 (*(startCollectionBuf+3) != ' ' &&
1528 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1529 startCollectionBuf++;
1530 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001531
1532 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001533 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001534 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001535 SourceLocation rightParenLoc = S->getRParenLoc();
1536 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001537 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001538 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001539
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001540 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001541 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001542 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001543 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001544 // ((unsigned int (*)
1545 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001546 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001547 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001548 // "countByEnumeratingWithState:objects:count:"),
1549 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001550 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001551 buf += "unsigned long limit =\n\t\t";
1552 SynthCountByEnumWithState(buf);
1553 buf += ";\n\t";
1554 /// if (limit) {
1555 /// unsigned long startMutations = *enumState.mutationsPtr;
1556 /// do {
1557 /// unsigned long counter = 0;
1558 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001559 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001560 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001561 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001562 buf += "if (limit) {\n\t";
1563 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1564 buf += "do {\n\t\t";
1565 buf += "unsigned long counter = 0;\n\t\t";
1566 buf += "do {\n\t\t\t";
1567 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1568 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1569 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001570 buf += " = (";
1571 buf += elementTypeAsString;
1572 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001573 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001574 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001576 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001578 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001579 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001580 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001581 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001582 /// }
1583 /// else
1584 /// elem = nil;
1585 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001586 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001587 buf = ";\n\t";
1588 buf += "__continue_label_";
1589 buf += utostr(ObjCBcLabelNo.back());
1590 buf += ": ;";
1591 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001592 buf += "} while (counter < limit);\n\t";
1593 buf += "} while (limit = ";
1594 SynthCountByEnumWithState(buf);
1595 buf += ");\n\t";
1596 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001597 buf += " = ((";
1598 buf += elementTypeAsString;
1599 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001600 buf += "__break_label_";
1601 buf += utostr(ObjCBcLabelNo.back());
1602 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 buf += "}\n\t";
1604 buf += "else\n\t\t";
1605 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001606 buf += " = ((";
1607 buf += elementTypeAsString;
1608 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001610
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001611 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001612 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001613 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001614 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001615 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001616 } else {
1617 /* Need to treat single statements specially. For example:
1618 *
1619 * for (A *a in b) if (stuff()) break;
1620 * for (A *a in b) xxxyy;
1621 *
1622 * The following code simply scans ahead to the semi to find the actual end.
1623 */
1624 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1625 const char *semiBuf = strchr(stmtBuf, ';');
1626 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001627 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001628 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001629 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001630 Stmts.pop_back();
1631 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001632 return nullptr;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001633}
1634
Mike Stump11289f42009-09-09 15:08:12 +00001635/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001636/// This routine rewrites @synchronized(expr) stmt;
1637/// into:
1638/// objc_sync_enter(expr);
1639/// @try stmt @finally { objc_sync_exit(expr); }
1640///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001641Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001642 // Get the start location and compute the semi location.
1643 SourceLocation startLoc = S->getLocStart();
1644 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001646 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001647
1648 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001649 buf = "objc_sync_enter((id)";
1650 const char *lparenBuf = startBuf;
1651 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001652 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001653 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1654 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001655 // been rewritten! (which implies the SourceLocation's are invalid).
1656 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001657 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001658 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001659 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001660 buf = ");\n";
1661 // declare a new scope with two variables, _stack and _rethrow.
1662 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1663 buf += "int buf[18/*32-bit i386*/];\n";
1664 buf += "char *pointers[4];} _stack;\n";
1665 buf += "id volatile _rethrow = 0;\n";
1666 buf += "objc_exception_try_enter(&_stack);\n";
1667 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001668 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001669 startLoc = S->getSynchBody()->getLocEnd();
1670 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001671
Steve Naroffad7013b2008-08-19 13:04:19 +00001672 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001673 SourceLocation lastCurlyLoc = startLoc;
1674 buf = "}\nelse {\n";
1675 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001676 buf += "}\n";
1677 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001678 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001679
1680 std::string syncBuf;
1681 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001682
1683 Expr *syncExpr = S->getSynchExpr();
1684 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1685 ? CK_BitCast :
1686 syncExpr->getType()->isBlockPointerType()
1687 ? CK_BlockPointerToObjCPointerCast
1688 : CK_CPointerToObjCPointerCast;
1689 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1690 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001691 std::string syncExprBufS;
1692 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Trieuddd01ce2014-06-09 22:53:25 +00001693 assert(syncExpr != nullptr && "Expected non-null Expr");
Craig Topper8ae12032014-05-07 06:21:57 +00001694 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001695 syncBuf += syncExprBuf.str();
1696 syncBuf += ");";
1697
1698 buf += syncBuf;
1699 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001700 buf += "}\n";
1701 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001702
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001703 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001704
1705 bool hasReturns = false;
1706 HasReturnStmts(S->getSynchBody(), hasReturns);
1707 if (hasReturns)
1708 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1709
Craig Topper8ae12032014-05-07 06:21:57 +00001710 return nullptr;
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001711}
1712
Steve Naroffec60b432009-12-05 21:43:12 +00001713void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1714{
Steve Naroff6d6da252008-12-05 17:03:39 +00001715 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001716 for (Stmt *SubStmt : S->children())
1717 if (SubStmt)
1718 WarnAboutReturnGotoStmts(SubStmt);
Steve Naroff6d6da252008-12-05 17:03:39 +00001719
Steve Naroffec60b432009-12-05 21:43:12 +00001720 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001721 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001722 TryFinallyContainsReturnDiag);
1723 }
Steve Naroff6d6da252008-12-05 17:03:39 +00001724}
1725
Steve Naroffec60b432009-12-05 21:43:12 +00001726void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1727{
1728 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001729 for (Stmt *SubStmt : S->children())
1730 if (SubStmt)
1731 HasReturnStmts(SubStmt, hasReturns);
Steve Naroffec60b432009-12-05 21:43:12 +00001732
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001733 if (isa<ReturnStmt>(S))
1734 hasReturns = true;
Steve Naroffec60b432009-12-05 21:43:12 +00001735}
1736
1737void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001738 // Perform a bottom up traversal of all children.
1739 for (Stmt *SubStmt : S->children())
1740 if (SubStmt) {
1741 RewriteTryReturnStmts(SubStmt);
1742 }
1743 if (isa<ReturnStmt>(S)) {
1744 SourceLocation startLoc = S->getLocStart();
1745 const char *startBuf = SM->getCharacterData(startLoc);
1746 const char *semiBuf = strchr(startBuf, ';');
1747 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1748 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001749
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001750 std::string buf;
1751 buf = "{ objc_exception_try_exit(&_stack); return";
Steve Naroffec60b432009-12-05 21:43:12 +00001752
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001753 ReplaceText(startLoc, 6, buf);
1754 InsertText(onePastSemiLoc, "}");
1755 }
Steve Naroffec60b432009-12-05 21:43:12 +00001756}
1757
1758void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1759 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001760 for (Stmt *SubStmt : S->children())
1761 if (SubStmt) {
1762 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
Steve Naroffec60b432009-12-05 21:43:12 +00001763 }
1764 if (isa<ReturnStmt>(S)) {
1765 SourceLocation startLoc = S->getLocStart();
1766 const char *startBuf = SM->getCharacterData(startLoc);
1767
1768 const char *semiBuf = strchr(startBuf, ';');
1769 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001770 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001771
1772 std::string buf;
1773 buf = "{ objc_exception_try_exit(&_stack);";
1774 buf += syncExitBuf;
1775 buf += " return";
1776
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001777 ReplaceText(startLoc, 6, buf);
1778 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001779 }
Steve Naroffec60b432009-12-05 21:43:12 +00001780}
1781
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001782Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001783 // Get the start location and compute the semi location.
1784 SourceLocation startLoc = S->getLocStart();
1785 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Steve Naroffbf478ec2007-11-07 04:08:17 +00001787 assert((*startBuf == '@') && "bogus @try location");
1788
1789 std::string buf;
1790 // declare a new scope with two variables, _stack and _rethrow.
1791 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1792 buf += "int buf[18/*32-bit i386*/];\n";
1793 buf += "char *pointers[4];} _stack;\n";
1794 buf += "id volatile _rethrow = 0;\n";
1795 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001796 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001797
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001798 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Steve Naroffbf478ec2007-11-07 04:08:17 +00001800 startLoc = S->getTryBody()->getLocEnd();
1801 startBuf = SM->getCharacterData(startLoc);
1802
1803 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001804
Steve Naroffbf478ec2007-11-07 04:08:17 +00001805 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001806 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001807 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001808 buf = " /* @catch begin */ else {\n";
1809 buf += " id _caught = objc_exception_extract(&_stack);\n";
1810 buf += " objc_exception_try_enter (&_stack);\n";
1811 buf += " if (_setjmp(_stack.buf))\n";
1812 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1813 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001814
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001815 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001816 } else { /* no catch list */
1817 buf = "}\nelse {\n";
1818 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1819 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001820 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001821 }
Craig Topper8ae12032014-05-07 06:21:57 +00001822 Stmt *lastCatchBody = nullptr;
Douglas Gregor96c79492010-04-23 22:50:49 +00001823 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1824 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001825 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001826
Douglas Gregor96c79492010-04-23 22:50:49 +00001827 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001828 buf = "if ("; // we are generating code for the first catch clause
1829 else
1830 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001831 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001832 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001833
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001835
Steve Naroffbf478ec2007-11-07 04:08:17 +00001836 const char *lParenLoc = strchr(startBuf, '(');
1837
Douglas Gregor96c79492010-04-23 22:50:49 +00001838 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001839 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001840 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001841 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1842 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001843 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001844 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001845 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001846
Steve Naroffedb5bc62008-02-01 20:02:07 +00001847 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001848 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001849 } else if (catchDecl) {
1850 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001851 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001852 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001853 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001854 } else if (const ObjCObjectPointerType *Ptr =
1855 t->getAs<ObjCObjectPointerType>()) {
1856 // Should be a pointer to a class.
1857 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1858 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001859 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001860 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001861 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001862 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001863 }
1864 }
1865 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001866 lastCatchBody = Catch->getCatchBody();
1867 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001868 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1869 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1870 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1871 assert((*rParenBuf == ')') && "bogus @catch paren location");
1872 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001873
Mike Stump11289f42009-09-09 15:08:12 +00001874 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001875 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001876 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001877 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001878 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001879 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001880 }
1881 // Complete the catch list...
1882 if (lastCatchBody) {
1883 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001884 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1885 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001886
Steve Naroff4adbe312008-09-11 15:29:03 +00001887 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001888 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001889 buf = "} /* last catch end */\n";
1890 buf += "else {\n";
1891 buf += " _rethrow = _caught;\n";
1892 buf += " objc_exception_try_exit(&_stack);\n";
1893 buf += "} } /* @catch end */\n";
1894 if (!S->getFinallyStmt())
1895 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001896 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001897
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898 // Set lastCurlyLoc
1899 lastCurlyLoc = lastCatchBody->getLocEnd();
1900 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001901 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001902 startLoc = finalStmt->getLocStart();
1903 startBuf = SM->getCharacterData(startLoc);
1904 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001905
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001906 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001907
Steve Naroffbf478ec2007-11-07 04:08:17 +00001908 Stmt *body = finalStmt->getFinallyBody();
1909 SourceLocation startLoc = body->getLocStart();
1910 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001911 assert(*SM->getCharacterData(startLoc) == '{' &&
1912 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001913 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001914 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001915
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001916 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001917 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001918 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001919 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001920
Steve Naroffbf478ec2007-11-07 04:08:17 +00001921 // Set lastCurlyLoc
1922 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001923
Steve Naroff6d6da252008-12-05 17:03:39 +00001924 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001925 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001926 } else { /* no finally clause - make sure we synthesize an implicit one */
1927 buf = "{ /* implicit finally clause */\n";
1928 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1929 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1930 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001931 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001932
1933 // Now check for any return/continue/go statements within the @try.
1934 // The implicit finally clause won't called if the @try contains any
1935 // jump statements.
1936 bool hasReturns = false;
1937 HasReturnStmts(S->getTryBody(), hasReturns);
1938 if (hasReturns)
1939 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001940 }
1941 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001942 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001943 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001944 return nullptr;
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001945}
1946
Mike Stump11289f42009-09-09 15:08:12 +00001947// This can't be done with ReplaceStmt(S, ThrowExpr), since
1948// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001949// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001950Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001951 // Get the start location and compute the semi location.
1952 SourceLocation startLoc = S->getLocStart();
1953 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Steve Naroffa733c7f2007-11-07 15:32:26 +00001955 assert((*startBuf == '@') && "bogus @throw location");
1956
1957 std::string buf;
1958 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001959 if (S->getThrowExpr())
1960 buf = "objc_exception_throw(";
1961 else // add an implicit argument
1962 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001963
Steve Naroff29788342008-07-25 15:41:30 +00001964 // handle "@ throw" correctly.
1965 const char *wBuf = strchr(startBuf, 'w');
1966 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001967 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001968
Steve Naroffa733c7f2007-11-07 15:32:26 +00001969 const char *semiBuf = strchr(startBuf, ';');
1970 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001971 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001972 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00001973 return nullptr;
Steve Naroffa733c7f2007-11-07 15:32:26 +00001974}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001975
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001976Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001977 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00001978 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001979 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00001980 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001981 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattner4431a1b2007-11-30 22:53:43 +00001983 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001984 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001985 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001986}
1987
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001988Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001989 if (!SelGetUidFunctionDecl)
1990 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001991 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1992 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001993 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00001994 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001995 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00001996 SelExprs);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001997 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001998 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001999 return SelExp;
2000}
2001
Craig Toppercf2126e2015-10-22 03:13:07 +00002002CallExpr *
2003RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2004 ArrayRef<Expr *> Args,
2005 SourceLocation StartLoc,
2006 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002007 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002008 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002009
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002010 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002011 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2012 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002013
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002014 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002015 QualType pToFunc = Context->getPointerType(msgSendType);
Craig Topper8ae12032014-05-07 06:21:57 +00002016 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002017 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002018 DRE, nullptr, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCall9dd450b2009-09-21 23:43:11 +00002020 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002021
Craig Toppercf2126e2015-10-22 03:13:07 +00002022 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2023 FT->getCallResultType(*Context),
2024 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002025 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002026}
2027
Steve Naroff50d42052007-11-01 13:24:47 +00002028static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2029 const char *&startRef, const char *&endRef) {
2030 while (startBuf < endBuf) {
2031 if (*startBuf == '<')
2032 startRef = startBuf; // mark the start.
2033 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002034 if (startRef && *startRef == '<') {
2035 endRef = startBuf; // mark the end.
2036 return true;
2037 }
2038 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002039 }
2040 startBuf++;
2041 }
2042 return false;
2043}
2044
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002045static void scanToNextArgument(const char *&argRef) {
2046 int angle = 0;
2047 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2048 if (*argRef == '<')
2049 angle++;
2050 else if (*argRef == '>')
2051 angle--;
2052 argRef++;
2053 }
2054 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2055}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002056
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002057bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002058 if (T->isObjCQualifiedIdType())
2059 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002060 if (const PointerType *PT = T->getAs<PointerType>()) {
2061 if (PT->getPointeeType()->isObjCQualifiedIdType())
2062 return true;
2063 }
2064 if (T->isObjCObjectPointerType()) {
2065 T = T->getPointeeType();
2066 return T->isObjCQualifiedInterfaceType();
2067 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002068 if (T->isArrayType()) {
2069 QualType ElemTy = Context->getBaseElementType(T);
2070 return needToScanForQualifiers(ElemTy);
2071 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002072 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002073}
2074
Steve Naroff873bd842008-07-29 18:15:38 +00002075void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2076 QualType Type = E->getType();
2077 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002078 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002079
Steve Naroffdbfc6932008-11-19 21:15:47 +00002080 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2081 Loc = ECE->getLParenLoc();
2082 EndLoc = ECE->getRParenLoc();
2083 } else {
2084 Loc = E->getLocStart();
2085 EndLoc = E->getLocEnd();
2086 }
2087 // This will defend against trying to rewrite synthesized expressions.
2088 if (Loc.isInvalid() || EndLoc.isInvalid())
2089 return;
2090
Steve Naroff873bd842008-07-29 18:15:38 +00002091 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002092 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002093 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff873bd842008-07-29 18:15:38 +00002094 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2095 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002096 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2097 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002098 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002099 InsertText(LessLoc, "/*");
2100 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002101 }
2102 }
2103}
2104
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002105void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002106 SourceLocation Loc;
2107 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002108 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002109 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2110 Loc = VD->getLocation();
2111 Type = VD->getType();
2112 }
2113 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2114 Loc = FD->getLocation();
2115 // Check for ObjC 'id' and class types that have been adorned with protocol
2116 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002117 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002118 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002119 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002120 if (!proto)
2121 return;
Alp Toker314cc812014-01-25 16:55:45 +00002122 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002123 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002124 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2125 Loc = FD->getLocation();
2126 Type = FD->getType();
2127 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002128 else
2129 return;
Mike Stump11289f42009-09-09 15:08:12 +00002130
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002131 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002132 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002133
Steve Naroff50d42052007-11-01 13:24:47 +00002134 const char *endBuf = SM->getCharacterData(Loc);
2135 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002136 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002137 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002138 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002139 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2140 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002141 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2142 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002143 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002144 InsertText(LessLoc, "/*");
2145 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002146 }
2147 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002148 if (!proto)
2149 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002150 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002151 const char *startBuf = SM->getCharacterData(Loc);
2152 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002153 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2154 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002155 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002156
Steve Naroff50d42052007-11-01 13:24:47 +00002157 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002158 // scan forward (from the decl location) for argument types.
2159 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002160 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002161 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2162 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002163 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002164 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002165 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002166 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002167 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002168 InsertText(LessLoc, "/*");
2169 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002170 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002171 startBuf = ++endBuf;
2172 }
2173 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002174 // If the function name is derived from a macro expansion, then the
2175 // argument buffer will not follow the name. Need to speak with Chris.
2176 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002177 startBuf++; // scan forward (from the decl location) for argument types.
2178 startBuf++;
2179 }
Steve Naroff50d42052007-11-01 13:24:47 +00002180 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002181}
2182
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002183void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2184 QualType QT = ND->getType();
2185 const Type* TypePtr = QT->getAs<Type>();
2186 if (!isa<TypeOfExprType>(TypePtr))
2187 return;
2188 while (isa<TypeOfExprType>(TypePtr)) {
2189 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2190 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2191 TypePtr = QT->getAs<Type>();
2192 }
2193 // FIXME. This will not work for multiple declarators; as in:
2194 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002195 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002196 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2197 const char *startBuf = SM->getCharacterData(DeclLoc);
2198 if (ND->getInit()) {
2199 std::string Name(ND->getNameAsString());
2200 TypeAsString += " " + Name + " = ";
2201 Expr *E = ND->getInit();
2202 SourceLocation startLoc;
2203 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2204 startLoc = ECE->getLParenLoc();
2205 else
2206 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002207 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002208 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002209 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002210 }
2211 else {
2212 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002213 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002214 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002215 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002216 }
2217}
2218
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002219// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002220void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002221 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002222 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002223 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002224 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002225 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002226 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002227 SourceLocation(),
2228 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002229 SelGetUidIdent, getFuncType,
2230 nullptr, SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002231}
2232
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002233void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002234 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002235 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002236 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002237 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002238 return;
2239 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002240 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002241}
2242
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002243void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002244 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002245 const char *argPtr = TypeString.c_str();
2246 if (!strchr(argPtr, '^')) {
2247 Str += TypeString;
2248 return;
2249 }
2250 while (*argPtr) {
2251 Str += (*argPtr == '^' ? '*' : *argPtr);
2252 argPtr++;
2253 }
2254}
2255
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002256// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002257void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2258 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002259 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002260 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002261 const char *argPtr = TypeString.c_str();
2262 int paren = 0;
2263 while (*argPtr) {
2264 switch (*argPtr) {
2265 case '(':
2266 Str += *argPtr;
2267 paren++;
2268 break;
2269 case ')':
2270 Str += *argPtr;
2271 paren--;
2272 break;
2273 case '^':
2274 Str += '*';
2275 if (paren == 1)
2276 Str += VD->getNameAsString();
2277 break;
2278 default:
2279 Str += *argPtr;
2280 break;
2281 }
2282 argPtr++;
2283 }
2284}
2285
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002286void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2287 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2288 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2289 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2290 if (!proto)
2291 return;
Alp Toker314cc812014-01-25 16:55:45 +00002292 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002293 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002294 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002295 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002296 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002297 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002298 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002299 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002300 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002301 if (i+1 < numArgs)
2302 FdStr += ", ";
2303 }
2304 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002305 InsertText(FunLocStart, FdStr);
Craig Topper8ae12032014-05-07 06:21:57 +00002306 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002307}
2308
Benjamin Kramer60509af2013-09-09 14:48:42 +00002309// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2310void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2311 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002312 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002313 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002314 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002315 QualType argT = Context->getObjCIdType();
2316 assert(!argT.isNull() && "Can't find 'id' type");
2317 ArgTys.push_back(argT);
2318 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002319 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002320 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002321 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002322 SourceLocation(),
2323 SourceLocation(),
2324 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002325 nullptr, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002326}
2327
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002328// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002329void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002330 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002331 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002332 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002333 assert(!argT.isNull() && "Can't find 'id' type");
2334 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002335 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002336 assert(!argT.isNull() && "Can't find 'SEL' type");
2337 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002338 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002339 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002340 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002341 SourceLocation(),
2342 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002343 msgSendIdent, msgSendType,
2344 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002345}
2346
Steve Naroff7fa2f042007-11-15 10:28:18 +00002347// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002348void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002349 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002350 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002351 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002352 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002353 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002354 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2355 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2356 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002357 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002358 assert(!argT.isNull() && "Can't find 'SEL' type");
2359 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002360 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002361 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002362 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002363 SourceLocation(),
2364 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002365 msgSendIdent, msgSendType,
2366 nullptr, SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002367}
2368
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002369// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002370void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002372 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002373 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002376 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002379 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002380 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002381 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002382 SourceLocation(),
2383 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002384 msgSendIdent, msgSendType,
2385 nullptr, SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002386}
2387
Mike Stump11289f42009-09-09 15:08:12 +00002388// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002389// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002390void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002391 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002392 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002393 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002394 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002395 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002396 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002397 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2398 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2399 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002400 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002401 assert(!argT.isNull() && "Can't find 'SEL' type");
2402 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002403 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002404 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002405 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002406 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002407 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002408 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002409 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002410 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002411}
2412
Steve Naroff2e4e3852008-05-08 22:02:18 +00002413// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002414void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002415 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002417 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002418 assert(!argT.isNull() && "Can't find 'id' type");
2419 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002420 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002421 assert(!argT.isNull() && "Can't find 'SEL' type");
2422 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002423 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002424 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002425 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002426 SourceLocation(),
2427 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002428 msgSendIdent, msgSendType,
2429 nullptr, SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002430}
2431
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002432// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002433void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002434 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002435 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002436 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002437 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002438 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002439 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002440 SourceLocation(),
2441 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002442 getClassIdent, getClassType,
2443 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002444}
2445
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002446// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2447void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2448 IdentifierInfo *getSuperClassIdent =
2449 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002450 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002451 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002452 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002453 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002454 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002455 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002456 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002457 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002458 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002459 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002460}
2461
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002462// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002463void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002464 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002465 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002466 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002467 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002469 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
2472 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002473 nullptr, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002474}
2475
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002476Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002477 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffce8e8862008-03-15 00:55:56 +00002478 QualType strType = getConstantStringStructType();
2479
2480 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002481
2482 std::string tmpName = InFileName;
2483 unsigned i;
2484 for (i=0; i < tmpName.length(); i++) {
2485 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002486 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002487 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002488 tmpName[i] = '_';
2489 }
2490 S += tmpName;
2491 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002492 S += utostr(NumObjCStringLiterals++);
2493
Steve Naroff00a31762008-03-27 22:29:16 +00002494 Preamble += "static __NSConstantStringImpl " + S;
2495 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2496 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002497 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002498 std::string prettyBufS;
2499 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002500 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002501 Preamble += prettyBuf.str();
2502 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002503 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002504
2505 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002506 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002507 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002508 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002509 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002510 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002511 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002512 VK_RValue, OK_Ordinary,
2513 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002514 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002515 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002516 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002517 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002518 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002519 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002520}
2521
Steve Naroff7fa2f042007-11-15 10:28:18 +00002522// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002523QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002524 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002525 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002526 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002527 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002528 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002529
Steve Naroff7fa2f042007-11-15 10:28:18 +00002530 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002531 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002532 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002533 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002534
Steve Naroff7fa2f042007-11-15 10:28:18 +00002535 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002536 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002537 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002538 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002539 SourceLocation(), nullptr,
2540 FieldTypes[i], nullptr,
2541 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002542 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002543 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregord5058122010-02-11 01:19:42 +00002546 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002547 }
2548 return Context->getTagDeclType(SuperStructDecl);
2549}
2550
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002551QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002552 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002553 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002554 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002555 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002556 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002557
Steve Naroffce8e8862008-03-15 00:55:56 +00002558 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002559 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002560 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002561 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002562 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002563 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002564 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002565 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002566
Steve Naroffce8e8862008-03-15 00:55:56 +00002567 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002568 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002569 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2570 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002571 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002572 SourceLocation(), nullptr,
2573 FieldTypes[i], nullptr,
2574 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002575 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002576 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002577 }
2578
Douglas Gregord5058122010-02-11 01:19:42 +00002579 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002580 }
2581 return Context->getTagDeclType(ConstantStringDecl);
2582}
2583
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002584CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2585 QualType msgSendType,
2586 QualType returnType,
2587 SmallVectorImpl<QualType> &ArgTypes,
2588 SmallVectorImpl<Expr*> &MsgExprs,
2589 ObjCMethodDecl *Method) {
2590 // Create a reference to the objc_msgSend_stret() declaration.
2591 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2592 false, msgSendType,
2593 VK_LValue, SourceLocation());
2594 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2595 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2596 Context->getPointerType(Context->VoidTy),
2597 CK_BitCast, STDRE);
2598 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002599 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2600 Method ? Method->isVariadic()
2601 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002602 castType = Context->getPointerType(castType);
2603 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2604 cast);
2605
2606 // Don't forget the parens to enforce the proper binding.
2607 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2608
2609 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002610 CallExpr *STCE = new (Context) CallExpr(
2611 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002612 return STCE;
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002613}
2614
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002615Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2616 SourceLocation StartLoc,
2617 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002618 if (!SelGetUidFunctionDecl)
2619 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002620 if (!MsgSendFunctionDecl)
2621 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002622 if (!MsgSendSuperFunctionDecl)
2623 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002624 if (!MsgSendStretFunctionDecl)
2625 SynthMsgSendStretFunctionDecl();
2626 if (!MsgSendSuperStretFunctionDecl)
2627 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002628 if (!MsgSendFpretFunctionDecl)
2629 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002630 if (!GetClassFunctionDecl)
2631 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002632 if (!GetSuperClassFunctionDecl)
2633 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002634 if (!GetMetaClassFunctionDecl)
2635 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002636
Steve Naroff7fa2f042007-11-15 10:28:18 +00002637 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002638 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2639 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00002640 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroffd9803712009-04-29 16:37:50 +00002641 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002642 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002643 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002644 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002645 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002646 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
Steve Naroff574440f2007-10-24 22:48:43 +00002649 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002650 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002651 switch (Exp->getReceiverKind()) {
2652 case ObjCMessageExpr::SuperClass: {
2653 MsgSendFlavor = MsgSendSuperFunctionDecl;
2654 if (MsgSendStretFlavor)
2655 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2656 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002657
Douglas Gregor9a129192010-04-21 00:45:42 +00002658 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002659
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002660 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002661
Douglas Gregor9a129192010-04-21 00:45:42 +00002662 // set the receiver to self, the first argument to all methods.
2663 InitExprs.push_back(
2664 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002665 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002666 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002667 false,
John McCall7decc9e2010-11-18 06:31:45 +00002668 Context->getObjCIdType(),
2669 VK_RValue,
2670 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002671 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002672
Douglas Gregor9a129192010-04-21 00:45:42 +00002673 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002675 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002676 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002677 ClsExprs, StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002678 // (Class)objc_getClass("CurrentClass")
2679 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2680 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002681 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002682 ClsExprs.clear();
2683 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002684 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002685 StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002686 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2687 // To turn off a warning, type-cast to 'id'
2688 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2689 NoTypeInfoCStyleCastExpr(Context,
2690 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002691 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002692 // struct objc_super
2693 QualType superType = getSuperStructType();
2694 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002695
Francois Pichet0706d202011-09-17 17:15:52 +00002696 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002697 SynthSuperConstructorFunctionDecl();
2698 // Simulate a constructor call...
2699 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002700 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002701 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002702 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002703 superType, VK_LValue,
2704 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002705 // The code for super is a little tricky to prevent collision with
2706 // the structure definition in the header. The rewriter has it's own
2707 // internal definition (__rw_objc_super) that is uses. This is why
2708 // we need the cast below. For example:
2709 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2710 //
John McCalle3027922010-08-25 11:45:40 +00002711 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002712 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002713 VK_RValue, OK_Ordinary,
2714 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002715 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2716 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002717 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002718 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002719 // (struct objc_super) { <exprs from above> }
2720 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002721 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002722 SourceLocation());
2723 TypeSourceInfo *superTInfo
2724 = Context->getTrivialTypeSourceInfo(superType);
2725 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002726 superType, VK_LValue,
2727 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002728 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002729 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002730 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002731 VK_RValue, OK_Ordinary,
2732 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002733 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002734 MsgExprs.push_back(SuperRep);
2735 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002736 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002737
2738 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002739 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002740 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002741 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002742 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002743 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002744 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002745 StartLoc, EndLoc);
2746 MsgExprs.push_back(Cls);
2747 break;
2748 }
2749
2750 case ObjCMessageExpr::SuperInstance:{
2751 MsgSendFlavor = MsgSendSuperFunctionDecl;
2752 if (MsgSendStretFlavor)
2753 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2754 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2755 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002756 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002757
2758 InitExprs.push_back(
2759 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002760 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002761 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002762 false,
John McCall7decc9e2010-11-18 06:31:45 +00002763 Context->getObjCIdType(),
2764 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002765 ); // set the 'receiver'.
2766
2767 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002768 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002769 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002770 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002771 StartLoc, EndLoc);
2772 // (Class)objc_getClass("CurrentClass")
2773 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2774 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002775 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 ClsExprs.clear();
2777 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002778 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002779 StartLoc, EndLoc);
2780
2781 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2782 // To turn off a warning, type-cast to 'id'
2783 InitExprs.push_back(
2784 // set 'super class', using class_getSuperclass().
2785 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002786 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 // struct objc_super
2788 QualType superType = getSuperStructType();
2789 Expr *SuperRep;
2790
Francois Pichet0706d202011-09-17 17:15:52 +00002791 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002792 SynthSuperConstructorFunctionDecl();
2793 // Simulate a constructor call...
2794 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002795 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002796 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002797 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002798 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002799 // The code for super is a little tricky to prevent collision with
2800 // the structure definition in the header. The rewriter has it's own
2801 // internal definition (__rw_objc_super) that is uses. This is why
2802 // we need the cast below. For example:
2803 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2804 //
John McCalle3027922010-08-25 11:45:40 +00002805 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002806 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002807 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002808 SourceLocation());
2809 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2810 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002811 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002812 } else {
2813 // (struct objc_super) { <exprs from above> }
2814 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002815 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002816 SourceLocation());
2817 TypeSourceInfo *superTInfo
2818 = Context->getTrivialTypeSourceInfo(superType);
2819 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002820 superType, VK_RValue, ILE,
2821 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002822 }
2823 MsgExprs.push_back(SuperRep);
2824 break;
2825 }
2826
2827 case ObjCMessageExpr::Instance: {
2828 // Remove all type-casts because it may contain objc-style types; e.g.
2829 // Foo<Proto> *.
2830 Expr *recExpr = Exp->getInstanceReceiver();
2831 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2832 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002833 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2834 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2835 ? CK_BlockPointerToObjCPointerCast
2836 : CK_CPointerToObjCPointerCast;
2837
Douglas Gregor9a129192010-04-21 00:45:42 +00002838 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002839 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002840 MsgExprs.push_back(recExpr);
2841 break;
2842 }
2843 }
2844
Steve Naroffa397efd2007-11-03 11:27:19 +00002845 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002846 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002847 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002848 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002849 SelExprs, StartLoc, EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002850 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Steve Naroff574440f2007-10-24 22:48:43 +00002852 // Now push any user supplied arguments.
2853 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002854 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002855 // Make all implicit casts explicit...ICE comes in handy:-)
2856 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2857 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002858 QualType type = ICE->getType();
2859 if (needToScanForQualifiers(type))
2860 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002861 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002862 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002863 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002864 CastKind CK;
2865 if (SubExpr->getType()->isIntegralType(*Context) &&
2866 type->isBooleanType()) {
2867 CK = CK_IntegralToBoolean;
2868 } else if (type->isObjCObjectPointerType()) {
2869 if (SubExpr->getType()->isBlockPointerType()) {
2870 CK = CK_BlockPointerToObjCPointerCast;
2871 } else if (SubExpr->getType()->isPointerType()) {
2872 CK = CK_CPointerToObjCPointerCast;
2873 } else {
2874 CK = CK_BitCast;
2875 }
2876 } else {
2877 CK = CK_BitCast;
2878 }
2879
2880 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002881 }
2882 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002883 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002884 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002885 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002886 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002887 CastKind CK;
2888 if (userExpr->getType()->isIntegralType(*Context)) {
2889 CK = CK_IntegralToPointer;
2890 } else if (userExpr->getType()->isBlockPointerType()) {
2891 CK = CK_BlockPointerToObjCPointerCast;
2892 } else if (userExpr->getType()->isPointerType()) {
2893 CK = CK_CPointerToObjCPointerCast;
2894 } else {
2895 CK = CK_BitCast;
2896 }
John McCall97513962010-01-15 18:39:57 +00002897 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002898 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002899 }
Mike Stump11289f42009-09-09 15:08:12 +00002900 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002901 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002902 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2903 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002904 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002905 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002906 }
Steve Narofff36987c2007-11-04 22:37:50 +00002907 // Generate the funky cast.
2908 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002909 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002910 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002911
Steve Narofff36987c2007-11-04 22:37:50 +00002912 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002913 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2914 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2915 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002916 ArgTypes.push_back(Context->getObjCIdType());
2917 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002918 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002919 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00002920 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002921 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002922 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002923 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002924 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002925 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002926 ArgTypes.push_back(t);
2927 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002928 returnType = Exp->getType();
2929 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002930 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002931 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002932 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002933 }
2934 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002935 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002936
Steve Narofff36987c2007-11-04 22:37:50 +00002937 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002938 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002939 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002940
Mike Stump11289f42009-09-09 15:08:12 +00002941 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002942 // If we don't do this cast, we get the following bizarre warning/note:
2943 // xx.m:13: warning: function called through a non-compatible type
2944 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002945 cast = NoTypeInfoCStyleCastExpr(Context,
2946 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002947 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002948
Steve Narofff36987c2007-11-04 22:37:50 +00002949 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002950 // If we don't have a method decl, force a variadic cast.
2951 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002952 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002953 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002954 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002955 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002956 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002957
2958 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002959 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002960
John McCall9dd450b2009-09-21 23:43:11 +00002961 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002962 CallExpr *CE = new (Context)
2963 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002964 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002965 if (MsgSendStretFlavor) {
2966 // We have the method which returns a struct/union. Must also generate
2967 // call to objc_msgSend_stret and hang both varieties on a conditional
2968 // expression which dictate which one to envoke depending on size of
2969 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002970
2971 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2972 msgSendType, returnType,
2973 ArgTypes, MsgExprs,
2974 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002975
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002976 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002977 UnaryExprOrTypeTraitExpr *sizeofExpr =
2978 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2979 Context->getTrivialTypeSourceInfo(returnType),
2980 Context->getSizeType(), SourceLocation(),
2981 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002982 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2983 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2984 // For X86 it is more complicated and some kind of target specific routine
2985 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002986 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002987 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002988 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2989 llvm::APInt(IntSize, 8),
2990 Context->IntTy,
2991 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00002992 BinaryOperator *lessThanExpr =
2993 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00002994 VK_RValue, OK_Ordinary, SourceLocation(),
2995 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002996 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002997 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002998 new (Context) ConditionalOperator(lessThanExpr,
2999 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003000 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003001 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003002 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3003 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003004 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003005 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003006 return ReplacingStmt;
3007}
3008
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003009Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003010 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3011 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003012
Steve Naroff574440f2007-10-24 22:48:43 +00003013 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003014 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003015
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003016 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003017 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003018}
3019
Steve Naroffd9803712009-04-29 16:37:50 +00003020// typedef struct objc_object Protocol;
3021QualType RewriteObjC::getProtocolType() {
3022 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003023 TypeSourceInfo *TInfo
3024 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003025 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003026 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003027 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003028 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003029 }
3030 return Context->getTypeDeclType(ProtocolTypeDecl);
3031}
3032
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003033/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003034/// a synthesized/forward data reference (to the protocol's metadata).
3035/// The forward references (and metadata) are generated in
3036/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003037Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003038 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3039 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003040 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003041 SourceLocation(), ID, getProtocolType(),
3042 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003043 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3044 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003045 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003046 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003047 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003048 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003049 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003050 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003051 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003052 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003053 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003054 return castExpr;
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003055}
3056
Mike Stump11289f42009-09-09 15:08:12 +00003057bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003058 const char *endBuf) {
3059 while (startBuf < endBuf) {
3060 if (*startBuf == '#') {
3061 // Skip whitespace.
3062 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3063 ;
3064 if (!strncmp(startBuf, "if", strlen("if")) ||
3065 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3066 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3067 !strncmp(startBuf, "define", strlen("define")) ||
3068 !strncmp(startBuf, "undef", strlen("undef")) ||
3069 !strncmp(startBuf, "else", strlen("else")) ||
3070 !strncmp(startBuf, "elif", strlen("elif")) ||
3071 !strncmp(startBuf, "endif", strlen("endif")) ||
3072 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3073 !strncmp(startBuf, "include", strlen("include")) ||
3074 !strncmp(startBuf, "import", strlen("import")) ||
3075 !strncmp(startBuf, "include_next", strlen("include_next")))
3076 return true;
3077 }
3078 startBuf++;
3079 }
3080 return false;
3081}
3082
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003083/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003084/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003085void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003086 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003087 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003088 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003089 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003090 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003091 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003092 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003093 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003094 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003095 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003096 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003097
Steve Naroffdde78982007-11-14 19:25:57 +00003098 const char *startBuf = SM->getCharacterData(LocStart);
3099 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003100
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003101 // If no ivars and no root or if its root, directly or indirectly,
3102 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003103 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003104 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003105 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003106 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003107 return;
3108 }
Mike Stump11289f42009-09-09 15:08:12 +00003109
3110 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003111 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003112 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003113 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003114 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003115 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003116
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003117 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003118 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003119 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003120 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003121 // If the buffer contains preprocessor directives, we do more fine-grained
3122 // rewrites. This is intended to fix code that looks like (which occurs in
3123 // NSURL.h, for example):
3124 //
3125 // #ifdef XYZ
3126 // @interface Foo : NSObject
3127 // #else
3128 // @interface FooBar : NSObject
3129 // #endif
3130 // {
3131 // int i;
3132 // }
3133 // @end
3134 //
3135 // This clause is segregated to avoid breaking the common case.
3136 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003137 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003138 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003139 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003140 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003141
Chris Lattnerf5b77512009-02-20 18:18:36 +00003142 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003143 // advance to the end of the referenced protocols.
3144 while (endHeader < cursor && *endHeader != '>') endHeader++;
3145 endHeader++;
3146 }
3147 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003148 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003149 } else {
3150 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003151 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003152 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003153 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003154 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003155 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003156 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003157 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003158 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003159
Steve Naroffdde78982007-11-14 19:25:57 +00003160 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003161 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003162 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003163 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003164 }
3165 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003166
Steve Naroffdde78982007-11-14 19:25:57 +00003167 // Now comment out any visibility specifiers.
3168 while (cursor < endBuf) {
3169 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003170 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003171 // Skip whitespace.
3172 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3173 /*scan*/;
3174
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003175 // FIXME: presence of @public, etc. inside comment results in
3176 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003177 if (!strncmp(cursor, "public", strlen("public")) ||
3178 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003179 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003180 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003181 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003182 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003183 // FIXME: If there are cases where '<' is used in ivar declaration part
3184 // of user code, then scan the ivar list and use needToScanForQualifiers
3185 // for type checking.
3186 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003187 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003188 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003189 cursor = strchr(cursor, '>');
3190 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003191 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003192 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003193 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003194 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003195 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003196 }
Steve Naroffdde78982007-11-14 19:25:57 +00003197 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003198 }
Steve Naroffdde78982007-11-14 19:25:57 +00003199 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003200 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003201 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003202 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003203 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003204 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003205 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003206 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003207 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003208 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003209 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003210 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003211 if (!ObjCSynthesizedStructs.insert(CDecl).second)
David Blaikie83d382b2011-09-23 05:06:16 +00003212 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003213}
3214
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003215//===----------------------------------------------------------------------===//
3216// Meta Data Emission
3217//===----------------------------------------------------------------------===//
3218
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003219/// RewriteImplementations - This routine rewrites all method implementations
3220/// and emits meta-data.
3221
Steve Narofff8cfd162008-11-13 20:07:04 +00003222void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003223 int ClsDefCount = ClassImplementation.size();
3224 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003225
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003226 // Rewrite implemented methods
3227 for (int i = 0; i < ClsDefCount; i++)
3228 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003229
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003230 for (int i = 0; i < CatDefCount; i++)
3231 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003232}
Mike Stump11289f42009-09-09 15:08:12 +00003233
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003234void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3235 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003236 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003237 assert(BlockByRefDeclNo.count(VD) &&
3238 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003239 if (def)
3240 ResultStr += "struct ";
3241 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003242 "_" + utostr(BlockByRefDeclNo[VD]) ;
3243}
3244
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003245static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3246 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3247 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3248 return false;
3249}
3250
Steve Naroff677ab3a2008-10-27 17:20:55 +00003251std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003252 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003253 std::string Tag) {
3254 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003255 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003256 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003257 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003258 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003259
Steve Naroff677ab3a2008-10-27 17:20:55 +00003260 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003261
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003262 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003263 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003264 // block (to reference imported block decl refs).
3265 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003266 } else if (BD->param_empty()) {
3267 S += "(" + StructRef + " *__cself)";
3268 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003269 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003270 assert(FT && "SynthesizeBlockFunc: No function proto");
3271 S += '(';
3272 // first add the implicit argument.
3273 S += StructRef + " *__cself, ";
3274 std::string ParamStr;
3275 for (BlockDecl::param_iterator AI = BD->param_begin(),
3276 E = BD->param_end(); AI != E; ++AI) {
3277 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003278 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003279 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003280 (void)convertBlockPointerToFunctionPointer(QT);
3281 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003282 S += ParamStr;
3283 }
3284 if (FT->isVariadic()) {
3285 if (!BD->param_empty()) S += ", ";
3286 S += "...";
3287 }
3288 S += ')';
3289 }
3290 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003291
Steve Naroff677ab3a2008-10-27 17:20:55 +00003292 // Create local declarations to avoid rewriting all closure decl ref exprs.
3293 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003294 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003295 E = BlockByRefDecls.end(); I != E; ++I) {
3296 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003297 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003298 std::string TypeString;
3299 RewriteByRefString(TypeString, Name, (*I));
3300 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003301 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003302 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003303 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003304 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003305 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003306 E = BlockByCopyDecls.end(); I != E; ++I) {
3307 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003308 // Handle nested closure invocation. For example:
3309 //
3310 // void (^myImportedClosure)(void);
3311 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003312 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003313 // void (^anotherClosure)(void);
3314 // anotherClosure = ^(void) {
3315 // myImportedClosure(); // import and invoke the closure
3316 // };
3317 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003318 if (isTopLevelBlockPointerType((*I)->getType())) {
3319 RewriteBlockPointerTypeVariable(S, (*I));
3320 S += " = (";
3321 RewriteBlockPointerType(S, (*I)->getType());
3322 S += ")";
3323 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3324 }
3325 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003326 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003327 QualType QT = (*I)->getType();
3328 if (HasLocalVariableExternalStorage(*I))
3329 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003330 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003331 S += Name + " = __cself->" +
3332 (*I)->getNameAsString() + "; // bound by copy\n";
3333 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003334 }
3335 std::string RewrittenStr = RewrittenBlockExprs[CE];
3336 const char *cstr = RewrittenStr.c_str();
3337 while (*cstr++ != '{') ;
3338 S += cstr;
3339 S += "\n";
3340 return S;
3341}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003342
Steve Naroff677ab3a2008-10-27 17:20:55 +00003343std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003344 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003345 std::string Tag) {
3346 std::string StructRef = "struct " + Tag;
3347 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003348
Steve Naroff677ab3a2008-10-27 17:20:55 +00003349 S += funcName;
3350 S += "_block_copy_" + utostr(i);
3351 S += "(" + StructRef;
3352 S += "*dst, " + StructRef;
3353 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003354 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003355 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00003356 S += VD->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003357 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003358 S += VD->getNameAsString();
3359 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003360 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003361 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003362 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003363 else
3364 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003365 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003366 S += "}\n";
3367
Steve Naroff677ab3a2008-10-27 17:20:55 +00003368 S += "\nstatic void __";
3369 S += funcName;
3370 S += "_block_dispose_" + utostr(i);
3371 S += "(" + StructRef;
3372 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003373 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003374 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003375 S += VD->getNameAsString();
3376 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003377 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003378 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003379 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003380 else
3381 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003382 }
Mike Stump11289f42009-09-09 15:08:12 +00003383 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003384 return S;
3385}
3386
Steve Naroff30484702009-12-06 21:14:13 +00003387std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3388 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003389 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003390 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003391
Steve Naroff677ab3a2008-10-27 17:20:55 +00003392 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003393 S += " struct " + Desc;
3394 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003395
Steve Naroff30484702009-12-06 21:14:13 +00003396 Constructor += "(void *fp, "; // Invoke function pointer.
3397 Constructor += "struct " + Desc; // Descriptor pointer.
3398 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003399
Steve Naroff677ab3a2008-10-27 17:20:55 +00003400 if (BlockDeclRefs.size()) {
3401 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003402 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003403 E = BlockByCopyDecls.end(); I != E; ++I) {
3404 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003405 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003406 std::string ArgName = "_" + FieldName;
3407 // Handle nested closure invocation. For example:
3408 //
3409 // void (^myImportedBlock)(void);
3410 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003411 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003412 // void (^anotherBlock)(void);
3413 // anotherBlock = ^(void) {
3414 // myImportedBlock(); // import and invoke the closure
3415 // };
3416 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003417 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003418 S += "struct __block_impl *";
3419 Constructor += ", void *" + ArgName;
3420 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003421 QualType QT = (*I)->getType();
3422 if (HasLocalVariableExternalStorage(*I))
3423 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003424 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3425 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003426 Constructor += ", " + ArgName;
3427 }
3428 S += FieldName + ";\n";
3429 }
3430 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003431 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003432 E = BlockByRefDecls.end(); I != E; ++I) {
3433 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003434 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003435 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003436 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003437 std::string TypeString;
3438 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003439 TypeString += " *";
3440 FieldName = TypeString + FieldName;
3441 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003442 Constructor += ", " + ArgName;
3443 }
3444 S += FieldName + "; // by ref\n";
3445 }
3446 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003447 Constructor += ", int flags=0)";
3448 // Initialize all "by copy" arguments.
3449 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003450 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003451 E = BlockByCopyDecls.end(); I != E; ++I) {
3452 std::string Name = (*I)->getNameAsString();
3453 if (firsTime) {
3454 Constructor += " : ";
3455 firsTime = false;
3456 }
3457 else
3458 Constructor += ", ";
3459 if (isTopLevelBlockPointerType((*I)->getType()))
3460 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3461 else
3462 Constructor += Name + "(_" + Name + ")";
3463 }
3464 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003465 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003466 E = BlockByRefDecls.end(); I != E; ++I) {
3467 std::string Name = (*I)->getNameAsString();
3468 if (firsTime) {
3469 Constructor += " : ";
3470 firsTime = false;
3471 }
3472 else
3473 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003474 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003475 }
3476
3477 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003478 if (GlobalVarDecl)
3479 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3480 else
3481 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003482 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003483
Steve Naroff30484702009-12-06 21:14:13 +00003484 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003485 } else {
3486 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003487 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003488 if (GlobalVarDecl)
3489 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3490 else
3491 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003492 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3493 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003494 }
3495 Constructor += " ";
3496 Constructor += "}\n";
3497 S += Constructor;
3498 S += "};\n";
3499 return S;
3500}
3501
Steve Naroff30484702009-12-06 21:14:13 +00003502std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3503 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003504 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003505 unsigned hasCopy) {
3506 std::string S = "\nstatic struct " + DescTag;
3507
3508 S += " {\n unsigned long reserved;\n";
3509 S += " unsigned long Block_size;\n";
3510 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003511 S += " void (*copy)(struct ";
3512 S += ImplTag; S += "*, struct ";
3513 S += ImplTag; S += "*);\n";
3514
3515 S += " void (*dispose)(struct ";
3516 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003517 }
3518 S += "} ";
3519
3520 S += DescTag + "_DATA = { 0, sizeof(struct ";
3521 S += ImplTag + ")";
3522 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003523 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3524 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003525 }
3526 S += "};\n";
3527 return S;
3528}
3529
Steve Naroff677ab3a2008-10-27 17:20:55 +00003530void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003531 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003532 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003533 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003534 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003535 bool RewriteSC = (GlobalVarDecl &&
3536 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003537 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003538 GlobalVarDecl->getType().getCVRQualifiers());
3539 if (RewriteSC) {
3540 std::string SC(" void __");
3541 SC += GlobalVarDecl->getNameAsString();
3542 SC += "() {}";
3543 InsertText(FunLocStart, SC);
3544 }
3545
Steve Naroff677ab3a2008-10-27 17:20:55 +00003546 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003547 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3548 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003549 // Need to copy-in the inner copied-in variables not actually used in this
3550 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003551 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003552 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003553 ValueDecl *VD = Exp->getDecl();
3554 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003555 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003556 BlockByCopyDeclsPtrSet.insert(VD);
3557 BlockByCopyDecls.push_back(VD);
3558 }
John McCall113bee02012-03-10 09:33:50 +00003559 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003560 BlockByRefDeclsPtrSet.insert(VD);
3561 BlockByRefDecls.push_back(VD);
3562 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003563 // imported objects in the inner blocks not used in the outer
3564 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003565 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003566 VD->getType()->isObjCObjectPointerType() ||
3567 VD->getType()->isBlockPointerType())
3568 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003569 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003570
Daniel Dunbar56df9772010-08-17 22:39:59 +00003571 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3572 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003573
Steve Naroff30484702009-12-06 21:14:13 +00003574 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003575
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003576 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003577
Steve Naroff30484702009-12-06 21:14:13 +00003578 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003580 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003581
3582 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003583 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003584 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003585 }
Steve Naroff30484702009-12-06 21:14:13 +00003586 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3587 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003588 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Steve Naroff677ab3a2008-10-27 17:20:55 +00003590 BlockDeclRefs.clear();
3591 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003592 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003593 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003594 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003595 ImportedBlockDecls.clear();
3596 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003597 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003598 // Must insert any 'const/volatile/static here. Since it has been
3599 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003600 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003601 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003602 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003603 if (GlobalVarDecl->getType().isConstQualified())
3604 SC += "const ";
3605 if (GlobalVarDecl->getType().isVolatileQualified())
3606 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003607 if (GlobalVarDecl->getType().isRestrictQualified())
3608 SC += "restrict ";
3609 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003610 }
3611
Steve Naroff677ab3a2008-10-27 17:20:55 +00003612 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003613 InnerDeclRefsCount.clear();
3614 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003615 RewrittenBlockExprs.clear();
3616}
3617
3618void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3619 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003620 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003621
Steve Naroff677ab3a2008-10-27 17:20:55 +00003622 SynthesizeBlockLiterals(FunLocStart, FuncName);
3623}
3624
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003625static void BuildUniqueMethodName(std::string &Name,
3626 ObjCMethodDecl *MD) {
3627 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003628 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003629 Name += "__" + MD->getSelector().getAsString();
3630 // Convert colons to underscores.
3631 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00003632 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003633 Name.replace(loc, 1, "_");
3634}
3635
Steve Naroff677ab3a2008-10-27 17:20:55 +00003636void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003637 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3638 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003639 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003640 std::string FuncName;
3641 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003642 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003643}
3644
3645void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003646 for (Stmt *SubStmt : S->children())
3647 if (SubStmt) {
3648 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003649 GetBlockDeclRefExprs(CBE->getBody());
3650 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003651 GetBlockDeclRefExprs(SubStmt);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003652 }
3653 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003654 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003655 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003656 HasLocalVariableExternalStorage(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003657 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003658 BlockDeclRefs.push_back(DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003659}
3660
Craig Topper5603df42013-07-05 19:34:19 +00003661void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3662 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00003663 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003664 for (Stmt *SubStmt : S->children())
3665 if (SubStmt) {
3666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003667 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003668 GetInnerBlockDeclRefExprs(CBE->getBody(),
3669 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003670 InnerContexts);
3671 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003672 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003673 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003674 }
3675 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003676 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003677 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003678 HasLocalVariableExternalStorage(DRE->getDecl())) {
3679 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00003680 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00003681 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003682 if (Var->isFunctionOrMethodVarDecl())
3683 ImportedLocalExternalDecls.insert(Var);
3684 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003685 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003686}
3687
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003688/// convertFunctionTypeOfBlocks - This routine converts a function type
3689/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003690/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003691/// all block pointers to function pointers.
3692QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3693 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3694 // FTP will be null for closures that don't take arguments.
3695 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003696 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003697 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003698 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003699
3700 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003701 for (auto &I : FTP->param_types()) {
3702 QualType t = I;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003703 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003704 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003705 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003706 ArgTypes.push_back(t);
3707 }
3708 }
3709 QualType FuncType;
3710 // FIXME. Does this work if block takes no argument but has a return type
3711 // which is of block type?
3712 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003713 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003714 else FuncType = QualType(FT, 0);
3715 return FuncType;
3716}
3717
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003718Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003719 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00003720 const BlockPointerType *CPT = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003721
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003722 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003723 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003724 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003725 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003726 }
3727 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3728 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3729 }
3730 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3731 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3732 else if (const ConditionalOperator *CEXPR =
3733 dyn_cast<ConditionalOperator>(BlockExp)) {
3734 Expr *LHSExp = CEXPR->getLHS();
3735 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3736 Expr *RHSExp = CEXPR->getRHS();
3737 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3738 Expr *CONDExp = CEXPR->getCond();
3739 ConditionalOperator *CondExpr =
3740 new (Context) ConditionalOperator(CONDExp,
3741 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003742 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003743 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003744 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003745 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3746 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003747 } else if (const PseudoObjectExpr *POE
3748 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3749 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003750 } else {
Craig Topper0da20762016-04-24 02:08:22 +00003751 assert(false && "RewriteBlockClass: Bad type");
Steve Naroff677ab3a2008-10-27 17:20:55 +00003752 }
3753 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003754 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003755 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003756 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003757 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003758
Abramo Bagnara6150c882010-05-11 21:36:43 +00003759 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003760 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003761 &Context->Idents.get("__block_impl"));
3762 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003763
Steve Naroff350b6652008-10-30 10:07:53 +00003764 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003765 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003766
Steve Naroff350b6652008-10-30 10:07:53 +00003767 // Push the block argument type.
3768 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003770 for (auto &I : FTP->param_types()) {
3771 QualType t = I;
Steve Naroff350b6652008-10-30 10:07:53 +00003772 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003773 if (!convertBlockPointerToFunctionPointer(t))
3774 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003775 ArgTypes.push_back(t);
3776 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003777 }
Steve Naroff350b6652008-10-30 10:07:53 +00003778 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003779 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003780
Steve Naroff350b6652008-10-30 10:07:53 +00003781 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003782
John McCall97513962010-01-15 18:39:57 +00003783 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003784 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003785 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003786 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003787 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3788 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003789 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003790
Craig Topper8ae12032014-05-07 06:21:57 +00003791 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003792 SourceLocation(),
3793 &Context->Idents.get("FuncPtr"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003794 Context->VoidPtrTy, nullptr,
3795 /*BitWidth=*/nullptr, /*Mutable=*/true,
3796 ICIS_NoInit);
3797 MemberExpr *ME =
3798 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
3799 FD->getType(), VK_LValue, OK_Ordinary);
3800
3801 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3802 CK_BitCast, ME);
3803 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003804
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003805 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003806 // Add the implicit argument.
3807 BlkExprs.push_back(BlkCast);
3808 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003809 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003810 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003811 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003813 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003814 Exp->getType(), VK_RValue,
3815 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003816 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817}
3818
Steve Naroffd9803712009-04-29 16:37:50 +00003819// We need to return the rewritten expression to handle cases where the
3820// BlockDeclRefExpr is embedded in another expression being rewritten.
3821// For example:
3822//
3823// int main() {
3824// __block Foo *f;
3825// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003826//
Steve Naroffd9803712009-04-29 16:37:50 +00003827// void (^myblock)() = ^() {
3828// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3829// i = 77;
3830// };
3831//}
John McCall113bee02012-03-10 09:33:50 +00003832Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003833 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003834 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003835 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003836 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003837 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00003838
3839 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003840 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003841 &Context->Idents.get("__forwarding"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003842 Context->VoidPtrTy, nullptr,
3843 /*BitWidth=*/nullptr, /*Mutable=*/true,
3844 ICIS_NoInit);
3845 MemberExpr *ME = new (Context)
3846 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
3847 FD->getType(), VK_LValue, OK_Ordinary);
3848
3849 StringRef Name = VD->getName();
3850 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003851 &Context->Idents.get(Name),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003852 Context->VoidPtrTy, nullptr,
3853 /*BitWidth=*/nullptr, /*Mutable=*/true,
3854 ICIS_NoInit);
3855 ME =
3856 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
3857 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3858
3859 // Need parens to enforce precedence.
3860 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3861 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003862 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003863 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003864 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865}
3866
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003867// Rewrites the imported local variable V with external storage
3868// (static, extern, etc.) as *V
3869//
3870Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3871 ValueDecl *VD = DRE->getDecl();
3872 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3873 if (!ImportedLocalExternalDecls.count(Var))
3874 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003875 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3876 VK_LValue, OK_Ordinary,
3877 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003878 // Need parens to enforce precedence.
3879 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3880 Exp);
3881 ReplaceStmt(DRE, PE);
3882 return PE;
3883}
3884
Steve Naroffc989a7b2008-11-03 23:29:32 +00003885void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3886 SourceLocation LocStart = CE->getLParenLoc();
3887 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003888
3889 // Need to avoid trying to rewrite synthesized casts.
3890 if (LocStart.isInvalid())
3891 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003892 // Need to avoid trying to rewrite casts contained in macros.
3893 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3894 return;
Mike Stump11289f42009-09-09 15:08:12 +00003895
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 const char *startBuf = SM->getCharacterData(LocStart);
3897 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003898 QualType QT = CE->getType();
3899 const Type* TypePtr = QT->getAs<Type>();
3900 if (isa<TypeOfExprType>(TypePtr)) {
3901 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3902 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3903 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003904 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003905 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003906 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003907 return;
3908 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003909 // advance the location to startArgList.
3910 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003911
Steve Naroff677ab3a2008-10-27 17:20:55 +00003912 while (*argPtr++ && (argPtr < endBuf)) {
3913 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003914 case '^':
3915 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003916 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003917 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003918 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003919 }
3920 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003921}
3922
3923void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3924 SourceLocation DeclLoc = FD->getLocation();
3925 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003926
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927 // We have 1 or more arguments that have closure pointers.
3928 const char *startBuf = SM->getCharacterData(DeclLoc);
3929 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003930
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003932
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 parenCount++;
3934 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003935 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003936 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00003937
Steve Naroff677ab3a2008-10-27 17:20:55 +00003938 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00003939
Steve Naroff677ab3a2008-10-27 17:20:55 +00003940 while (*argPtr++ && parenCount) {
3941 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003942 case '^':
3943 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003944 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003945 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003946 break;
3947 case '(':
3948 parenCount++;
3949 break;
3950 case ')':
3951 parenCount--;
3952 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003953 }
3954 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003955}
3956
3957bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003958 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003959 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003960 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00003961 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003962 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003963 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003964 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00003965 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 }
3967 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003968 for (const auto &I : FTP->param_types())
3969 if (isTopLevelBlockPointerType(I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003970 return true;
3971 }
3972 return false;
3973}
3974
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003975bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3976 const FunctionProtoType *FTP;
3977 const PointerType *PT = QT->getAs<PointerType>();
3978 if (PT) {
3979 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3980 } else {
3981 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3982 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3983 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3984 }
3985 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003986 for (const auto &I : FTP->param_types()) {
3987 if (I->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003988 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003989 if (I->isObjCObjectPointerType() &&
3990 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian733dde62010-11-03 23:50:34 +00003991 return true;
3992 }
3993
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003994 }
3995 return false;
3996}
3997
Ted Kremenek5a201952009-02-07 01:47:29 +00003998void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3999 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 const char *argPtr = strchr(Name, '(');
4001 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004002
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 LParen = argPtr; // output the start.
4004 argPtr++; // skip past the left paren.
4005 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004006
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 while (*argPtr && parenCount) {
4008 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004009 case '(': parenCount++; break;
4010 case ')': parenCount--; break;
4011 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004012 }
4013 if (parenCount) argPtr++;
4014 }
4015 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4016 RParen = argPtr; // output the end
4017}
4018
4019void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4021 RewriteBlockPointerFunctionArgs(FD);
4022 return;
Mike Stump11289f42009-09-09 15:08:12 +00004023 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004024 // Handle Variables and Typedefs.
4025 SourceLocation DeclLoc = ND->getLocation();
4026 QualType DeclT;
4027 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4028 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004029 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 DeclT = TDD->getUnderlyingType();
4031 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4032 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004033 else
David Blaikie83d382b2011-09-23 05:06:16 +00004034 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004035
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 const char *startBuf = SM->getCharacterData(DeclLoc);
4037 const char *endBuf = startBuf;
4038 // scan backward (from the decl location) for the end of the previous decl.
4039 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4040 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004041 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004042 std::string buf;
4043 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004044 // *startBuf != '^' if we are dealing with a pointer to function that
4045 // may take block argument types (which will be handled below).
4046 if (*startBuf == '^') {
4047 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004048 buf = '*';
4049 startBuf++;
4050 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004051 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004052 while (*startBuf != ')') {
4053 buf += *startBuf;
4054 startBuf++;
4055 OrigLength++;
4056 }
4057 buf += ')';
4058 OrigLength++;
4059
4060 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4061 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004063 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004064 DeclLoc = ND->getLocation();
4065 startBuf = SM->getCharacterData(DeclLoc);
4066 const char *argListBegin, *argListEnd;
4067 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4068 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004069 if (*argListBegin == '^')
4070 buf += '*';
4071 else if (*argListBegin == '<') {
4072 buf += "/*";
4073 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004074 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004075 while (*argListBegin != '>') {
4076 buf += *argListBegin++;
4077 OrigLength++;
4078 }
4079 buf += *argListBegin;
4080 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004081 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004082 else
4083 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004084 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004085 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004087 buf += ')';
4088 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004089 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004090 ReplaceText(Start, OrigLength, buf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004091}
4092
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004093/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4094/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4095/// struct Block_byref_id_object *src) {
4096/// _Block_object_assign (&_dest->object, _src->object,
4097/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4098/// [|BLOCK_FIELD_IS_WEAK]) // object
4099/// _Block_object_assign(&_dest->object, _src->object,
4100/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4101/// [|BLOCK_FIELD_IS_WEAK]) // block
4102/// }
4103/// And:
4104/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4105/// _Block_object_dispose(_src->object,
4106/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4107/// [|BLOCK_FIELD_IS_WEAK]) // object
4108/// _Block_object_dispose(_src->object,
4109/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4110/// [|BLOCK_FIELD_IS_WEAK]) // block
4111/// }
4112
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004113std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4114 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004115 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004116 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004117 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004118 CopyDestroyCache.insert(flag);
4119 S = "static void __Block_byref_id_object_copy_";
4120 S += utostr(flag);
4121 S += "(void *dst, void *src) {\n";
4122
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004123 // offset into the object pointer is computed as:
4124 // void * + void* + int + int + void* + void *
4125 unsigned IntSize =
4126 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4127 unsigned VoidPtrSize =
4128 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4129
Ken Dyckd9c83e62011-04-30 16:08:27 +00004130 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004131 S += " _Block_object_assign((char*)dst + ";
4132 S += utostr(offset);
4133 S += ", *(void * *) ((char*)src + ";
4134 S += utostr(offset);
4135 S += "), ";
4136 S += utostr(flag);
4137 S += ");\n}\n";
4138
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004139 S += "static void __Block_byref_id_object_dispose_";
4140 S += utostr(flag);
4141 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004142 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4143 S += utostr(offset);
4144 S += "), ";
4145 S += utostr(flag);
4146 S += ");\n}\n";
4147 return S;
4148}
4149
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004150/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4151/// the declaration into:
4152/// struct __Block_byref_ND {
4153/// void *__isa; // NULL for everything except __weak pointers
4154/// struct __Block_byref_ND *__forwarding;
4155/// int32_t __flags;
4156/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004157/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4158/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004159/// typex ND;
4160/// };
4161///
4162/// It then replaces declaration of ND variable with:
4163/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4164/// __size=sizeof(struct __Block_byref_ND),
4165/// ND=initializer-if-any};
4166///
4167///
4168void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004169 // Insert declaration for the function in which block literal is
4170 // used.
4171 if (CurFunctionDeclToDeclareForBlock)
4172 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004173 int flag = 0;
4174 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004175 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004176 if (DeclLoc.isInvalid())
4177 // If type location is missing, it is because of missing type (a warning).
4178 // Use variable's location which is good for this case.
4179 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004180 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004181 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004182 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004183 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004184 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004185 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004186 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004187 ByrefType += " {\n";
4188 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004189 RewriteByRefString(ByrefType, Name, ND);
4190 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004191 ByrefType += " int __flags;\n";
4192 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004193 // Add void *__Block_byref_id_object_copy;
4194 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004195 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004196 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004197 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004198 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4199 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004200 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004201
4202 QualType T = Ty;
4203 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004204 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004205
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004206 ByrefType += " " + Name + ";\n";
4207 ByrefType += "};\n";
4208 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004209 SourceLocation FunLocStart;
4210 if (CurFunctionDef)
4211 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4212 else {
4213 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4214 FunLocStart = CurMethodDef->getLocStart();
4215 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004216 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004217 if (Ty.isObjCGCWeak()) {
4218 flag |= BLOCK_FIELD_IS_WEAK;
4219 isa = 1;
4220 }
4221
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004222 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004223 flag = BLOCK_BYREF_CALLER;
4224 QualType Ty = ND->getType();
4225 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4226 if (Ty->isBlockPointerType())
4227 flag |= BLOCK_FIELD_IS_BLOCK;
4228 else
4229 flag |= BLOCK_FIELD_IS_OBJECT;
4230 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004231 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004232 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004233 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004234
4235 // struct __Block_byref_ND ND =
4236 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4237 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00004238 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004239 unsigned flags = 0;
4240 if (HasCopyAndDispose)
4241 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004242 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004243 ByrefType.clear();
4244 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004245 std::string ForwardingCastType("(");
4246 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004247 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004248 ByrefType += " " + Name + " = {(void*)";
4249 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004250 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004251 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004252 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004253 ByrefType += "sizeof(";
4254 RewriteByRefString(ByrefType, Name, ND);
4255 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004256 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004257 ByrefType += ", __Block_byref_id_object_copy_";
4258 ByrefType += utostr(flag);
4259 ByrefType += ", __Block_byref_id_object_dispose_";
4260 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004261 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004262 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004263 unsigned nameSize = Name.size();
4264 // for block or function pointer declaration. Name is aleady
4265 // part of the declaration.
4266 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4267 nameSize = 1;
4268 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004269 }
4270 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004271 SourceLocation startLoc;
4272 Expr *E = ND->getInit();
4273 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4274 startLoc = ECE->getLParenLoc();
4275 else
4276 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004277 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004278 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004279 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004280 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004281 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004282 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004283 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004284 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004285 ByrefType += "sizeof(";
4286 RewriteByRefString(ByrefType, Name, ND);
4287 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004288 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004289 ByrefType += "__Block_byref_id_object_copy_";
4290 ByrefType += utostr(flag);
4291 ByrefType += ", __Block_byref_id_object_dispose_";
4292 ByrefType += utostr(flag);
4293 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004294 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004295 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004296
4297 // Complete the newly synthesized compound expression by inserting a right
4298 // curly brace before the end of the declaration.
4299 // FIXME: This approach avoids rewriting the initializer expression. It
4300 // also assumes there is only one declarator. For example, the following
4301 // isn't currently supported by this routine (in general):
4302 //
4303 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4304 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004305 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4306 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004307 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4308 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004309 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004310
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004311 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004312 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004313}
4314
Mike Stump11289f42009-09-09 15:08:12 +00004315void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 // Add initializers for any closure decl refs.
4317 GetBlockDeclRefExprs(Exp->getBody());
4318 if (BlockDeclRefs.size()) {
4319 // Unique all "by copy" declarations.
4320 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004321 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004322 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4323 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4324 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4325 }
4326 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004327 // Unique all "by ref" declarations.
4328 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004329 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004330 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4331 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4332 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4333 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004334 }
4335 // Find any imported blocks...they will need special attention.
4336 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004337 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004338 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004339 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004340 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004341 }
4342}
4343
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004344FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004345 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004346 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004347 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00004348 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004349 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004350}
4351
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004352Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004353 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004354 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004355 Blocks.push_back(Exp);
4356
4357 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004358
4359 // Add inner imported variables now used in current block.
4360 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004361 if (!InnerBlockDeclRefs.empty()) {
4362 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004363 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004364 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004365 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004366 // We need to save the copied-in variables in nested
4367 // blocks because it is needed at the end for some of the API generations.
4368 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004369 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4370 BlockDeclRefs.push_back(Exp);
4371 BlockByCopyDeclsPtrSet.insert(VD);
4372 BlockByCopyDecls.push_back(VD);
4373 }
John McCall113bee02012-03-10 09:33:50 +00004374 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004375 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4376 BlockDeclRefs.push_back(Exp);
4377 BlockByRefDeclsPtrSet.insert(VD);
4378 BlockByRefDecls.push_back(VD);
4379 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004380 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004381 // Find any imported blocks...they will need special attention.
4382 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004383 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004384 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4385 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4386 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004387 }
4388 InnerDeclRefsCount.push_back(countOfInnerDecls);
4389
Steve Narofff4b992a2008-10-28 20:29:00 +00004390 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004391
Steve Narofff4b992a2008-10-28 20:29:00 +00004392 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004393 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004394 else if (CurMethodDef)
4395 BuildUniqueMethodName(FuncName, CurMethodDef);
4396 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004397 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004398
Steve Narofff4b992a2008-10-28 20:29:00 +00004399 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004400
Steve Narofff4b992a2008-10-28 20:29:00 +00004401 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4402 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Steve Narofff4b992a2008-10-28 20:29:00 +00004404 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004405 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4406 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004407
4408 FunctionDecl *FD;
4409 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Benjamin Kramer60509af2013-09-09 14:48:42 +00004411 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004412 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004413 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004414 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004415
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004416 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004417
Steve Naroffe2514232008-10-29 21:23:59 +00004418 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004419 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004420 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4421 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004422 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004423 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004424 InitExprs.push_back(castExpr);
4425
Steve Naroff30484702009-12-06 21:14:13 +00004426 // Initialize the block descriptor.
4427 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004428
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004429 VarDecl *NewVD = VarDecl::Create(
4430 *Context, TUDecl, SourceLocation(), SourceLocation(),
4431 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004432 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004433 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004434 Context->VoidPtrTy,
4435 VK_LValue,
4436 SourceLocation()),
4437 UO_AddrOf,
4438 Context->getPointerType(Context->VoidPtrTy),
4439 VK_RValue, OK_Ordinary,
4440 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004441 InitExprs.push_back(DescRefExpr);
4442
Steve Narofff4b992a2008-10-28 20:29:00 +00004443 // Add initializers for any closure decl refs.
4444 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004445 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004446 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004447 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004448 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004449 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004450 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004451 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004452 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004453 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004454 if (HasLocalVariableExternalStorage(*I)) {
4455 QualType QT = (*I)->getType();
4456 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004457 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4458 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004459 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004460 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004461 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004462 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004463 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004464 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004465 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004466 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004467 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004468 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004469 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004470 if (HasLocalVariableExternalStorage(*I)) {
4471 QualType QT = (*I)->getType();
4472 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004473 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4474 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004475 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004476 }
Mike Stump11289f42009-09-09 15:08:12 +00004477 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004478 }
4479 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004480 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004481 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004482 ValueDecl *ND = (*I);
4483 std::string Name(ND->getNameAsString());
4484 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004485 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004486 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4487 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004488 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004489 SourceLocation(), SourceLocation(),
4490 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004491 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4492 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4493
Daniel Dunbar56df9772010-08-17 22:39:59 +00004494 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004495 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004496 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004497 bool isNestedCapturedVar = false;
4498 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00004499 for (const auto &CI : block->captures()) {
4500 const VarDecl *variable = CI.getVariable();
4501 if (variable == ND && CI.isNested()) {
4502 assert (CI.isByRef() &&
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004503 "SynthBlockInitExpr - captured block variable is not byref");
4504 isNestedCapturedVar = true;
4505 break;
4506 }
4507 }
4508 // captured nested byref variable has its address passed. Do not take
4509 // its address again.
4510 if (!isNestedCapturedVar)
4511 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004512 Context->getPointerType(Exp->getType()),
4513 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004514 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004515 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004516 }
4517 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004518 if (ImportedBlockDecls.size()) {
4519 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4520 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004521 unsigned IntSize =
4522 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004523 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4524 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004525 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004526 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004527 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004528 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004529 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004530 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004531 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004532 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004533 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004534 BlockDeclRefs.clear();
4535 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004536 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004537 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004538 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004539 ImportedBlockDecls.clear();
4540 return NewRep;
4541}
4542
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004543bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4544 if (const ObjCForCollectionStmt * CS =
4545 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4546 return CS->getElement() == DS;
4547 return false;
4548}
4549
Steve Narofff4b992a2008-10-28 20:29:00 +00004550//===----------------------------------------------------------------------===//
4551// Function Body / Expression rewriting
4552//===----------------------------------------------------------------------===//
4553
4554Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004555 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004556 isa<DoStmt>(S) || isa<ForStmt>(S))
4557 Stmts.push_back(S);
4558 else if (isa<ObjCForCollectionStmt>(S)) {
4559 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004560 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004561 }
Mike Stump11289f42009-09-09 15:08:12 +00004562
John McCallfe96e0b2011-11-06 09:01:30 +00004563 // Pseudo-object operations and ivar references need special
4564 // treatment because we're going to recursively rewrite them.
4565 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4566 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4567 return RewritePropertyOrImplicitSetter(PseudoOp);
4568 } else {
4569 return RewritePropertyOrImplicitGetter(PseudoOp);
4570 }
4571 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4572 return RewriteObjCIvarRefExpr(IvarRefExpr);
4573 }
4574
Steve Narofff4b992a2008-10-28 20:29:00 +00004575 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004576
Steve Narofff4b992a2008-10-28 20:29:00 +00004577 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00004578 for (Stmt *&childStmt : S->children())
4579 if (childStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004580 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004581 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004582 childStmt = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004583 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004584 }
Mike Stump11289f42009-09-09 15:08:12 +00004585
Steve Narofff4b992a2008-10-28 20:29:00 +00004586 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004587 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004588 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4589 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004590 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004591 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004592 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004593 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004594 Stmt *SaveCurrentBody = CurrentBody;
4595 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00004596 PropParentMap = nullptr;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004597 // block literal on rhs of a property-dot-sytax assignment
4598 // must be replaced by its synthesize ast so getRewrittenText
4599 // works as expected. In this case, what actually ends up on RHS
4600 // is the blockTranscribed which is the helper function for the
4601 // block literal; as in: self.c = ^() {[ace ARR];};
4602 bool saveDisableReplaceStmt = DisableReplaceStmt;
4603 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004604 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004605 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004606 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00004607 PropParentMap = nullptr;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004608 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004609 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004610 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004611 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004612
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004613 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4614
Steve Narofff4b992a2008-10-28 20:29:00 +00004615 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004616 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004617 return blockTranscribed;
4618 }
4619 // Handle specific things.
4620 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4621 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004622
Steve Narofff4b992a2008-10-28 20:29:00 +00004623 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4624 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004625
Steve Narofff4b992a2008-10-28 20:29:00 +00004626 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4627 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004628
Steve Narofff4b992a2008-10-28 20:29:00 +00004629 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004630#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004631 // Before we rewrite it, put the original message expression in a comment.
4632 SourceLocation startLoc = MessExpr->getLocStart();
4633 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004634
Steve Narofff4b992a2008-10-28 20:29:00 +00004635 const char *startBuf = SM->getCharacterData(startLoc);
4636 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004637
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 std::string messString;
4639 messString += "// ";
4640 messString.append(startBuf, endBuf-startBuf+1);
4641 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004642
4643 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004644 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004645 // InsertText(startLoc, messString);
Steve Narofff4b992a2008-10-28 20:29:00 +00004646 // Tried this, but it didn't work either...
4647 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004648#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004649 return RewriteMessageExpr(MessExpr);
4650 }
Mike Stump11289f42009-09-09 15:08:12 +00004651
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4653 return RewriteObjCTryStmt(StmtTry);
4654
4655 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4656 return RewriteObjCSynchronizedStmt(StmtTry);
4657
4658 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4659 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004660
Steve Narofff4b992a2008-10-28 20:29:00 +00004661 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4662 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004663
4664 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004665 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004666 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004667 OrigStmtRange.getEnd());
4668 if (BreakStmt *StmtBreakStmt =
4669 dyn_cast<BreakStmt>(S))
4670 return RewriteBreakStmt(StmtBreakStmt);
4671 if (ContinueStmt *StmtContinueStmt =
4672 dyn_cast<ContinueStmt>(S))
4673 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004674
4675 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004676 // and cast exprs.
4677 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4678 // FIXME: What we're doing here is modifying the type-specifier that
4679 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004680 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004681 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4682 // the context of an ObjCForCollectionStmt. For example:
4683 // NSArray *someArray;
4684 // for (id <FooProtocol> index in someArray) ;
4685 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4686 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004687 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004688 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004689
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Blocks rewrite rules.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004691 for (auto *SD : DS->decls()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004693 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004695 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004696 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004697 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004698 if (VD->hasAttr<BlocksAttr>()) {
4699 static unsigned uniqueByrefDeclCount = 0;
4700 assert(!BlockByRefDeclNo.count(ND) &&
4701 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4702 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004703 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004704 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004705 else
4706 RewriteTypeOfDecl(VD);
4707 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004708 }
Richard Smithdda56e42011-04-15 14:24:37 +00004709 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004710 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004711 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004712 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004713 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4714 }
4715 }
4716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
Steve Narofff4b992a2008-10-28 20:29:00 +00004718 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4719 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004720
4721 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004722 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4723 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004724 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4725 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004726 && "Statement stack mismatch");
4727 Stmts.pop_back();
4728 }
4729 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004730 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4731 ValueDecl *VD = DRE->getDecl();
4732 if (VD->hasAttr<BlocksAttr>())
4733 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004734 if (HasLocalVariableExternalStorage(VD))
4735 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004736 }
4737
Steve Narofff4b992a2008-10-28 20:29:00 +00004738 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004739 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004740 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004741 ReplaceStmt(S, BlockCall);
4742 return BlockCall;
4743 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004744 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004745 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004746 RewriteCastExpr(CE);
4747 }
4748#if 0
4749 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004750 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4751 ICE->getSubExpr(),
4752 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004753 // Get the new text.
4754 std::string SStr;
4755 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004756 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 const std::string &Str = Buf.str();
4758
4759 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004760 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Steve Narofff4b992a2008-10-28 20:29:00 +00004761 delete S;
4762 return Replacement;
4763 }
4764#endif
4765 // Return this stmt unmodified.
4766 return S;
4767}
4768
Steve Naroffe70a52a2009-12-05 15:55:59 +00004769void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004770 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004771 if (isTopLevelBlockPointerType(FD->getType()))
4772 RewriteBlockPointerDecl(FD);
4773 if (FD->getType()->isObjCQualifiedIdType() ||
4774 FD->getType()->isObjCQualifiedInterfaceType())
4775 RewriteObjCQualifiedInterfaceTypes(FD);
4776 }
4777}
4778
Steve Narofff4b992a2008-10-28 20:29:00 +00004779/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4780/// main file of the input.
4781void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004782 switch (D->getKind()) {
4783 case Decl::Function: {
4784 FunctionDecl *FD = cast<FunctionDecl>(D);
4785 if (FD->isOverloadedOperator())
4786 return;
Mike Stump11289f42009-09-09 15:08:12 +00004787
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004788 // Since function prototypes don't have ParmDecl's, we check the function
4789 // prototype. This enables us to rewrite function declarations and
4790 // definitions using the same code.
4791 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004792
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004793 if (!FD->isThisDeclarationADefinition())
4794 break;
4795
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004796 // FIXME: If this should support Obj-C++, support CXXTryStmt
4797 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4798 CurFunctionDef = FD;
4799 CurFunctionDeclToDeclareForBlock = FD;
4800 CurrentBody = Body;
4801 Body =
4802 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4803 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004804 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004805 if (PropParentMap) {
4806 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004807 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004808 }
4809 // This synthesizes and inserts the block "impl" struct, invoke function,
4810 // and any copy/dispose helper functions.
4811 InsertBlockLiteralsWithinFunction(FD);
Craig Topper8ae12032014-05-07 06:21:57 +00004812 CurFunctionDef = nullptr;
4813 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004814 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004815 break;
Mike Stump11289f42009-09-09 15:08:12 +00004816 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004817 case Decl::ObjCMethod: {
4818 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4819 if (CompoundStmt *Body = MD->getCompoundBody()) {
4820 CurMethodDef = MD;
4821 CurrentBody = Body;
4822 Body =
4823 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4824 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004825 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004826 if (PropParentMap) {
4827 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004828 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004829 }
4830 InsertBlockLiteralsWithinMethod(MD);
Craig Topper8ae12032014-05-07 06:21:57 +00004831 CurMethodDef = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004832 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004833 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004835 case Decl::ObjCImplementation: {
4836 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4837 ClassImplementation.push_back(CI);
4838 break;
4839 }
4840 case Decl::ObjCCategoryImpl: {
4841 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4842 CategoryImplementation.push_back(CI);
4843 break;
4844 }
4845 case Decl::Var: {
4846 VarDecl *VD = cast<VarDecl>(D);
4847 RewriteObjCQualifiedInterfaceTypes(VD);
4848 if (isTopLevelBlockPointerType(VD->getType()))
4849 RewriteBlockPointerDecl(VD);
4850 else if (VD->getType()->isFunctionPointerType()) {
4851 CheckFunctionPointerDecl(VD->getType(), VD);
4852 if (VD->getInit()) {
4853 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4854 RewriteCastExpr(CE);
4855 }
4856 }
4857 } else if (VD->getType()->isRecordType()) {
4858 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4859 if (RD->isCompleteDefinition())
4860 RewriteRecordBody(RD);
4861 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004863 GlobalVarDecl = VD;
4864 CurrentBody = VD->getInit();
4865 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00004866 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004867 if (PropParentMap) {
4868 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004869 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004870 }
4871 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00004872 GlobalVarDecl = nullptr;
4873
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004874 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004875 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004876 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004877 }
4878 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004879 break;
4880 }
4881 case Decl::TypeAlias:
4882 case Decl::Typedef: {
4883 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4884 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4885 RewriteBlockPointerDecl(TD);
4886 else if (TD->getUnderlyingType()->isFunctionPointerType())
4887 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4888 }
4889 break;
4890 }
4891 case Decl::CXXRecord:
4892 case Decl::Record: {
4893 RecordDecl *RD = cast<RecordDecl>(D);
4894 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004895 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004896 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004897 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004898 default:
4899 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 }
4901 // Nothing yet.
4902}
4903
Chris Lattnercf169832009-03-28 04:11:33 +00004904void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 if (Diags.hasErrorOccurred())
4906 return;
Mike Stump11289f42009-09-09 15:08:12 +00004907
Steve Narofff4b992a2008-10-28 20:29:00 +00004908 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004909
Steve Naroffd9803712009-04-29 16:37:50 +00004910 // Here's a great place to add any extra declarations that may be needed.
4911 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00004912 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4913 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
Steve Naroffd9803712009-04-29 16:37:50 +00004914
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004915 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004916 if (ClassImplementation.size() || CategoryImplementation.size())
4917 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004918
Steve Narofff4b992a2008-10-28 20:29:00 +00004919 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4920 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004921 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 Rewrite.getRewriteBufferFor(MainFileID)) {
4923 //printf("Changed:\n");
4924 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4925 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004926 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00004927 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004928
Steve Naroffd9803712009-04-29 16:37:50 +00004929 if (ClassImplementation.size() || CategoryImplementation.size() ||
4930 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004931 // Rewrite Objective-c meta data*
4932 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00004933 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004934 // Emit metadata.
4935 *OutFile << ResultStr;
4936 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004937 OutFile->flush();
4938}
Fariborz Jahanian83077422011-12-08 18:25:15 +00004939
4940void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4941 InitializeCommon(context);
4942
4943 // declaring objc_selector outside the parameter list removes a silly
4944 // scope related warning...
4945 if (IsHeader)
4946 Preamble = "#pragma once\n";
4947 Preamble += "struct objc_selector; struct objc_class;\n";
4948 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4949 Preamble += "struct objc_object *superClass; ";
4950 if (LangOpts.MicrosoftExt) {
4951 // Add a constructor for creating temporary objects.
4952 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4953 ": ";
4954 Preamble += "object(o), superClass(s) {} ";
4955 }
4956 Preamble += "};\n";
4957 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4958 Preamble += "typedef struct objc_object Protocol;\n";
4959 Preamble += "#define _REWRITER_typedef_Protocol\n";
4960 Preamble += "#endif\n";
4961 if (LangOpts.MicrosoftExt) {
4962 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4963 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4964 } else
4965 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4966 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4967 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4968 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4969 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4970 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4971 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4972 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4973 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4974 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4975 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4976 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4977 Preamble += "(const char *);\n";
4978 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4979 Preamble += "(struct objc_class *);\n";
4980 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4981 Preamble += "(const char *);\n";
4982 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4983 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4984 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4985 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4986 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4987 Preamble += "(struct objc_class *, struct objc_object *);\n";
4988 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00004989 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4990 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00004991 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4992 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4993 Preamble += "struct __objcFastEnumerationState {\n\t";
4994 Preamble += "unsigned long state;\n\t";
4995 Preamble += "void **itemsPtr;\n\t";
4996 Preamble += "unsigned long *mutationsPtr;\n\t";
4997 Preamble += "unsigned long extra[5];\n};\n";
4998 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
4999 Preamble += "#define __FASTENUMERATIONSTATE\n";
5000 Preamble += "#endif\n";
5001 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5002 Preamble += "struct __NSConstantStringImpl {\n";
5003 Preamble += " int *isa;\n";
5004 Preamble += " int flags;\n";
5005 Preamble += " char *str;\n";
5006 Preamble += " long length;\n";
5007 Preamble += "};\n";
5008 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5009 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5010 Preamble += "#else\n";
5011 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5012 Preamble += "#endif\n";
5013 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5014 Preamble += "#endif\n";
5015 // Blocks preamble.
5016 Preamble += "#ifndef BLOCK_IMPL\n";
5017 Preamble += "#define BLOCK_IMPL\n";
5018 Preamble += "struct __block_impl {\n";
5019 Preamble += " void *isa;\n";
5020 Preamble += " int Flags;\n";
5021 Preamble += " int Reserved;\n";
5022 Preamble += " void *FuncPtr;\n";
5023 Preamble += "};\n";
5024 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5025 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5026 Preamble += "extern \"C\" __declspec(dllexport) "
5027 "void _Block_object_assign(void *, const void *, const int);\n";
5028 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5029 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5030 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5031 Preamble += "#else\n";
5032 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5034 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5036 Preamble += "#endif\n";
5037 Preamble += "#endif\n";
5038 if (LangOpts.MicrosoftExt) {
5039 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5040 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5041 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5042 Preamble += "#define __attribute__(X)\n";
5043 Preamble += "#endif\n";
5044 Preamble += "#define __weak\n";
5045 }
5046 else {
5047 Preamble += "#define __block\n";
5048 Preamble += "#define __weak\n";
5049 }
5050 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5051 // as this avoids warning in any 64bit/32bit compilation model.
5052 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5053}
5054
5055/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5056/// ivar offset.
5057void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5058 std::string &Result) {
5059 if (ivar->isBitField()) {
5060 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5061 // place all bitfields at offset 0.
5062 Result += "0";
5063 } else {
5064 Result += "__OFFSETOFIVAR__(struct ";
5065 Result += ivar->getContainingInterface()->getNameAsString();
5066 if (LangOpts.MicrosoftExt)
5067 Result += "_IMPL";
5068 Result += ", ";
5069 Result += ivar->getNameAsString();
5070 Result += ")";
5071 }
5072}
5073
5074/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5075void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5076 ObjCProtocolDecl *PDecl, StringRef prefix,
5077 StringRef ClassName, std::string &Result) {
5078 static bool objc_protocol_methods = false;
5079
5080 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005081 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005082 /* struct protocol_methods {
5083 SEL _cmd;
5084 char *method_types;
5085 }
5086 */
5087 Result += "\nstruct _protocol_methods {\n";
5088 Result += "\tstruct objc_selector *_cmd;\n";
5089 Result += "\tchar *method_types;\n";
5090 Result += "};\n";
5091
5092 objc_protocol_methods = true;
5093 }
5094 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005095 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005096 return;
5097
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005098 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5099 PDecl = Def;
5100
Fariborz Jahanian83077422011-12-08 18:25:15 +00005101 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5102 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5103 PDecl->instmeth_end());
5104 /* struct _objc_protocol_method_list {
5105 int protocol_method_count;
5106 struct protocol_methods protocols[];
5107 }
5108 */
5109 Result += "\nstatic struct {\n";
5110 Result += "\tint protocol_method_count;\n";
5111 Result += "\tstruct _protocol_methods protocol_methods[";
5112 Result += utostr(NumMethods);
5113 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5114 Result += PDecl->getNameAsString();
5115 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5116 "{\n\t" + utostr(NumMethods) + "\n";
5117
5118 // Output instance methods declared in this protocol.
5119 for (ObjCProtocolDecl::instmeth_iterator
5120 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5121 I != E; ++I) {
5122 if (I == PDecl->instmeth_begin())
5123 Result += "\t ,{{(struct objc_selector *)\"";
5124 else
5125 Result += "\t ,{(struct objc_selector *)\"";
5126 Result += (*I)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005127 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005128 Result += "\", \"";
5129 Result += MethodTypeString;
5130 Result += "\"}\n";
5131 }
5132 Result += "\t }\n};\n";
5133 }
5134
5135 // Output class methods declared in this protocol.
5136 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5137 PDecl->classmeth_end());
5138 if (NumMethods > 0) {
5139 /* struct _objc_protocol_method_list {
5140 int protocol_method_count;
5141 struct protocol_methods protocols[];
5142 }
5143 */
5144 Result += "\nstatic struct {\n";
5145 Result += "\tint protocol_method_count;\n";
5146 Result += "\tstruct _protocol_methods protocol_methods[";
5147 Result += utostr(NumMethods);
5148 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5149 Result += PDecl->getNameAsString();
5150 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5151 "{\n\t";
5152 Result += utostr(NumMethods);
5153 Result += "\n";
5154
5155 // Output instance methods declared in this protocol.
5156 for (ObjCProtocolDecl::classmeth_iterator
5157 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5158 I != E; ++I) {
5159 if (I == PDecl->classmeth_begin())
5160 Result += "\t ,{{(struct objc_selector *)\"";
5161 else
5162 Result += "\t ,{(struct objc_selector *)\"";
5163 Result += (*I)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005164 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005165 Result += "\", \"";
5166 Result += MethodTypeString;
5167 Result += "\"}\n";
5168 }
5169 Result += "\t }\n};\n";
5170 }
5171
5172 // Output:
5173 /* struct _objc_protocol {
5174 // Objective-C 1.0 extensions
5175 struct _objc_protocol_extension *isa;
5176 char *protocol_name;
5177 struct _objc_protocol **protocol_list;
5178 struct _objc_protocol_method_list *instance_methods;
5179 struct _objc_protocol_method_list *class_methods;
5180 };
5181 */
5182 static bool objc_protocol = false;
5183 if (!objc_protocol) {
5184 Result += "\nstruct _objc_protocol {\n";
5185 Result += "\tstruct _objc_protocol_extension *isa;\n";
5186 Result += "\tchar *protocol_name;\n";
5187 Result += "\tstruct _objc_protocol **protocol_list;\n";
5188 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5189 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5190 Result += "};\n";
5191
5192 objc_protocol = true;
5193 }
5194
5195 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5196 Result += PDecl->getNameAsString();
5197 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5198 "{\n\t0, \"";
5199 Result += PDecl->getNameAsString();
5200 Result += "\", 0, ";
5201 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5202 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5203 Result += PDecl->getNameAsString();
5204 Result += ", ";
5205 }
5206 else
5207 Result += "0, ";
5208 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5209 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5210 Result += PDecl->getNameAsString();
5211 Result += "\n";
5212 }
5213 else
5214 Result += "0\n";
5215 Result += "};\n";
5216
5217 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00005218 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005219 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian83077422011-12-08 18:25:15 +00005220}
5221
5222void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5223 const ObjCList<ObjCProtocolDecl> &Protocols,
5224 StringRef prefix, StringRef ClassName,
5225 std::string &Result) {
5226 if (Protocols.empty()) return;
5227
5228 for (unsigned i = 0; i != Protocols.size(); i++)
5229 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5230
5231 // Output the top lovel protocol meta-data for the class.
5232 /* struct _objc_protocol_list {
5233 struct _objc_protocol_list *next;
5234 int protocol_count;
5235 struct _objc_protocol *class_protocols[];
5236 }
5237 */
5238 Result += "\nstatic struct {\n";
5239 Result += "\tstruct _objc_protocol_list *next;\n";
5240 Result += "\tint protocol_count;\n";
5241 Result += "\tstruct _objc_protocol *class_protocols[";
5242 Result += utostr(Protocols.size());
5243 Result += "];\n} _OBJC_";
5244 Result += prefix;
5245 Result += "_PROTOCOLS_";
5246 Result += ClassName;
5247 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5248 "{\n\t0, ";
5249 Result += utostr(Protocols.size());
5250 Result += "\n";
5251
5252 Result += "\t,{&_OBJC_PROTOCOL_";
5253 Result += Protocols[0]->getNameAsString();
5254 Result += " \n";
5255
5256 for (unsigned i = 1; i != Protocols.size(); i++) {
5257 Result += "\t ,&_OBJC_PROTOCOL_";
5258 Result += Protocols[i]->getNameAsString();
5259 Result += "\n";
5260 }
5261 Result += "\t }\n};\n";
5262}
5263
5264void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5265 std::string &Result) {
5266 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5267
5268 // Explicitly declared @interface's are already synthesized.
5269 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005270 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005271 // produce correct synthesis as yet.
5272 RewriteObjCInternalStruct(CDecl, Result);
5273 }
5274
5275 // Build _objc_ivar_list metadata for classes ivars if needed
5276 unsigned NumIvars = !IDecl->ivar_empty()
5277 ? IDecl->ivar_size()
5278 : (CDecl ? CDecl->ivar_size() : 0);
5279 if (NumIvars > 0) {
5280 static bool objc_ivar = false;
5281 if (!objc_ivar) {
5282 /* struct _objc_ivar {
5283 char *ivar_name;
5284 char *ivar_type;
5285 int ivar_offset;
5286 };
5287 */
5288 Result += "\nstruct _objc_ivar {\n";
5289 Result += "\tchar *ivar_name;\n";
5290 Result += "\tchar *ivar_type;\n";
5291 Result += "\tint ivar_offset;\n";
5292 Result += "};\n";
5293
5294 objc_ivar = true;
5295 }
5296
5297 /* struct {
5298 int ivar_count;
5299 struct _objc_ivar ivar_list[nIvars];
5300 };
5301 */
5302 Result += "\nstatic struct {\n";
5303 Result += "\tint ivar_count;\n";
5304 Result += "\tstruct _objc_ivar ivar_list[";
5305 Result += utostr(NumIvars);
5306 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5307 Result += IDecl->getNameAsString();
5308 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5309 "{\n\t";
5310 Result += utostr(NumIvars);
5311 Result += "\n";
5312
5313 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5314 SmallVector<ObjCIvarDecl *, 8> IVars;
5315 if (!IDecl->ivar_empty()) {
Aaron Ballmand6d25de2014-03-14 15:16:45 +00005316 for (auto *IV : IDecl->ivars())
5317 IVars.push_back(IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005318 IVI = IDecl->ivar_begin();
5319 IVE = IDecl->ivar_end();
5320 } else {
5321 IVI = CDecl->ivar_begin();
5322 IVE = CDecl->ivar_end();
5323 }
5324 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005325 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005326 Result += "\", \"";
5327 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005328 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005329 QuoteDoublequotes(TmpString, StrEncoding);
5330 Result += StrEncoding;
5331 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005332 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005333 Result += "}\n";
5334 for (++IVI; IVI != IVE; ++IVI) {
5335 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005336 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005337 Result += "\", \"";
5338 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005339 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005340 QuoteDoublequotes(TmpString, StrEncoding);
5341 Result += StrEncoding;
5342 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005343 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005344 Result += "}\n";
5345 }
5346
5347 Result += "\t }\n};\n";
5348 }
5349
5350 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005351 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005352
5353 // If any of our property implementations have associated getters or
5354 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005355 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005356 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005357 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005358 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005359 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005360 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005361 if (!PD)
5362 continue;
5363 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5364 if (!Getter->isDefined())
5365 InstanceMethods.push_back(Getter);
5366 if (PD->isReadOnly())
5367 continue;
5368 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5369 if (!Setter->isDefined())
5370 InstanceMethods.push_back(Setter);
5371 }
5372 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5373 true, "", IDecl->getName(), Result);
5374
5375 // Build _objc_method_list for class's class methods if needed
5376 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5377 false, "", IDecl->getName(), Result);
5378
5379 // Protocols referenced in class declaration?
5380 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5381 "CLASS", CDecl->getName(), Result);
5382
5383 // Declaration of class/meta-class metadata
5384 /* struct _objc_class {
5385 struct _objc_class *isa; // or const char *root_class_name when metadata
5386 const char *super_class_name;
5387 char *name;
5388 long version;
5389 long info;
5390 long instance_size;
5391 struct _objc_ivar_list *ivars;
5392 struct _objc_method_list *methods;
5393 struct objc_cache *cache;
5394 struct objc_protocol_list *protocols;
5395 const char *ivar_layout;
5396 struct _objc_class_ext *ext;
5397 };
5398 */
5399 static bool objc_class = false;
5400 if (!objc_class) {
5401 Result += "\nstruct _objc_class {\n";
5402 Result += "\tstruct _objc_class *isa;\n";
5403 Result += "\tconst char *super_class_name;\n";
5404 Result += "\tchar *name;\n";
5405 Result += "\tlong version;\n";
5406 Result += "\tlong info;\n";
5407 Result += "\tlong instance_size;\n";
5408 Result += "\tstruct _objc_ivar_list *ivars;\n";
5409 Result += "\tstruct _objc_method_list *methods;\n";
5410 Result += "\tstruct objc_cache *cache;\n";
5411 Result += "\tstruct _objc_protocol_list *protocols;\n";
5412 Result += "\tconst char *ivar_layout;\n";
5413 Result += "\tstruct _objc_class_ext *ext;\n";
5414 Result += "};\n";
5415 objc_class = true;
5416 }
5417
5418 // Meta-class metadata generation.
Craig Topper8ae12032014-05-07 06:21:57 +00005419 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005420 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5421 while (SuperClass) {
5422 RootClass = SuperClass;
5423 SuperClass = SuperClass->getSuperClass();
5424 }
5425 SuperClass = CDecl->getSuperClass();
5426
5427 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5428 Result += CDecl->getNameAsString();
5429 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5430 "{\n\t(struct _objc_class *)\"";
5431 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5432 Result += "\"";
5433
5434 if (SuperClass) {
5435 Result += ", \"";
5436 Result += SuperClass->getNameAsString();
5437 Result += "\", \"";
5438 Result += CDecl->getNameAsString();
5439 Result += "\"";
5440 }
5441 else {
5442 Result += ", 0, \"";
5443 Result += CDecl->getNameAsString();
5444 Result += "\"";
5445 }
5446 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5447 // 'info' field is initialized to CLS_META(2) for metaclass
5448 Result += ", 0,2, sizeof(struct _objc_class), 0";
5449 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5450 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5451 Result += IDecl->getNameAsString();
5452 Result += "\n";
5453 }
5454 else
5455 Result += ", 0\n";
5456 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5457 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5458 Result += CDecl->getNameAsString();
5459 Result += ",0,0\n";
5460 }
5461 else
5462 Result += "\t,0,0,0,0\n";
5463 Result += "};\n";
5464
5465 // class metadata generation.
5466 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5467 Result += CDecl->getNameAsString();
5468 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5469 "{\n\t&_OBJC_METACLASS_";
5470 Result += CDecl->getNameAsString();
5471 if (SuperClass) {
5472 Result += ", \"";
5473 Result += SuperClass->getNameAsString();
5474 Result += "\", \"";
5475 Result += CDecl->getNameAsString();
5476 Result += "\"";
5477 }
5478 else {
5479 Result += ", 0, \"";
5480 Result += CDecl->getNameAsString();
5481 Result += "\"";
5482 }
5483 // 'info' field is initialized to CLS_CLASS(1) for class
5484 Result += ", 0,1";
5485 if (!ObjCSynthesizedStructs.count(CDecl))
5486 Result += ",0";
5487 else {
5488 // class has size. Must synthesize its size.
5489 Result += ",sizeof(struct ";
5490 Result += CDecl->getNameAsString();
5491 if (LangOpts.MicrosoftExt)
5492 Result += "_IMPL";
5493 Result += ")";
5494 }
5495 if (NumIvars > 0) {
5496 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5497 Result += CDecl->getNameAsString();
5498 Result += "\n\t";
5499 }
5500 else
5501 Result += ",0";
5502 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5503 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5504 Result += CDecl->getNameAsString();
5505 Result += ", 0\n\t";
5506 }
5507 else
5508 Result += ",0,0";
5509 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5510 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5511 Result += CDecl->getNameAsString();
5512 Result += ", 0,0\n";
5513 }
5514 else
5515 Result += ",0,0,0\n";
5516 Result += "};\n";
5517}
5518
5519void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5520 int ClsDefCount = ClassImplementation.size();
5521 int CatDefCount = CategoryImplementation.size();
5522
5523 // For each implemented class, write out all its meta data.
5524 for (int i = 0; i < ClsDefCount; i++)
5525 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5526
5527 // For each implemented category, write out all its meta data.
5528 for (int i = 0; i < CatDefCount; i++)
5529 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5530
5531 // Write objc_symtab metadata
5532 /*
5533 struct _objc_symtab
5534 {
5535 long sel_ref_cnt;
5536 SEL *refs;
5537 short cls_def_cnt;
5538 short cat_def_cnt;
5539 void *defs[cls_def_cnt + cat_def_cnt];
5540 };
5541 */
5542
5543 Result += "\nstruct _objc_symtab {\n";
5544 Result += "\tlong sel_ref_cnt;\n";
5545 Result += "\tSEL *refs;\n";
5546 Result += "\tshort cls_def_cnt;\n";
5547 Result += "\tshort cat_def_cnt;\n";
5548 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5549 Result += "};\n\n";
5550
5551 Result += "static struct _objc_symtab "
5552 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5553 Result += "\t0, 0, " + utostr(ClsDefCount)
5554 + ", " + utostr(CatDefCount) + "\n";
5555 for (int i = 0; i < ClsDefCount; i++) {
5556 Result += "\t,&_OBJC_CLASS_";
5557 Result += ClassImplementation[i]->getNameAsString();
5558 Result += "\n";
5559 }
5560
5561 for (int i = 0; i < CatDefCount; i++) {
5562 Result += "\t,&_OBJC_CATEGORY_";
5563 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5564 Result += "_";
5565 Result += CategoryImplementation[i]->getNameAsString();
5566 Result += "\n";
5567 }
5568
5569 Result += "};\n\n";
5570
5571 // Write objc_module metadata
5572
5573 /*
5574 struct _objc_module {
5575 long version;
5576 long size;
5577 const char *name;
5578 struct _objc_symtab *symtab;
5579 }
5580 */
5581
5582 Result += "\nstruct _objc_module {\n";
5583 Result += "\tlong version;\n";
5584 Result += "\tlong size;\n";
5585 Result += "\tconst char *name;\n";
5586 Result += "\tstruct _objc_symtab *symtab;\n";
5587 Result += "};\n\n";
5588 Result += "static struct _objc_module "
5589 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5590 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5591 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5592 Result += "};\n\n";
5593
5594 if (LangOpts.MicrosoftExt) {
5595 if (ProtocolExprDecls.size()) {
5596 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5597 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Craig Topperc6914d02014-08-25 04:15:02 +00005598 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005599 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005600 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005601 Result += " = &_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005602 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005603 Result += ";\n";
5604 }
5605 Result += "#pragma data_seg(pop)\n\n";
5606 }
5607 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5608 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5609 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5610 Result += "&_OBJC_MODULES;\n";
5611 Result += "#pragma data_seg(pop)\n\n";
5612 }
5613}
5614
5615/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5616/// implementation.
5617void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5618 std::string &Result) {
5619 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5620 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005621 ObjCCategoryDecl *CDecl
5622 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005623
5624 std::string FullCategoryName = ClassDecl->getNameAsString();
5625 FullCategoryName += '_';
5626 FullCategoryName += IDecl->getNameAsString();
5627
5628 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005629 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005630
5631 // If any of our property implementations have associated getters or
5632 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005633 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005634 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005635 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005636 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005637 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005638 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005639 if (!PD)
5640 continue;
5641 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5642 InstanceMethods.push_back(Getter);
5643 if (PD->isReadOnly())
5644 continue;
5645 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5646 InstanceMethods.push_back(Setter);
5647 }
5648 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005649 true, "CATEGORY_", FullCategoryName, Result);
5650
Fariborz Jahanian83077422011-12-08 18:25:15 +00005651 // Build _objc_method_list for class's class methods if needed
5652 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005653 false, "CATEGORY_", FullCategoryName, Result);
5654
Fariborz Jahanian83077422011-12-08 18:25:15 +00005655 // Protocols referenced in class declaration?
5656 // Null CDecl is case of a category implementation with no category interface
5657 if (CDecl)
5658 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5659 FullCategoryName, Result);
5660 /* struct _objc_category {
5661 char *category_name;
5662 char *class_name;
5663 struct _objc_method_list *instance_methods;
5664 struct _objc_method_list *class_methods;
5665 struct _objc_protocol_list *protocols;
5666 // Objective-C 1.0 extensions
5667 uint32_t size; // sizeof (struct _objc_category)
5668 struct _objc_property_list *instance_properties; // category's own
5669 // @property decl.
5670 };
5671 */
5672
5673 static bool objc_category = false;
5674 if (!objc_category) {
5675 Result += "\nstruct _objc_category {\n";
5676 Result += "\tchar *category_name;\n";
5677 Result += "\tchar *class_name;\n";
5678 Result += "\tstruct _objc_method_list *instance_methods;\n";
5679 Result += "\tstruct _objc_method_list *class_methods;\n";
5680 Result += "\tstruct _objc_protocol_list *protocols;\n";
5681 Result += "\tunsigned int size;\n";
5682 Result += "\tstruct _objc_property_list *instance_properties;\n";
5683 Result += "};\n";
5684 objc_category = true;
5685 }
5686 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5687 Result += FullCategoryName;
5688 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5689 Result += IDecl->getNameAsString();
5690 Result += "\"\n\t, \"";
5691 Result += ClassDecl->getNameAsString();
5692 Result += "\"\n";
5693
5694 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5695 Result += "\t, (struct _objc_method_list *)"
5696 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5697 Result += FullCategoryName;
5698 Result += "\n";
5699 }
5700 else
5701 Result += "\t, 0\n";
5702 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5703 Result += "\t, (struct _objc_method_list *)"
5704 "&_OBJC_CATEGORY_CLASS_METHODS_";
5705 Result += FullCategoryName;
5706 Result += "\n";
5707 }
5708 else
5709 Result += "\t, 0\n";
5710
5711 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5712 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5713 Result += FullCategoryName;
5714 Result += "\n";
5715 }
5716 else
5717 Result += "\t, 0\n";
5718 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5719}
5720
5721// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5722/// class methods.
5723template<typename MethodIterator>
5724void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5725 MethodIterator MethodEnd,
5726 bool IsInstanceMethod,
5727 StringRef prefix,
5728 StringRef ClassName,
5729 std::string &Result) {
5730 if (MethodBegin == MethodEnd) return;
5731
5732 if (!objc_impl_method) {
5733 /* struct _objc_method {
5734 SEL _cmd;
5735 char *method_types;
5736 void *_imp;
5737 }
5738 */
5739 Result += "\nstruct _objc_method {\n";
5740 Result += "\tSEL _cmd;\n";
5741 Result += "\tchar *method_types;\n";
5742 Result += "\tvoid *_imp;\n";
5743 Result += "};\n";
5744
5745 objc_impl_method = true;
5746 }
5747
5748 // Build _objc_method_list for class's methods if needed
5749
5750 /* struct {
5751 struct _objc_method_list *next_method;
5752 int method_count;
5753 struct _objc_method method_list[];
5754 }
5755 */
5756 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5757 Result += "\nstatic struct {\n";
5758 Result += "\tstruct _objc_method_list *next_method;\n";
5759 Result += "\tint method_count;\n";
5760 Result += "\tstruct _objc_method method_list[";
5761 Result += utostr(NumMethods);
5762 Result += "];\n} _OBJC_";
5763 Result += prefix;
5764 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5765 Result += "_METHODS_";
5766 Result += ClassName;
5767 Result += " __attribute__ ((used, section (\"__OBJC, __";
5768 Result += IsInstanceMethod ? "inst" : "cls";
5769 Result += "_meth\")))= ";
5770 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5771
5772 Result += "\t,{{(SEL)\"";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005773 Result += (*MethodBegin)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005774 std::string MethodTypeString =
5775 Context->getObjCEncodingForMethodDecl(*MethodBegin);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005776 Result += "\", \"";
5777 Result += MethodTypeString;
5778 Result += "\", (void *)";
5779 Result += MethodInternalNames[*MethodBegin];
5780 Result += "}\n";
5781 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5782 Result += "\t ,{(SEL)\"";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005783 Result += (*MethodBegin)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005784 std::string MethodTypeString =
5785 Context->getObjCEncodingForMethodDecl(*MethodBegin);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005786 Result += "\", \"";
5787 Result += MethodTypeString;
5788 Result += "\", (void *)";
5789 Result += MethodInternalNames[*MethodBegin];
5790 Result += "}\n";
5791 }
5792 Result += "\t }\n};\n";
5793}
5794
5795Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5796 SourceRange OldRange = IV->getSourceRange();
5797 Expr *BaseExpr = IV->getBase();
5798
5799 // Rewrite the base, but without actually doing replaces.
5800 {
5801 DisableReplaceStmtScope S(*this);
5802 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5803 IV->setBase(BaseExpr);
5804 }
5805
5806 ObjCIvarDecl *D = IV->getDecl();
5807
5808 Expr *Replacement = IV;
5809 if (CurMethodDef) {
5810 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5811 const ObjCInterfaceType *iFaceDecl =
5812 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5813 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5814 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005815 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005816 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5817 clsDeclared);
5818 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5819
5820 // Synthesize an explicit cast to gain access to the ivar.
5821 std::string RecName = clsDeclared->getIdentifier()->getName();
5822 RecName += "_IMPL";
5823 IdentifierInfo *II = &Context->Idents.get(RecName);
5824 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5825 SourceLocation(), SourceLocation(),
5826 II);
5827 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5828 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5829 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5830 CK_BitCast,
5831 IV->getBase());
5832 // Don't forget the parens to enforce the proper binding.
5833 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5834 OldRange.getEnd(),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00005835 castExpr);
5836 if (IV->isFreeIvar() &&
5837 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5838 MemberExpr *ME = new (Context)
5839 MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(),
5840 D->getType(), VK_LValue, OK_Ordinary);
5841 Replacement = ME;
5842 } else {
5843 IV->setBase(PE);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005844 }
5845 }
5846 } else { // we are outside a method.
5847 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5848
5849 // Explicit ivar refs need to have a cast inserted.
5850 // FIXME: consider sharing some of this code with the code above.
5851 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5852 const ObjCInterfaceType *iFaceDecl =
5853 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5854 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005855 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005856 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5857 clsDeclared);
5858 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5859
5860 // Synthesize an explicit cast to gain access to the ivar.
5861 std::string RecName = clsDeclared->getIdentifier()->getName();
5862 RecName += "_IMPL";
5863 IdentifierInfo *II = &Context->Idents.get(RecName);
5864 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5865 SourceLocation(), SourceLocation(),
5866 II);
5867 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5868 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5869 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5870 CK_BitCast,
5871 IV->getBase());
5872 // Don't forget the parens to enforce the proper binding.
5873 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5874 IV->getBase()->getLocEnd(), castExpr);
5875 // Cannot delete IV->getBase(), since PE points to it.
5876 // Replace the old base with the cast. This is important when doing
5877 // embedded rewrites. For example, [newInv->_container addObject:0].
5878 IV->setBase(PE);
5879 }
5880 }
5881
5882 ReplaceStmtWithRange(IV, Replacement, OldRange);
5883 return Replacement;
5884}
Alp Toker0621cb22014-07-16 16:48:33 +00005885
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005886#endif // CLANG_ENABLE_OBJC_REWRITER