blob: 9938f89eb869294d90e3c100d8c3acff9ca75f5d [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"
NAKAMURA Takumi7f633df2017-07-18 08:55:03 +000023#include "clang/Config/config.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000032
NAKAMURA Takumid9739822017-10-18 05:21:17 +000033#if CLANG_ENABLE_OBJC_REWRITER
Alp Toker0621cb22014-07-16 16:48:33 +000034
Chris Lattnere99c8322007-10-11 00:43:27 +000035using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000036using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000037
Chris Lattnere99c8322007-10-11 00:43:27 +000038namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian83077422011-12-08 18:25:15 +000040 protected:
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000041 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000042 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000043 block, ... */
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
46 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000047 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000048 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000049 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000050 support routines */
51 BLOCK_BYREF_CURRENT_MAX = 256
52 };
53
54 enum {
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
61 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000062 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000063
Chris Lattner0bd1c972007-10-16 21:07:07 +000064 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000065 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000066 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000067 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000068 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000069 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000070 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000071 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000072 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000074 std::string InFileName;
Peter Collingbourne03f89072016-07-15 00:55:40 +000075 std::unique_ptr<raw_ostream> OutFile;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000076 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000085
Fariborz Jahanian8efef602011-12-05 19:50:04 +000086 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
Fariborz Jahanian83077422011-12-08 18:25:15 +000089 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000090 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000109 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000120
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000127
John McCall113bee02012-03-10 09:33:50 +0000128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff22216db2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000145
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000146 // Needed for header files being rewritten
147 bool IsHeader;
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
150
Steve Naroff08628db2008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000152 class DisableReplaceStmtScope {
153 RewriteObjC &R;
154 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000155
John McCallfe96e0b2011-11-06 09:01:30 +0000156 public:
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
160 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000161
John McCallfe96e0b2011-11-06 09:01:30 +0000162 ~DisableReplaceStmtScope() {
163 R.DisableReplaceStmt = SavedValue;
164 }
165 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000166
Fariborz Jahanian83077422011-12-08 18:25:15 +0000167 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chris Lattnere99c8322007-10-11 00:43:27 +0000169 public:
Chris Lattner3c799d72007-10-24 17:06:59 +0000170 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000171 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000172 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000173 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
174 if (!Class->isThisDeclarationADefinition()) {
175 RewriteForwardClassDecl(D);
176 break;
177 }
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000178 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000179
Douglas Gregorf6102672012-01-01 21:23:57 +0000180 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
181 if (!Proto->isThisDeclarationADefinition()) {
182 RewriteForwardProtocolDecl(D);
183 break;
184 }
185 }
186
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000187 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000188 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000189 return true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000192 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000193 void HandleDeclInMainFile(Decl *D);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000194 RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000195 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000196 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000197
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000198 ~RewriteObjC() override {}
Mike Stump11289f42009-09-09 15:08:12 +0000199
Craig Topperfb6b25b2014-03-15 04:29:04 +0000200 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000202 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000203 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Chris Lattner2e0d2602008-01-31 19:37:57 +0000204 }
Steve Naroff08628db2008-12-09 12:56:34 +0000205
206 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000207 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000208
209 Stmt *ReplacingStmt = ReplacedNodes[Old];
210 if (ReplacingStmt)
211 return; // We can't rewrite the same node twice.
212
John McCallfe96e0b2011-11-06 09:01:30 +0000213 if (DisableReplaceStmt)
214 return;
215
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000216 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000217 int Size = Rewrite.getRangeSize(SrcRange);
218 if (Size == -1) {
219 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
220 << Old->getSourceRange();
221 return;
222 }
223 // Get the new text.
224 std::string SStr;
225 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000226 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000227 const std::string &Str = S.str();
228
229 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000230 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000231 ReplacedNodes[Old] = New;
232 return;
233 }
234 if (SilenceRewriteMacroWarning)
235 return;
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 }
239
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000240 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000241 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000243 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner1780a852008-01-31 19:42:41 +0000247 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattner9cc55f52008-01-31 19:51:04 +0000250 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000251 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000252 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000253 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000254 SilenceRewriteMacroWarning)
255 return;
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattner9cc55f52008-01-31 19:51:04 +0000257 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
258 }
Mike Stump11289f42009-09-09 15:08:12 +0000259
Chris Lattner3c799d72007-10-24 17:06:59 +0000260 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000261 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000262 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000263 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000264 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000265 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000266 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000267 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000268 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
269 ObjCImplementationDecl *IMD,
270 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000271 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000272 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000273 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
274 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000275 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
276 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000277 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000278 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000279 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
280 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000281 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000282 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000283 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000284 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000285 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000286 void RewriteBlockPointerType(std::string& Str, QualType Type);
287 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000288 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000289 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000290 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000291 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000292
Chris Lattner3c799d72007-10-24 17:06:59 +0000293 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000294 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000295 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000296 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
297 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000298 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000299 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000300 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000301 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000302 void RewriteTryReturnStmts(Stmt *S);
303 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000304 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000305 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000306 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000307 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
308 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000311 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000312
Steve Naroff677ab3a2008-10-27 17:20:55 +0000313 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000314 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000315
Mike Stump11289f42009-09-09 15:08:12 +0000316 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000317 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000318 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000319 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000320 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000321 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000322
323 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
324 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000325
David Blaikie1cbb9712014-11-14 19:09:44 +0000326 void Initialize(ASTContext &context) override = 0;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000327
Fariborz Jahanian83077422011-12-08 18:25:15 +0000328 // Metadata Rewriting.
329 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
330 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
331 StringRef prefix,
332 StringRef ClassName,
333 std::string &Result) = 0;
334 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
335 std::string &Result) = 0;
336 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
337 StringRef prefix,
338 StringRef ClassName,
339 std::string &Result) = 0;
340 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
341 std::string &Result) = 0;
342
343 // Rewriting ivar access
344 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
345 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
346 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000347
Benjamin Kramer474261a2012-06-02 10:20:41 +0000348 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000349 // rewriting routines on the new ASTs.
350 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000351 ArrayRef<Expr *> Args,
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000352 SourceLocation StartLoc=SourceLocation(),
353 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000354 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
355 QualType msgSendType,
356 QualType returnType,
357 SmallVectorImpl<QualType> &ArgTypes,
358 SmallVectorImpl<Expr*> &MsgExprs,
359 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000360 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 void SynthCountByEnumWithState(std::string &buf);
365 void SynthMsgSendFunctionDecl();
366 void SynthMsgSendSuperFunctionDecl();
367 void SynthMsgSendStretFunctionDecl();
368 void SynthMsgSendFpretFunctionDecl();
369 void SynthMsgSendSuperStretFunctionDecl();
370 void SynthGetClassFunctionDecl();
371 void SynthGetMetaClassFunctionDecl();
372 void SynthGetSuperClassFunctionDecl();
373 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000374 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000375
376 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000377 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000378 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000379 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000380 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000381 std::string SynthesizeBlockImpl(BlockExpr *CE,
382 std::string Tag, std::string Desc);
383 std::string SynthesizeBlockDescriptor(std::string DescTag,
384 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000385 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000386 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000387 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000390 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
391 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000392 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000393
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000394 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000395 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000396 void WarnAboutReturnGotoStmts(Stmt *S);
397 void HasReturnStmts(Stmt *S, bool &hasReturns);
398 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
399 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
400 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
401
402 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000404 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000405 void GetInnerBlockDeclRefExprs(Stmt *S,
406 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000407 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000408
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409 // We avoid calling Type::isBlockPointerType(), since it operates on the
410 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000411 bool isTopLevelBlockPointerType(QualType T) {
412 return isa<BlockPointerType>(T);
413 }
Mike Stump11289f42009-09-09 15:08:12 +0000414
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000415 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
416 /// to a function pointer type and upon success, returns true; false
417 /// otherwise.
418 bool convertBlockPointerToFunctionPointer(QualType &T) {
419 if (isTopLevelBlockPointerType(T)) {
420 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
421 T = Context->getPointerType(BPT->getPointeeType());
422 return true;
423 }
424 return false;
425 }
426
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000427 bool needToScanForQualifiers(QualType T);
428 QualType getSuperStructType();
429 QualType getConstantStringStructType();
430 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
431 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
432
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000433 void convertToUnqualifiedObjCType(QualType &T) {
434 if (T->isObjCQualifiedIdType())
435 T = Context->getObjCIdType();
436 else if (T->isObjCQualifiedClassType())
437 T = Context->getObjCClassType();
438 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000439 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
440 if (const ObjCObjectPointerType * OBJPT =
441 T->getAsObjCInterfacePointerType()) {
442 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
443 T = QualType(IFaceT, 0);
444 T = Context->getPointerType(T);
445 }
446 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000447 }
448
Steve Naroff677ab3a2008-10-27 17:20:55 +0000449 // FIXME: This predicate seems like it would be useful to add to ASTContext.
450 bool isObjCType(QualType T) {
451 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
452 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000453
Steve Naroff677ab3a2008-10-27 17:20:55 +0000454 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000455
Steve Naroff677ab3a2008-10-27 17:20:55 +0000456 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
457 OCT == Context->getCanonicalType(Context->getObjCClassType()))
458 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000460 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000461 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000462 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000463 return true;
464 }
465 return false;
466 }
467 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000468 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000469 void GetExtentOfArgList(const char *Name, const char *&LParen,
470 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000471
Steve Naroffd9803712009-04-29 16:37:50 +0000472 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000473 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000474 if (From[i] == '"')
475 To += "\\\"";
476 else
477 To += From[i];
478 }
479 }
John McCalldb40c7f2010-12-14 08:05:40 +0000480
481 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000482 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000483 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000488 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000489 }
John McCall97513962010-01-15 18:39:57 +0000490
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
496 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000497 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000498
499 StringLiteral *getStringLiteral(StringRef Str) {
500 QualType StrType = Context->getConstantArrayType(
501 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
502 0);
503 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
504 /*Pascal=*/false, StrType, SourceLocation());
505 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000506 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000507
508 class RewriteObjCFragileABI : public RewriteObjC {
509 public:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000510 RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
511 DiagnosticsEngine &D, const LangOptions &LOpts,
512 bool silenceMacroWarn)
513 : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000514
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000515 ~RewriteObjCFragileABI() override {}
David Blaikie1cbb9712014-11-14 19:09:44 +0000516 void Initialize(ASTContext &context) override;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000517
Fariborz Jahanian83077422011-12-08 18:25:15 +0000518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000526 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix, StringRef ClassName,
528 std::string &Result) override;
529 void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result) override;
532 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result) override;
534 void RewriteMetaDataIntoBuffer(std::string &Result) override;
535 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result) override;
537
Fariborz Jahanian83077422011-12-08 18:25:15 +0000538 // Rewriting ivar
Craig Topperfb6b25b2014-03-15 04:29:04 +0000539 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result) override;
541 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahanian83077422011-12-08 18:25:15 +0000542 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000543} // end anonymous namespace
Chris Lattnere99c8322007-10-11 00:43:27 +0000544
Mike Stump11289f42009-09-09 15:08:12 +0000545void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000547 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000549 for (const auto &I : fproto->param_types())
550 if (isTopLevelBlockPointerType(I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000551 // All the args are checked/rewritten. Don't call twice!
552 RewriteBlockPointerDecl(D);
553 break;
554 }
555 }
556}
557
558void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000559 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000561 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562}
563
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000564static bool IsHeaderFile(const std::string &Filename) {
565 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000566
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000567 if (DotPos == std::string::npos) {
568 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000569 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000570 }
Mike Stump11289f42009-09-09 15:08:12 +0000571
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
573 // C header: .h
574 // C++ header: .hh or .H;
575 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000576}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000577
Peter Collingbourne03f89072016-07-15 00:55:40 +0000578RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000579 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000580 bool silenceMacroWarn)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000583 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000584 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000585 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000590}
591
David Blaikie6beb6aa2014-08-10 19:56:51 +0000592std::unique_ptr<ASTConsumer>
Peter Collingbourne03f89072016-07-15 00:55:40 +0000593clang::CreateObjCRewriter(const std::string &InFile,
594 std::unique_ptr<raw_ostream> OS,
David Blaikie6beb6aa2014-08-10 19:56:51 +0000595 DiagnosticsEngine &Diags, const LangOptions &LOpts,
596 bool SilenceRewriteMacroWarning) {
Peter Collingbourne03f89072016-07-15 00:55:40 +0000597 return llvm::make_unique<RewriteObjCFragileABI>(
598 InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000599}
Chris Lattnere99c8322007-10-11 00:43:27 +0000600
Fariborz Jahanian83077422011-12-08 18:25:15 +0000601void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000602 Context = &context;
603 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000604 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000605 MsgSendFunctionDecl = nullptr;
606 MsgSendSuperFunctionDecl = nullptr;
607 MsgSendStretFunctionDecl = nullptr;
608 MsgSendSuperStretFunctionDecl = nullptr;
609 MsgSendFpretFunctionDecl = nullptr;
610 GetClassFunctionDecl = nullptr;
611 GetMetaClassFunctionDecl = nullptr;
612 GetSuperClassFunctionDecl = nullptr;
613 SelGetUidFunctionDecl = nullptr;
614 CFStringFunctionDecl = nullptr;
615 ConstantStringClassReference = nullptr;
616 NSStringRecord = nullptr;
617 CurMethodDef = nullptr;
618 CurFunctionDef = nullptr;
619 CurFunctionDeclToDeclareForBlock = nullptr;
620 GlobalVarDecl = nullptr;
621 SuperStructDecl = nullptr;
622 ProtocolTypeDecl = nullptr;
623 ConstantStringDecl = nullptr;
Chris Lattner187f6262008-01-31 19:38:44 +0000624 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000625 SuperConstructorFunctionDecl = nullptr;
Steve Naroffce8e8862008-03-15 00:55:56 +0000626 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000627 PropParentMap = nullptr;
628 CurrentBody = nullptr;
Steve Naroff08628db2008-12-09 12:56:34 +0000629 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000630 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattner187f6262008-01-31 19:38:44 +0000632 // Get the ID and start/end of the main file.
633 MainFileID = SM->getMainFileID();
634 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635 MainFileStart = MainBuf->getBufferStart();
636 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000637
David Blaikiebbafb8a2012-03-11 07:00:24 +0000638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000639}
640
Chris Lattner3c799d72007-10-24 17:06:59 +0000641//===----------------------------------------------------------------------===//
642// Top Level Driver Code
643//===----------------------------------------------------------------------===//
644
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000645void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000646 if (Diags.hasErrorOccurred())
647 return;
648
Chris Lattner0bd1c972007-10-16 21:07:07 +0000649 // Two cases: either the decl could be in the main file, or it could be in a
650 // #included file. If the former, rewrite it now. If the later, check to see
651 // if we rewrote the #include/#import.
652 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000653 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000654
Chris Lattner0bd1c972007-10-16 21:07:07 +0000655 // If this is for a builtin, ignore it.
656 if (Loc.isInvalid()) return;
657
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000658 // Look for built-in declarations that we need to refer during the rewrite.
659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000660 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000661 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000662 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000663 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000664 ConstantStringClassReference = FVD;
665 return;
666 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000667 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
668 if (ID->isThisDeclarationADefinition())
669 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000671 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
676 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000677 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000679 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000680 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
681 if (!IFace->isThisDeclarationADefinition()) {
682 SmallVector<Decl *, 8> DG;
683 SourceLocation StartLoc = IFace->getLocStart();
684 do {
685 if (isa<ObjCInterfaceDecl>(*DI) &&
686 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687 StartLoc == (*DI)->getLocStart())
688 DG.push_back(*DI);
689 else
690 break;
691
Douglas Gregordc9166c2011-12-15 20:29:51 +0000692 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000693 } while (DI != DIEnd);
694 RewriteForwardClassDecl(DG);
695 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000696 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000697 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000698
699 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
700 if (!Proto->isThisDeclarationADefinition()) {
701 SmallVector<Decl *, 8> DG;
702 SourceLocation StartLoc = Proto->getLocStart();
703 do {
704 if (isa<ObjCProtocolDecl>(*DI) &&
705 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706 StartLoc == (*DI)->getLocStart())
707 DG.push_back(*DI);
708 else
709 break;
710
711 ++DI;
712 } while (DI != DIEnd);
713 RewriteForwardProtocolDecl(DG);
714 continue;
715 }
716 }
717
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000718 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000719 ++DI;
720 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000721 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000722 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000723 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000724 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000725}
726
Chris Lattner3c799d72007-10-24 17:06:59 +0000727//===----------------------------------------------------------------------===//
728// Syntactic (non-AST) Rewriting Code
729//===----------------------------------------------------------------------===//
730
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000731void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000733 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000736 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000737
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000738 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
742 return;
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
745 return;
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000748 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000749 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000750 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000751 BufPtr += ImportLen;
752 }
753 }
754 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000755}
756
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000757static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000759 std::string S;
760 S = "((struct ";
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000763 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000764 return S;
765}
766
Steve Naroffc038b3a2008-12-02 17:36:43 +0000767void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000772 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000773 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000778 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000779 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000780
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000783
Steve Naroff9af94912008-12-02 15:48:25 +0000784 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Steve Naroff003d00e2008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Bill Wendling44426052012-12-20 19:22:21 +0000790 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000791 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000794 ObjCPropertyDecl::OBJC_PR_copy));
795 std::string Getr;
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000801 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
804 Getr += "{ ";
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000810 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000812 FPRetType);
813 Getr += " _TYPE";
814 if (FPRetType) {
815 Getr += ")"; // close the precedence "scope" for "*".
816
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000820 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000821 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000822 std::string ParamStr =
823 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000824 Getr += ParamStr;
825 }
826 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000827 if (FT->getNumParams())
828 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000838 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000845 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000848 return;
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Naroff9af94912008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000868 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000871 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000873 Setr += "0, ";
874 else
875 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000884 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000887}
Chris Lattner16a0de42007-10-11 18:38:32 +0000888
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000889static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
890 std::string &typedefString) {
891 typedefString += "#ifndef _REWRITER_typedef_";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
895 typedefString += ForwardDecl->getNameAsString();
896 typedefString += "\n";
897 typedefString += "typedef struct objc_object ";
898 typedefString += ForwardDecl->getNameAsString();
899 typedefString += ";\n#endif\n";
900}
901
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000902void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000903 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000904 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000905 const char *startBuf = SM->getCharacterData(startLoc);
906 const char *semiPtr = strchr(startBuf, ';');
907 // Replace the @class with typedefs corresponding to the classes.
908 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
909}
910
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000911void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000912 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000913 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000914 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000915 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000916 // Translate to typedef's that forward reference structs with the same name
917 // as the class. As a convenience, we include the original declaration
918 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000919 typedefString += "// @class ";
920 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000921 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000922 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000923 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000924 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000925 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000926 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000927}
Mike Stump11289f42009-09-09 15:08:12 +0000928
Craig Topper5603df42013-07-05 19:34:19 +0000929void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000933 if (i == 0) {
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000941}
942
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000943void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000946 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000947 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chandler Carruthd48db212011-07-25 21:09:52 +0000951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000955 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000956 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000957 }
958}
959
Mike Stump11289f42009-09-09 15:08:12 +0000960void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000961 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000962
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000963 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000964 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000965}
966
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000967void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000968 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000969
Steve Naroff5448cf62007-10-30 13:30:57 +0000970 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000972
Manman Rena7a8b1f2016-01-26 18:05:23 +0000973 for (auto *I : CatDecl->instance_properties())
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000974 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000975 for (auto *I : CatDecl->instance_methods())
976 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000977 for (auto *I : CatDecl->class_methods())
978 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000979
Steve Naroff5448cf62007-10-30 13:30:57 +0000980 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000981 ReplaceText(CatDecl->getAtEndRange().getBegin(),
982 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000983}
984
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000985void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000986 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000987 assert(PDecl->isThisDeclarationADefinition());
988
Steve Narofff921385f2007-10-30 16:42:30 +0000989 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000990 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000991
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000992 for (auto *I : PDecl->instance_methods())
993 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000994 for (auto *I : PDecl->class_methods())
995 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +0000996 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000997 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000998
Steve Narofff921385f2007-10-30 16:42:30 +0000999 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001000 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001001 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001002
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001003 // Must comment out @optional/@required
1004 const char *startBuf = SM->getCharacterData(LocStart);
1005 const char *endBuf = SM->getCharacterData(LocEnd);
1006 for (const char *p = startBuf; p < endBuf; p++) {
1007 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001008 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001009 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001010
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001011 }
1012 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001013 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001014 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001015
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001016 }
1017 }
Steve Narofff921385f2007-10-30 16:42:30 +00001018}
1019
Douglas Gregorf6102672012-01-01 21:23:57 +00001020void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1021 SourceLocation LocStart = (*D.begin())->getLocStart();
1022 if (LocStart.isInvalid())
1023 llvm_unreachable("Invalid SourceLocation");
1024 // FIXME: handle forward protocol that are declared across multiple lines.
1025 ReplaceText(LocStart, 0, "// ");
1026}
1027
1028void
Craig Topper5603df42013-07-05 19:34:19 +00001029RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001030 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001031 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001032 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001033 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001034 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001035}
1036
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001037void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1038 const FunctionType *&FPRetType) {
1039 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001040 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001041 else if (T->isFunctionPointerType() ||
1042 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001043 // needs special handling, since pointer-to-functions have special
1044 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001045 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001046 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001048 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001049 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001050 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001051 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001052 ResultStr +=
1053 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001054 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001055 }
1056 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001057 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001058}
1059
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001060void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1061 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001062 std::string &ResultStr) {
1063 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001064 const FunctionType *FPRetType = nullptr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001065 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001066 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001067 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001068
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregorffca3a22009-01-09 17:18:27 +00001072 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001073 NameStr += "_I_";
1074 else
1075 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001076
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001077 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001078 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001079
1080 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001081 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001082 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001083 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001086 {
1087 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 int len = selString.size();
1089 for (int i = 0; i < len; i++)
1090 if (selString[i] == ':')
1091 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001092 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001094 // Remember this name for metadata emission
1095 MethodInternalNames[OMD] = NameStr;
1096 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 // Rewrite arguments
1099 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001100
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001101 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001102 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001103 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001104 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001105 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001106 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001107 ResultStr += "struct ";
1108 }
1109 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001110 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001111 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 }
1113 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001114 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001115 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001116
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001117 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001118 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001119 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001120
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001121 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001122 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001123 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001124 if (PDecl->getType()->isObjCQualifiedIdType()) {
1125 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001126 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001127 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001128 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001129 QualType QT = PDecl->getType();
1130 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001131 (void)convertBlockPointerToFunctionPointer(QT);
1132 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001133 ResultStr += Name;
1134 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001135 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001136 if (OMD->isVariadic())
1137 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001138 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001139
Steve Naroffb067bbd2008-07-16 14:40:40 +00001140 if (FPRetType) {
1141 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001142
Steve Naroffb067bbd2008-07-16 14:40:40 +00001143 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001144 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001145 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001146 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001147 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001148 std::string ParamStr =
1149 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001150 ResultStr += ParamStr;
1151 }
1152 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001153 if (FT->getNumParams())
1154 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001155 ResultStr += "...";
1156 }
1157 ResultStr += ")";
1158 } else {
1159 ResultStr += "()";
1160 }
1161 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001162}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001163
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001164void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001165 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1166 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001168 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001169
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001170 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001172 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001173 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001175
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001181 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001182 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001183 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001184 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001185 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001186
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001187 const char *startBuf = SM->getCharacterData(LocStart);
1188 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001189 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001190 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001191 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1192 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001193
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001194 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001195}
1196
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001197void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001198 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001199 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001200 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001201 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001202 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001203 ResultStr += "\n";
1204 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001205 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001206 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001207 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001208 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001209 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001210 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001211 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001212 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001213 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001214
Manman Rena7a8b1f2016-01-26 18:05:23 +00001215 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001216 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001217 for (auto *I : ClassDecl->instance_methods())
1218 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001219 for (auto *I : ClassDecl->class_methods())
1220 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +00001221
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001222 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1224 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001225}
1226
John McCallfe96e0b2011-11-06 09:01:30 +00001227Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1228 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001229
John McCallfe96e0b2011-11-06 09:01:30 +00001230 // We just magically know some things about the structure of this
1231 // expression.
1232 ObjCMessageExpr *OldMsg =
1233 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1234 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCallfe96e0b2011-11-06 09:01:30 +00001236 // Because the rewriter doesn't allow us to rewrite rewritten code,
1237 // we need to suppress rewriting the sub-statements.
1238 Expr *Base, *RHS;
1239 {
1240 DisableReplaceStmtScope S(*this);
1241
1242 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001243 Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001244 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1245 Base = OldMsg->getInstanceReceiver();
1246 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1247 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1248 }
1249
1250 // Rebuild the RHS.
1251 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1252 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1253 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1254 }
1255
1256 // TODO: avoid this copy.
1257 SmallVector<SourceLocation, 1> SelLocs;
1258 OldMsg->getSelectorLocs(SelLocs);
1259
Craig Topper8ae12032014-05-07 06:21:57 +00001260 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001261 switch (OldMsg->getReceiverKind()) {
1262 case ObjCMessageExpr::Class:
1263 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1264 OldMsg->getValueKind(),
1265 OldMsg->getLeftLoc(),
1266 OldMsg->getClassReceiverTypeInfo(),
1267 OldMsg->getSelector(),
1268 SelLocs,
1269 OldMsg->getMethodDecl(),
1270 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001271 OldMsg->getRightLoc(),
1272 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001273 break;
1274
1275 case ObjCMessageExpr::Instance:
1276 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1277 OldMsg->getValueKind(),
1278 OldMsg->getLeftLoc(),
1279 Base,
1280 OldMsg->getSelector(),
1281 SelLocs,
1282 OldMsg->getMethodDecl(),
1283 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001284 OldMsg->getRightLoc(),
1285 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001286 break;
1287
1288 case ObjCMessageExpr::SuperClass:
1289 case ObjCMessageExpr::SuperInstance:
1290 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1291 OldMsg->getValueKind(),
1292 OldMsg->getLeftLoc(),
1293 OldMsg->getSuperLoc(),
1294 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1295 OldMsg->getSuperType(),
1296 OldMsg->getSelector(),
1297 SelLocs,
1298 OldMsg->getMethodDecl(),
1299 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001300 OldMsg->getRightLoc(),
1301 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001302 break;
1303 }
1304
1305 Stmt *Replacement = SynthMessageExpr(NewMsg);
1306 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1307 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001308}
1309
John McCallfe96e0b2011-11-06 09:01:30 +00001310Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1311 SourceRange OldRange = PseudoOp->getSourceRange();
1312
1313 // We just magically know some things about the structure of this
1314 // expression.
1315 ObjCMessageExpr *OldMsg =
1316 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1317
1318 // Because the rewriter doesn't allow us to rewrite rewritten code,
1319 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001320 Expr *Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001321 {
1322 DisableReplaceStmtScope S(*this);
1323
1324 // Rebuild the base expression if we have one.
1325 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1326 Base = OldMsg->getInstanceReceiver();
1327 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1328 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001329 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001330 }
Steve Narofff326f402008-12-03 00:56:33 +00001331
John McCallfe96e0b2011-11-06 09:01:30 +00001332 // Intentionally empty.
1333 SmallVector<SourceLocation, 1> SelLocs;
1334 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001335
Craig Topper8ae12032014-05-07 06:21:57 +00001336 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001337 switch (OldMsg->getReceiverKind()) {
1338 case ObjCMessageExpr::Class:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 OldMsg->getClassReceiverTypeInfo(),
1343 OldMsg->getSelector(),
1344 SelLocs,
1345 OldMsg->getMethodDecl(),
1346 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001347 OldMsg->getRightLoc(),
1348 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001349 break;
1350
1351 case ObjCMessageExpr::Instance:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1355 Base,
1356 OldMsg->getSelector(),
1357 SelLocs,
1358 OldMsg->getMethodDecl(),
1359 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001360 OldMsg->getRightLoc(),
1361 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001362 break;
1363
1364 case ObjCMessageExpr::SuperClass:
1365 case ObjCMessageExpr::SuperInstance:
1366 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1367 OldMsg->getValueKind(),
1368 OldMsg->getLeftLoc(),
1369 OldMsg->getSuperLoc(),
1370 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1371 OldMsg->getSuperType(),
1372 OldMsg->getSelector(),
1373 SelLocs,
1374 OldMsg->getMethodDecl(),
1375 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001378 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001379 }
John McCallfe96e0b2011-11-06 09:01:30 +00001380
1381 Stmt *Replacement = SynthMessageExpr(NewMsg);
1382 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1383 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001384}
1385
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001386/// SynthCountByEnumWithState - To print:
1387/// ((unsigned int (*)
1388/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001389/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001390/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001391/// "countByEnumeratingWithState:objects:count:"),
1392/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001393/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001395void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1397 "id *, unsigned int))(void *)objc_msgSend)";
1398 buf += "\n\t\t";
1399 buf += "((id)l_collection,\n\t\t";
1400 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1401 buf += "\n\t\t";
1402 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001403 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001404}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001405
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001406/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1407/// statement to exit to its outer synthesized loop.
1408///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001409Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001410 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1411 return S;
1412 // replace break with goto __break_label
1413 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001414
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001415 SourceLocation startLoc = S->getLocStart();
1416 buf = "goto __break_label_";
1417 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001418 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001419
Craig Topper8ae12032014-05-07 06:21:57 +00001420 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001421}
1422
1423/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1424/// statement to continue with its inner synthesized loop.
1425///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001426Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001427 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1428 return S;
1429 // replace continue with goto __continue_label
1430 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001431
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001432 SourceLocation startLoc = S->getLocStart();
1433 buf = "goto __continue_label_";
1434 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001435 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001436
Craig Topper8ae12032014-05-07 06:21:57 +00001437 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001438}
1439
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001440/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001441/// It rewrites:
1442/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001443
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001444/// Into:
1445/// {
Mike Stump11289f42009-09-09 15:08:12 +00001446/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001448/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001450/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001451/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001452/// if (limit) {
1453/// unsigned long startMutations = *enumState.mutationsPtr;
1454/// do {
1455/// unsigned long counter = 0;
1456/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001457/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001459/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001460/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001461/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001462/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001463/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001464/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001465/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001466/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001467/// }
1468/// else
1469/// elem = nil;
1470/// }
1471///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001472Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001473 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001474 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001475 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001476 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001477 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001478 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001479
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001482 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001483 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 std::string buf;
1485 buf = "\n{\n\t";
1486 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1487 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001488 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001489 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001490 if (ElementType->isObjCQualifiedIdType() ||
1491 ElementType->isObjCQualifiedInterfaceType())
1492 // Simply use 'id' for all qualified types.
1493 elementTypeAsString = "id";
1494 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001495 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001496 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001498 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001499 buf += elementName;
1500 buf += ";\n\t";
1501 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001502 else {
1503 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001504 elementName = DR->getDecl()->getName();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001505 ValueDecl *VD = DR->getDecl();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001506 if (VD->getType()->isObjCQualifiedIdType() ||
1507 VD->getType()->isObjCQualifiedInterfaceType())
1508 // Simply use 'id' for all qualified types.
1509 elementTypeAsString = "id";
1510 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001511 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514 // struct __objcFastEnumerationState enumState = { 0 };
1515 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001516 // id __rw_items[16];
1517 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001518 // id l_collection = (id)
1519 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001520 // Find start location of 'collection' the hard way!
1521 const char *startCollectionBuf = startBuf;
1522 startCollectionBuf += 3; // skip 'for'
1523 startCollectionBuf = strchr(startCollectionBuf, '(');
1524 startCollectionBuf++; // skip '('
1525 // find 'in' and skip it.
1526 while (*startCollectionBuf != ' ' ||
1527 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1528 (*(startCollectionBuf+3) != ' ' &&
1529 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1530 startCollectionBuf++;
1531 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001532
1533 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001534 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001535 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001536 SourceLocation rightParenLoc = S->getRParenLoc();
1537 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001538 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001540
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001541 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001542 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001543 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001544 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001545 // ((unsigned int (*)
1546 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001547 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001549 // "countByEnumeratingWithState:objects:count:"),
1550 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001551 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001552 buf += "unsigned long limit =\n\t\t";
1553 SynthCountByEnumWithState(buf);
1554 buf += ";\n\t";
1555 /// if (limit) {
1556 /// unsigned long startMutations = *enumState.mutationsPtr;
1557 /// do {
1558 /// unsigned long counter = 0;
1559 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001560 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001561 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001562 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001563 buf += "if (limit) {\n\t";
1564 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1565 buf += "do {\n\t\t";
1566 buf += "unsigned long counter = 0;\n\t\t";
1567 buf += "do {\n\t\t\t";
1568 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1569 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1570 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001571 buf += " = (";
1572 buf += elementTypeAsString;
1573 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001574 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001575 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001577 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001578 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001579 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001580 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001581 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001582 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001583 /// }
1584 /// else
1585 /// elem = nil;
1586 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001587 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001588 buf = ";\n\t";
1589 buf += "__continue_label_";
1590 buf += utostr(ObjCBcLabelNo.back());
1591 buf += ": ;";
1592 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001593 buf += "} while (counter < limit);\n\t";
1594 buf += "} while (limit = ";
1595 SynthCountByEnumWithState(buf);
1596 buf += ");\n\t";
1597 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001598 buf += " = ((";
1599 buf += elementTypeAsString;
1600 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001601 buf += "__break_label_";
1602 buf += utostr(ObjCBcLabelNo.back());
1603 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001604 buf += "}\n\t";
1605 buf += "else\n\t\t";
1606 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001607 buf += " = ((";
1608 buf += elementTypeAsString;
1609 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001611
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001612 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001613 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001614 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001615 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001616 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001617 } else {
1618 /* Need to treat single statements specially. For example:
1619 *
1620 * for (A *a in b) if (stuff()) break;
1621 * for (A *a in b) xxxyy;
1622 *
1623 * The following code simply scans ahead to the semi to find the actual end.
1624 */
1625 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1626 const char *semiBuf = strchr(stmtBuf, ';');
1627 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001628 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001629 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001630 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001631 Stmts.pop_back();
1632 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001633 return nullptr;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001634}
1635
Mike Stump11289f42009-09-09 15:08:12 +00001636/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001637/// This routine rewrites @synchronized(expr) stmt;
1638/// into:
1639/// objc_sync_enter(expr);
1640/// @try stmt @finally { objc_sync_exit(expr); }
1641///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001642Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001643 // Get the start location and compute the semi location.
1644 SourceLocation startLoc = S->getLocStart();
1645 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001646
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001647 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001648
1649 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001650 buf = "objc_sync_enter((id)";
1651 const char *lparenBuf = startBuf;
1652 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001653 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001654 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1655 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001656 // been rewritten! (which implies the SourceLocation's are invalid).
1657 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001658 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001659 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001660 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001661 buf = ");\n";
1662 // declare a new scope with two variables, _stack and _rethrow.
1663 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1664 buf += "int buf[18/*32-bit i386*/];\n";
1665 buf += "char *pointers[4];} _stack;\n";
1666 buf += "id volatile _rethrow = 0;\n";
1667 buf += "objc_exception_try_enter(&_stack);\n";
1668 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001669 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001670 startLoc = S->getSynchBody()->getLocEnd();
1671 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001672
Steve Naroffad7013b2008-08-19 13:04:19 +00001673 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001674 SourceLocation lastCurlyLoc = startLoc;
1675 buf = "}\nelse {\n";
1676 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001677 buf += "}\n";
1678 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001679 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001680
1681 std::string syncBuf;
1682 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001683
1684 Expr *syncExpr = S->getSynchExpr();
1685 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1686 ? CK_BitCast :
1687 syncExpr->getType()->isBlockPointerType()
1688 ? CK_BlockPointerToObjCPointerCast
1689 : CK_CPointerToObjCPointerCast;
1690 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1691 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001692 std::string syncExprBufS;
1693 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Trieuddd01ce2014-06-09 22:53:25 +00001694 assert(syncExpr != nullptr && "Expected non-null Expr");
Craig Topper8ae12032014-05-07 06:21:57 +00001695 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001696 syncBuf += syncExprBuf.str();
1697 syncBuf += ");";
1698
1699 buf += syncBuf;
1700 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001701 buf += "}\n";
1702 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001703
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001704 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001705
1706 bool hasReturns = false;
1707 HasReturnStmts(S->getSynchBody(), hasReturns);
1708 if (hasReturns)
1709 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1710
Craig Topper8ae12032014-05-07 06:21:57 +00001711 return nullptr;
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001712}
1713
Steve Naroffec60b432009-12-05 21:43:12 +00001714void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1715{
Steve Naroff6d6da252008-12-05 17:03:39 +00001716 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001717 for (Stmt *SubStmt : S->children())
1718 if (SubStmt)
1719 WarnAboutReturnGotoStmts(SubStmt);
Steve Naroff6d6da252008-12-05 17:03:39 +00001720
Steve Naroffec60b432009-12-05 21:43:12 +00001721 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001722 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001723 TryFinallyContainsReturnDiag);
1724 }
Steve Naroff6d6da252008-12-05 17:03:39 +00001725}
1726
Steve Naroffec60b432009-12-05 21:43:12 +00001727void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1728{
1729 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001730 for (Stmt *SubStmt : S->children())
1731 if (SubStmt)
1732 HasReturnStmts(SubStmt, hasReturns);
Steve Naroffec60b432009-12-05 21:43:12 +00001733
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001734 if (isa<ReturnStmt>(S))
1735 hasReturns = true;
Steve Naroffec60b432009-12-05 21:43:12 +00001736}
1737
1738void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001739 // Perform a bottom up traversal of all children.
1740 for (Stmt *SubStmt : S->children())
1741 if (SubStmt) {
1742 RewriteTryReturnStmts(SubStmt);
1743 }
1744 if (isa<ReturnStmt>(S)) {
1745 SourceLocation startLoc = S->getLocStart();
1746 const char *startBuf = SM->getCharacterData(startLoc);
1747 const char *semiBuf = strchr(startBuf, ';');
1748 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1749 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001750
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001751 std::string buf;
1752 buf = "{ objc_exception_try_exit(&_stack); return";
Steve Naroffec60b432009-12-05 21:43:12 +00001753
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001754 ReplaceText(startLoc, 6, buf);
1755 InsertText(onePastSemiLoc, "}");
1756 }
Steve Naroffec60b432009-12-05 21:43:12 +00001757}
1758
1759void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1760 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001761 for (Stmt *SubStmt : S->children())
1762 if (SubStmt) {
1763 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
Steve Naroffec60b432009-12-05 21:43:12 +00001764 }
1765 if (isa<ReturnStmt>(S)) {
1766 SourceLocation startLoc = S->getLocStart();
1767 const char *startBuf = SM->getCharacterData(startLoc);
1768
1769 const char *semiBuf = strchr(startBuf, ';');
1770 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001771 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001772
1773 std::string buf;
1774 buf = "{ objc_exception_try_exit(&_stack);";
1775 buf += syncExitBuf;
1776 buf += " return";
1777
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001778 ReplaceText(startLoc, 6, buf);
1779 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001780 }
Steve Naroffec60b432009-12-05 21:43:12 +00001781}
1782
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001783Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001784 // Get the start location and compute the semi location.
1785 SourceLocation startLoc = S->getLocStart();
1786 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Steve Naroffbf478ec2007-11-07 04:08:17 +00001788 assert((*startBuf == '@') && "bogus @try location");
1789
1790 std::string buf;
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001799 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Steve Naroffbf478ec2007-11-07 04:08:17 +00001801 startLoc = S->getTryBody()->getLocEnd();
1802 startBuf = SM->getCharacterData(startLoc);
1803
1804 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001805
Steve Naroffbf478ec2007-11-07 04:08:17 +00001806 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001807 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001808 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001809 buf = " /* @catch begin */ else {\n";
1810 buf += " id _caught = objc_exception_extract(&_stack);\n";
1811 buf += " objc_exception_try_enter (&_stack);\n";
1812 buf += " if (_setjmp(_stack.buf))\n";
1813 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1814 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001815
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001816 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001817 } else { /* no catch list */
1818 buf = "}\nelse {\n";
1819 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1820 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001821 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001822 }
Craig Topper8ae12032014-05-07 06:21:57 +00001823 Stmt *lastCatchBody = nullptr;
Douglas Gregor96c79492010-04-23 22:50:49 +00001824 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1825 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001826 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001827
Douglas Gregor96c79492010-04-23 22:50:49 +00001828 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001829 buf = "if ("; // we are generating code for the first catch clause
1830 else
1831 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001832 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001833 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001836
Steve Naroffbf478ec2007-11-07 04:08:17 +00001837 const char *lParenLoc = strchr(startBuf, '(');
1838
Douglas Gregor96c79492010-04-23 22:50:49 +00001839 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001840 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001841 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001842 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1843 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001844 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001845 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001846 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001847
Steve Naroffedb5bc62008-02-01 20:02:07 +00001848 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001849 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001850 } else if (catchDecl) {
1851 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001852 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001853 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001854 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001855 } else if (const ObjCObjectPointerType *Ptr =
1856 t->getAs<ObjCObjectPointerType>()) {
1857 // Should be a pointer to a class.
1858 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1859 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001860 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001861 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001862 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001863 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001864 }
1865 }
1866 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001867 lastCatchBody = Catch->getCatchBody();
1868 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1871 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1872 assert((*rParenBuf == ')') && "bogus @catch paren location");
1873 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001874
Mike Stump11289f42009-09-09 15:08:12 +00001875 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001876 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001877 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001878 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001879 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001880 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001881 }
1882 // Complete the catch list...
1883 if (lastCatchBody) {
1884 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001885 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1886 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001887
Steve Naroff4adbe312008-09-11 15:29:03 +00001888 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001889 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001890 buf = "} /* last catch end */\n";
1891 buf += "else {\n";
1892 buf += " _rethrow = _caught;\n";
1893 buf += " objc_exception_try_exit(&_stack);\n";
1894 buf += "} } /* @catch end */\n";
1895 if (!S->getFinallyStmt())
1896 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001897 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Steve Naroffbf478ec2007-11-07 04:08:17 +00001899 // Set lastCurlyLoc
1900 lastCurlyLoc = lastCatchBody->getLocEnd();
1901 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001902 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001903 startLoc = finalStmt->getLocStart();
1904 startBuf = SM->getCharacterData(startLoc);
1905 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001906
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001907 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001908
Steve Naroffbf478ec2007-11-07 04:08:17 +00001909 Stmt *body = finalStmt->getFinallyBody();
1910 SourceLocation startLoc = body->getLocStart();
1911 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001912 assert(*SM->getCharacterData(startLoc) == '{' &&
1913 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001914 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001915 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001916
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001917 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001918 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001919 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001920 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001921
Steve Naroffbf478ec2007-11-07 04:08:17 +00001922 // Set lastCurlyLoc
1923 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001924
Steve Naroff6d6da252008-12-05 17:03:39 +00001925 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001926 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001927 } else { /* no finally clause - make sure we synthesize an implicit one */
1928 buf = "{ /* implicit finally clause */\n";
1929 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1930 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1931 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001932 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001933
1934 // Now check for any return/continue/go statements within the @try.
1935 // The implicit finally clause won't called if the @try contains any
1936 // jump statements.
1937 bool hasReturns = false;
1938 HasReturnStmts(S->getTryBody(), hasReturns);
1939 if (hasReturns)
1940 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001941 }
1942 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001943 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001944 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001945 return nullptr;
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001946}
1947
Mike Stump11289f42009-09-09 15:08:12 +00001948// This can't be done with ReplaceStmt(S, ThrowExpr), since
1949// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001950// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001951Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001952 // Get the start location and compute the semi location.
1953 SourceLocation startLoc = S->getLocStart();
1954 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001955
Steve Naroffa733c7f2007-11-07 15:32:26 +00001956 assert((*startBuf == '@') && "bogus @throw location");
1957
1958 std::string buf;
1959 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001960 if (S->getThrowExpr())
1961 buf = "objc_exception_throw(";
1962 else // add an implicit argument
1963 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001964
Steve Naroff29788342008-07-25 15:41:30 +00001965 // handle "@ throw" correctly.
1966 const char *wBuf = strchr(startBuf, 'w');
1967 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001968 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Steve Naroffa733c7f2007-11-07 15:32:26 +00001970 const char *semiBuf = strchr(startBuf, ';');
1971 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001972 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001973 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00001974 return nullptr;
Steve Naroffa733c7f2007-11-07 15:32:26 +00001975}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001976
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001977Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001978 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00001979 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001980 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00001981 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001982 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Chris Lattner4431a1b2007-11-30 22:53:43 +00001984 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001985 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001986 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001987}
1988
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001990 if (!SelGetUidFunctionDecl)
1991 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001992 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1993 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001994 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00001995 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001996 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00001997 SelExprs);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001998 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001999 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002000 return SelExp;
2001}
2002
Craig Toppercf2126e2015-10-22 03:13:07 +00002003CallExpr *
2004RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2005 ArrayRef<Expr *> Args,
2006 SourceLocation StartLoc,
2007 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002008 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002009 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002010
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002011 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002012 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2013 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002014
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002015 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002016 QualType pToFunc = Context->getPointerType(msgSendType);
Craig Topper8ae12032014-05-07 06:21:57 +00002017 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002018 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002019 DRE, nullptr, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002020
John McCall9dd450b2009-09-21 23:43:11 +00002021 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002022
Craig Toppercf2126e2015-10-22 03:13:07 +00002023 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2024 FT->getCallResultType(*Context),
2025 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002026 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002027}
2028
Steve Naroff50d42052007-11-01 13:24:47 +00002029static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2030 const char *&startRef, const char *&endRef) {
2031 while (startBuf < endBuf) {
2032 if (*startBuf == '<')
2033 startRef = startBuf; // mark the start.
2034 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002035 if (startRef && *startRef == '<') {
2036 endRef = startBuf; // mark the end.
2037 return true;
2038 }
2039 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002040 }
2041 startBuf++;
2042 }
2043 return false;
2044}
2045
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002046static void scanToNextArgument(const char *&argRef) {
2047 int angle = 0;
2048 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2049 if (*argRef == '<')
2050 angle++;
2051 else if (*argRef == '>')
2052 angle--;
2053 argRef++;
2054 }
2055 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2056}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002057
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002058bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002059 if (T->isObjCQualifiedIdType())
2060 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002061 if (const PointerType *PT = T->getAs<PointerType>()) {
2062 if (PT->getPointeeType()->isObjCQualifiedIdType())
2063 return true;
2064 }
2065 if (T->isObjCObjectPointerType()) {
2066 T = T->getPointeeType();
2067 return T->isObjCQualifiedInterfaceType();
2068 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002069 if (T->isArrayType()) {
2070 QualType ElemTy = Context->getBaseElementType(T);
2071 return needToScanForQualifiers(ElemTy);
2072 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002073 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002074}
2075
Steve Naroff873bd842008-07-29 18:15:38 +00002076void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2077 QualType Type = E->getType();
2078 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002079 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Steve Naroffdbfc6932008-11-19 21:15:47 +00002081 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2082 Loc = ECE->getLParenLoc();
2083 EndLoc = ECE->getRParenLoc();
2084 } else {
2085 Loc = E->getLocStart();
2086 EndLoc = E->getLocEnd();
2087 }
2088 // This will defend against trying to rewrite synthesized expressions.
2089 if (Loc.isInvalid() || EndLoc.isInvalid())
2090 return;
2091
Steve Naroff873bd842008-07-29 18:15:38 +00002092 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002093 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002094 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff873bd842008-07-29 18:15:38 +00002095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002097 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2098 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002099 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002100 InsertText(LessLoc, "/*");
2101 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002102 }
2103 }
2104}
2105
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002106void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002107 SourceLocation Loc;
2108 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002109 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002110 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2111 Loc = VD->getLocation();
2112 Type = VD->getType();
2113 }
2114 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2115 Loc = FD->getLocation();
2116 // Check for ObjC 'id' and class types that have been adorned with protocol
2117 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002118 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002119 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002120 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002121 if (!proto)
2122 return;
Alp Toker314cc812014-01-25 16:55:45 +00002123 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002124 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002125 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2126 Loc = FD->getLocation();
2127 Type = FD->getType();
2128 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002129 else
2130 return;
Mike Stump11289f42009-09-09 15:08:12 +00002131
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002132 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002133 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002134
Steve Naroff50d42052007-11-01 13:24:47 +00002135 const char *endBuf = SM->getCharacterData(Loc);
2136 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002137 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002138 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002139 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002140 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2141 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002142 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2143 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002144 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002145 InsertText(LessLoc, "/*");
2146 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002147 }
2148 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002149 if (!proto)
2150 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002151 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152 const char *startBuf = SM->getCharacterData(Loc);
2153 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002154 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2155 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002156 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002157
Steve Naroff50d42052007-11-01 13:24:47 +00002158 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002159 // scan forward (from the decl location) for argument types.
2160 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002161 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002162 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2163 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002164 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002165 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002166 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002167 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002168 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002169 InsertText(LessLoc, "/*");
2170 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002171 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002172 startBuf = ++endBuf;
2173 }
2174 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002175 // If the function name is derived from a macro expansion, then the
2176 // argument buffer will not follow the name. Need to speak with Chris.
2177 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002178 startBuf++; // scan forward (from the decl location) for argument types.
2179 startBuf++;
2180 }
Steve Naroff50d42052007-11-01 13:24:47 +00002181 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002182}
2183
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002184void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2185 QualType QT = ND->getType();
2186 const Type* TypePtr = QT->getAs<Type>();
2187 if (!isa<TypeOfExprType>(TypePtr))
2188 return;
2189 while (isa<TypeOfExprType>(TypePtr)) {
2190 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2191 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2192 TypePtr = QT->getAs<Type>();
2193 }
2194 // FIXME. This will not work for multiple declarators; as in:
2195 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002196 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002197 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2198 const char *startBuf = SM->getCharacterData(DeclLoc);
2199 if (ND->getInit()) {
2200 std::string Name(ND->getNameAsString());
2201 TypeAsString += " " + Name + " = ";
2202 Expr *E = ND->getInit();
2203 SourceLocation startLoc;
2204 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2205 startLoc = ECE->getLParenLoc();
2206 else
2207 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002208 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002209 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002210 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002211 }
2212 else {
2213 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002214 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002215 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002216 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002217 }
2218}
2219
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002220// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002221void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002222 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002223 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002224 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002225 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002226 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002227 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002228 SourceLocation(),
2229 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002230 SelGetUidIdent, getFuncType,
2231 nullptr, SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002232}
2233
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002234void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002235 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002236 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002237 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002238 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002239 return;
2240 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002241 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002242}
2243
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002244void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002245 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002246 const char *argPtr = TypeString.c_str();
2247 if (!strchr(argPtr, '^')) {
2248 Str += TypeString;
2249 return;
2250 }
2251 while (*argPtr) {
2252 Str += (*argPtr == '^' ? '*' : *argPtr);
2253 argPtr++;
2254 }
2255}
2256
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002257// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002258void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2259 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002260 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002261 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002262 const char *argPtr = TypeString.c_str();
2263 int paren = 0;
2264 while (*argPtr) {
2265 switch (*argPtr) {
2266 case '(':
2267 Str += *argPtr;
2268 paren++;
2269 break;
2270 case ')':
2271 Str += *argPtr;
2272 paren--;
2273 break;
2274 case '^':
2275 Str += '*';
2276 if (paren == 1)
2277 Str += VD->getNameAsString();
2278 break;
2279 default:
2280 Str += *argPtr;
2281 break;
2282 }
2283 argPtr++;
2284 }
2285}
2286
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002287void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2288 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2289 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2290 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2291 if (!proto)
2292 return;
Alp Toker314cc812014-01-25 16:55:45 +00002293 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002294 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002295 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002296 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002297 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002298 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002299 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002300 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002301 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002302 if (i+1 < numArgs)
2303 FdStr += ", ";
2304 }
2305 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002306 InsertText(FunLocStart, FdStr);
Craig Topper8ae12032014-05-07 06:21:57 +00002307 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002308}
2309
Benjamin Kramer60509af2013-09-09 14:48:42 +00002310// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2311void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2312 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002313 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002314 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002315 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002316 QualType argT = Context->getObjCIdType();
2317 assert(!argT.isNull() && "Can't find 'id' type");
2318 ArgTys.push_back(argT);
2319 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002320 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002321 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002322 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002323 SourceLocation(),
2324 SourceLocation(),
2325 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002326 nullptr, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002327}
2328
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002329// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002330void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002331 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002332 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002333 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002334 assert(!argT.isNull() && "Can't find 'id' type");
2335 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002336 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002337 assert(!argT.isNull() && "Can't find 'SEL' type");
2338 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002339 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002340 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002341 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002342 SourceLocation(),
2343 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002344 msgSendIdent, msgSendType,
2345 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002346}
2347
Steve Naroff7fa2f042007-11-15 10:28:18 +00002348// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002349void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002350 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002351 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002352 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002353 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002354 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002355 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2356 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2357 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002358 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002359 assert(!argT.isNull() && "Can't find 'SEL' type");
2360 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002361 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002362 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002363 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002364 SourceLocation(),
2365 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002366 msgSendIdent, msgSendType,
2367 nullptr, SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002368}
2369
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002370// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002371void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002372 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002373 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002374 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002375 assert(!argT.isNull() && "Can't find 'id' type");
2376 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002377 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002380 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002381 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002382 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002383 SourceLocation(),
2384 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002385 msgSendIdent, msgSendType,
2386 nullptr, SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002387}
2388
Mike Stump11289f42009-09-09 15:08:12 +00002389// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002390// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002391void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002392 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002393 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002394 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002395 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002396 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002397 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002398 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2399 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2400 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002401 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002402 assert(!argT.isNull() && "Can't find 'SEL' type");
2403 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002404 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002405 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002406 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002407 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002408 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002409 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002410 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002411 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002412}
2413
Steve Naroff2e4e3852008-05-08 22:02:18 +00002414// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002415void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002417 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002418 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002421 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002424 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002425 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002426 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002427 SourceLocation(),
2428 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002429 msgSendIdent, msgSendType,
2430 nullptr, SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002431}
2432
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002433// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002434void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002435 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002436 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002437 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002438 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002439 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002440 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002441 SourceLocation(),
2442 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002443 getClassIdent, getClassType,
2444 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002445}
2446
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002447// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2448void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2449 IdentifierInfo *getSuperClassIdent =
2450 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002451 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002452 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002453 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002454 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002455 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002456 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002457 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002458 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002459 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002460 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002461}
2462
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002463// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002464void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002465 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002466 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002467 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002468 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002469 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002470 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002471 SourceLocation(),
2472 SourceLocation(),
2473 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002474 nullptr, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002475}
2476
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002477Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002478 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffce8e8862008-03-15 00:55:56 +00002479 QualType strType = getConstantStringStructType();
2480
2481 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002482
2483 std::string tmpName = InFileName;
2484 unsigned i;
2485 for (i=0; i < tmpName.length(); i++) {
2486 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002487 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002488 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002489 tmpName[i] = '_';
2490 }
2491 S += tmpName;
2492 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002493 S += utostr(NumObjCStringLiterals++);
2494
Steve Naroff00a31762008-03-27 22:29:16 +00002495 Preamble += "static __NSConstantStringImpl " + S;
2496 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2497 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002498 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002499 std::string prettyBufS;
2500 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002501 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002502 Preamble += prettyBuf.str();
2503 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002504 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002505
2506 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002507 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002508 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002509 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002510 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002511 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002512 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002513 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002514 SourceLocation(), false);
Steve Naroff265a6b92007-11-08 14:30:50 +00002515 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002516 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002517 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002518 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002519 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002520 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002521}
2522
Steve Naroff7fa2f042007-11-15 10:28:18 +00002523// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002524QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002525 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002526 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002527 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002528 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002529 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002530
Steve Naroff7fa2f042007-11-15 10:28:18 +00002531 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002532 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002533 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002534 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002535
Steve Naroff7fa2f042007-11-15 10:28:18 +00002536 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002537 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002538 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002539 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002540 SourceLocation(), nullptr,
2541 FieldTypes[i], nullptr,
2542 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002543 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002544 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Douglas Gregord5058122010-02-11 01:19:42 +00002547 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002548 }
2549 return Context->getTagDeclType(SuperStructDecl);
2550}
2551
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002552QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002553 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002554 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002555 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002556 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002557 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002558
Steve Naroffce8e8862008-03-15 00:55:56 +00002559 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002560 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002561 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002562 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002563 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002564 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002565 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002566 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002567
Steve Naroffce8e8862008-03-15 00:55:56 +00002568 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002569 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002570 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2571 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002572 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002573 SourceLocation(), nullptr,
2574 FieldTypes[i], nullptr,
2575 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002576 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002577 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002578 }
2579
Douglas Gregord5058122010-02-11 01:19:42 +00002580 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002581 }
2582 return Context->getTagDeclType(ConstantStringDecl);
2583}
2584
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002585CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2586 QualType msgSendType,
2587 QualType returnType,
2588 SmallVectorImpl<QualType> &ArgTypes,
2589 SmallVectorImpl<Expr*> &MsgExprs,
2590 ObjCMethodDecl *Method) {
2591 // Create a reference to the objc_msgSend_stret() declaration.
2592 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2593 false, msgSendType,
2594 VK_LValue, SourceLocation());
2595 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2596 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2597 Context->getPointerType(Context->VoidTy),
2598 CK_BitCast, STDRE);
2599 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002600 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2601 Method ? Method->isVariadic()
2602 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002603 castType = Context->getPointerType(castType);
2604 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2605 cast);
2606
2607 // Don't forget the parens to enforce the proper binding.
2608 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2609
2610 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002611 CallExpr *STCE = new (Context) CallExpr(
2612 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002613 return STCE;
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002614}
2615
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002616Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2617 SourceLocation StartLoc,
2618 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002619 if (!SelGetUidFunctionDecl)
2620 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002621 if (!MsgSendFunctionDecl)
2622 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002623 if (!MsgSendSuperFunctionDecl)
2624 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002625 if (!MsgSendStretFunctionDecl)
2626 SynthMsgSendStretFunctionDecl();
2627 if (!MsgSendSuperStretFunctionDecl)
2628 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002629 if (!MsgSendFpretFunctionDecl)
2630 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002631 if (!GetClassFunctionDecl)
2632 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002633 if (!GetSuperClassFunctionDecl)
2634 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002635 if (!GetMetaClassFunctionDecl)
2636 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002637
Steve Naroff7fa2f042007-11-15 10:28:18 +00002638 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002639 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2640 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00002641 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroffd9803712009-04-29 16:37:50 +00002642 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002643 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002644 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002645 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002646 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002647 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Steve Naroff574440f2007-10-24 22:48:43 +00002650 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002651 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002652 switch (Exp->getReceiverKind()) {
2653 case ObjCMessageExpr::SuperClass: {
2654 MsgSendFlavor = MsgSendSuperFunctionDecl;
2655 if (MsgSendStretFlavor)
2656 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2657 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002658
Douglas Gregor9a129192010-04-21 00:45:42 +00002659 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002661 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002662
Douglas Gregor9a129192010-04-21 00:45:42 +00002663 // set the receiver to self, the first argument to all methods.
2664 InitExprs.push_back(
2665 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002666 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002667 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002668 false,
John McCall7decc9e2010-11-18 06:31:45 +00002669 Context->getObjCIdType(),
2670 VK_RValue,
2671 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002672 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregor9a129192010-04-21 00:45:42 +00002674 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002675 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002676 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002677 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002678 ClsExprs, StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002679 // (Class)objc_getClass("CurrentClass")
2680 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2681 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002682 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002683 ClsExprs.clear();
2684 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002685 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002686 StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002687 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2688 // To turn off a warning, type-cast to 'id'
2689 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2690 NoTypeInfoCStyleCastExpr(Context,
2691 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002692 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002693 // struct objc_super
2694 QualType superType = getSuperStructType();
2695 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002696
Francois Pichet0706d202011-09-17 17:15:52 +00002697 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002698 SynthSuperConstructorFunctionDecl();
2699 // Simulate a constructor call...
2700 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002701 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002702 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002703 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002704 superType, VK_LValue,
2705 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002706 // The code for super is a little tricky to prevent collision with
2707 // the structure definition in the header. The rewriter has it's own
2708 // internal definition (__rw_objc_super) that is uses. This is why
2709 // we need the cast below. For example:
2710 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2711 //
John McCalle3027922010-08-25 11:45:40 +00002712 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002713 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002714 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002715 SourceLocation(), false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002716 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2717 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002718 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002719 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002720 // (struct objc_super) { <exprs from above> }
2721 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002722 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002723 SourceLocation());
2724 TypeSourceInfo *superTInfo
2725 = Context->getTrivialTypeSourceInfo(superType);
2726 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002727 superType, VK_LValue,
2728 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002729 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002730 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002731 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002732 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002733 SourceLocation(), false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002734 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002735 MsgExprs.push_back(SuperRep);
2736 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002737 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002738
2739 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002740 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002742 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002743 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002744 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002745 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002746 StartLoc, EndLoc);
2747 MsgExprs.push_back(Cls);
2748 break;
2749 }
2750
2751 case ObjCMessageExpr::SuperInstance:{
2752 MsgSendFlavor = MsgSendSuperFunctionDecl;
2753 if (MsgSendStretFlavor)
2754 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2755 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2756 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002757 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002758
2759 InitExprs.push_back(
2760 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002761 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002762 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002763 false,
John McCall7decc9e2010-11-18 06:31:45 +00002764 Context->getObjCIdType(),
2765 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 ); // set the 'receiver'.
2767
2768 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002769 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002770 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002771 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 StartLoc, EndLoc);
2773 // (Class)objc_getClass("CurrentClass")
2774 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2775 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002776 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002777 ClsExprs.clear();
2778 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002779 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002780 StartLoc, EndLoc);
2781
2782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 // To turn off a warning, type-cast to 'id'
2784 InitExprs.push_back(
2785 // set 'super class', using class_getSuperclass().
2786 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002787 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002788 // struct objc_super
2789 QualType superType = getSuperStructType();
2790 Expr *SuperRep;
2791
Francois Pichet0706d202011-09-17 17:15:52 +00002792 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002793 SynthSuperConstructorFunctionDecl();
2794 // Simulate a constructor call...
2795 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002796 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002797 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002798 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002799 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002800 // The code for super is a little tricky to prevent collision with
2801 // the structure definition in the header. The rewriter has it's own
2802 // internal definition (__rw_objc_super) that is uses. This is why
2803 // we need the cast below. For example:
2804 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2805 //
John McCalle3027922010-08-25 11:45:40 +00002806 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002807 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002808 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002809 SourceLocation(), false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002810 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2811 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002812 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002813 } else {
2814 // (struct objc_super) { <exprs from above> }
2815 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002816 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002817 SourceLocation());
2818 TypeSourceInfo *superTInfo
2819 = Context->getTrivialTypeSourceInfo(superType);
2820 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002821 superType, VK_RValue, ILE,
2822 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002823 }
2824 MsgExprs.push_back(SuperRep);
2825 break;
2826 }
2827
2828 case ObjCMessageExpr::Instance: {
2829 // Remove all type-casts because it may contain objc-style types; e.g.
2830 // Foo<Proto> *.
2831 Expr *recExpr = Exp->getInstanceReceiver();
2832 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2833 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002834 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2835 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2836 ? CK_BlockPointerToObjCPointerCast
2837 : CK_CPointerToObjCPointerCast;
2838
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002840 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002841 MsgExprs.push_back(recExpr);
2842 break;
2843 }
2844 }
2845
Steve Naroffa397efd2007-11-03 11:27:19 +00002846 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002847 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002848 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002849 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002850 SelExprs, StartLoc, EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002851 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Steve Naroff574440f2007-10-24 22:48:43 +00002853 // Now push any user supplied arguments.
2854 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002855 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002856 // Make all implicit casts explicit...ICE comes in handy:-)
2857 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2858 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002859 QualType type = ICE->getType();
2860 if (needToScanForQualifiers(type))
2861 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002862 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002863 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002864 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002865 CastKind CK;
2866 if (SubExpr->getType()->isIntegralType(*Context) &&
2867 type->isBooleanType()) {
2868 CK = CK_IntegralToBoolean;
2869 } else if (type->isObjCObjectPointerType()) {
2870 if (SubExpr->getType()->isBlockPointerType()) {
2871 CK = CK_BlockPointerToObjCPointerCast;
2872 } else if (SubExpr->getType()->isPointerType()) {
2873 CK = CK_CPointerToObjCPointerCast;
2874 } else {
2875 CK = CK_BitCast;
2876 }
2877 } else {
2878 CK = CK_BitCast;
2879 }
2880
2881 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002882 }
2883 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002884 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002885 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002886 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002887 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002888 CastKind CK;
2889 if (userExpr->getType()->isIntegralType(*Context)) {
2890 CK = CK_IntegralToPointer;
2891 } else if (userExpr->getType()->isBlockPointerType()) {
2892 CK = CK_BlockPointerToObjCPointerCast;
2893 } else if (userExpr->getType()->isPointerType()) {
2894 CK = CK_CPointerToObjCPointerCast;
2895 } else {
2896 CK = CK_BitCast;
2897 }
John McCall97513962010-01-15 18:39:57 +00002898 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002899 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002900 }
Mike Stump11289f42009-09-09 15:08:12 +00002901 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002902 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002903 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2904 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002905 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002906 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002907 }
Steve Narofff36987c2007-11-04 22:37:50 +00002908 // Generate the funky cast.
2909 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002910 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002911 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Steve Narofff36987c2007-11-04 22:37:50 +00002913 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002914 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2915 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2916 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002917 ArgTypes.push_back(Context->getObjCIdType());
2918 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002919 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002920 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00002921 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002922 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002923 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002924 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002925 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002926 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002927 ArgTypes.push_back(t);
2928 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002929 returnType = Exp->getType();
2930 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002931 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002932 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002933 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002934 }
2935 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002936 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002937
Steve Narofff36987c2007-11-04 22:37:50 +00002938 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002939 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002940 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002941
Mike Stump11289f42009-09-09 15:08:12 +00002942 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002943 // If we don't do this cast, we get the following bizarre warning/note:
2944 // xx.m:13: warning: function called through a non-compatible type
2945 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002946 cast = NoTypeInfoCStyleCastExpr(Context,
2947 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002948 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002949
Steve Narofff36987c2007-11-04 22:37:50 +00002950 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002951 // If we don't have a method decl, force a variadic cast.
2952 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002953 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002954 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002955 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002956 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002957 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002958
2959 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002960 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002961
John McCall9dd450b2009-09-21 23:43:11 +00002962 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002963 CallExpr *CE = new (Context)
2964 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002965 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002966 if (MsgSendStretFlavor) {
2967 // We have the method which returns a struct/union. Must also generate
2968 // call to objc_msgSend_stret and hang both varieties on a conditional
2969 // expression which dictate which one to envoke depending on size of
2970 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002971
2972 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2973 msgSendType, returnType,
2974 ArgTypes, MsgExprs,
2975 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002976
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002977 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002978 UnaryExprOrTypeTraitExpr *sizeofExpr =
2979 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2980 Context->getTrivialTypeSourceInfo(returnType),
2981 Context->getSizeType(), SourceLocation(),
2982 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002983 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2984 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2985 // For X86 it is more complicated and some kind of target specific routine
2986 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002987 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002988 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002989 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2990 llvm::APInt(IntSize, 8),
2991 Context->IntTy,
2992 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00002993 BinaryOperator *lessThanExpr =
2994 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00002995 VK_RValue, OK_Ordinary, SourceLocation(),
Adam Nemet484aa452017-03-27 19:17:25 +00002996 FPOptions());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002997 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002998 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002999 new (Context) ConditionalOperator(lessThanExpr,
3000 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003001 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003002 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003003 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3004 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003005 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003006 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003007 return ReplacingStmt;
3008}
3009
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003010Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003011 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3012 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003013
Steve Naroff574440f2007-10-24 22:48:43 +00003014 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003015 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003016
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003017 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003018 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003019}
3020
Steve Naroffd9803712009-04-29 16:37:50 +00003021// typedef struct objc_object Protocol;
3022QualType RewriteObjC::getProtocolType() {
3023 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003024 TypeSourceInfo *TInfo
3025 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003026 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003027 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003028 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003029 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003030 }
3031 return Context->getTypeDeclType(ProtocolTypeDecl);
3032}
3033
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003034/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003035/// a synthesized/forward data reference (to the protocol's metadata).
3036/// The forward references (and metadata) are generated in
3037/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003038Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003039 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3040 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003041 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003042 SourceLocation(), ID, getProtocolType(),
3043 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003044 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3045 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003046 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003047 Context->getPointerType(DRE->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00003048 VK_RValue, OK_Ordinary, SourceLocation(), false);
John McCall97513962010-01-15 18:39:57 +00003049 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003050 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003051 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003052 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003053 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003054 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003055 return castExpr;
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003056}
3057
Mike Stump11289f42009-09-09 15:08:12 +00003058bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003059 const char *endBuf) {
3060 while (startBuf < endBuf) {
3061 if (*startBuf == '#') {
3062 // Skip whitespace.
3063 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3064 ;
3065 if (!strncmp(startBuf, "if", strlen("if")) ||
3066 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3067 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3068 !strncmp(startBuf, "define", strlen("define")) ||
3069 !strncmp(startBuf, "undef", strlen("undef")) ||
3070 !strncmp(startBuf, "else", strlen("else")) ||
3071 !strncmp(startBuf, "elif", strlen("elif")) ||
3072 !strncmp(startBuf, "endif", strlen("endif")) ||
3073 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3074 !strncmp(startBuf, "include", strlen("include")) ||
3075 !strncmp(startBuf, "import", strlen("import")) ||
3076 !strncmp(startBuf, "include_next", strlen("include_next")))
3077 return true;
3078 }
3079 startBuf++;
3080 }
3081 return false;
3082}
3083
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003084/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003085/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003086void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003087 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003088 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003089 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003090 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003091 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003092 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003093 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003094 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003095 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003096 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003097 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003098
Steve Naroffdde78982007-11-14 19:25:57 +00003099 const char *startBuf = SM->getCharacterData(LocStart);
3100 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003101
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003102 // If no ivars and no root or if its root, directly or indirectly,
3103 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003104 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003105 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003106 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003107 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003108 return;
3109 }
Mike Stump11289f42009-09-09 15:08:12 +00003110
3111 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003112 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003113 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003114 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003115 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003116 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003117
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003118 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003119 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003120 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003121 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003122 // If the buffer contains preprocessor directives, we do more fine-grained
3123 // rewrites. This is intended to fix code that looks like (which occurs in
3124 // NSURL.h, for example):
3125 //
3126 // #ifdef XYZ
3127 // @interface Foo : NSObject
3128 // #else
3129 // @interface FooBar : NSObject
3130 // #endif
3131 // {
3132 // int i;
3133 // }
3134 // @end
3135 //
3136 // This clause is segregated to avoid breaking the common case.
3137 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003138 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003139 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003140 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003141 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003142
Chris Lattnerf5b77512009-02-20 18:18:36 +00003143 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003144 // advance to the end of the referenced protocols.
3145 while (endHeader < cursor && *endHeader != '>') endHeader++;
3146 endHeader++;
3147 }
3148 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003149 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003150 } else {
3151 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003152 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003153 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003154 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003155 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003156 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003157 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003158 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003159 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003160
Steve Naroffdde78982007-11-14 19:25:57 +00003161 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003162 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003163 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003164 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003165 }
3166 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003167
Steve Naroffdde78982007-11-14 19:25:57 +00003168 // Now comment out any visibility specifiers.
3169 while (cursor < endBuf) {
3170 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003171 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003172 // Skip whitespace.
3173 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3174 /*scan*/;
3175
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003176 // FIXME: presence of @public, etc. inside comment results in
3177 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003178 if (!strncmp(cursor, "public", strlen("public")) ||
3179 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003180 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003181 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003182 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003183 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003184 // FIXME: If there are cases where '<' is used in ivar declaration part
3185 // of user code, then scan the ivar list and use needToScanForQualifiers
3186 // for type checking.
3187 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003188 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003189 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003190 cursor = strchr(cursor, '>');
3191 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003192 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003193 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003194 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003195 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003196 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003197 }
Steve Naroffdde78982007-11-14 19:25:57 +00003198 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003199 }
Steve Naroffdde78982007-11-14 19:25:57 +00003200 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003201 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003202 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003203 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003204 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003205 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003206 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003207 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003208 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003209 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003210 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003211 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003212 if (!ObjCSynthesizedStructs.insert(CDecl).second)
David Blaikie83d382b2011-09-23 05:06:16 +00003213 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003214}
3215
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003216//===----------------------------------------------------------------------===//
3217// Meta Data Emission
3218//===----------------------------------------------------------------------===//
3219
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003220/// RewriteImplementations - This routine rewrites all method implementations
3221/// and emits meta-data.
3222
Steve Narofff8cfd162008-11-13 20:07:04 +00003223void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003224 int ClsDefCount = ClassImplementation.size();
3225 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003226
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003227 // Rewrite implemented methods
3228 for (int i = 0; i < ClsDefCount; i++)
3229 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003230
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003231 for (int i = 0; i < CatDefCount; i++)
3232 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003233}
Mike Stump11289f42009-09-09 15:08:12 +00003234
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003235void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3236 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003237 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003238 assert(BlockByRefDeclNo.count(VD) &&
3239 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003240 if (def)
3241 ResultStr += "struct ";
3242 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003243 "_" + utostr(BlockByRefDeclNo[VD]) ;
3244}
3245
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003246static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3247 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3248 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3249 return false;
3250}
3251
Steve Naroff677ab3a2008-10-27 17:20:55 +00003252std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003253 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003254 std::string Tag) {
3255 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003256 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003257 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003258 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003259 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003260
Steve Naroff677ab3a2008-10-27 17:20:55 +00003261 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003262
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003263 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003264 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003265 // block (to reference imported block decl refs).
3266 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003267 } else if (BD->param_empty()) {
3268 S += "(" + StructRef + " *__cself)";
3269 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003270 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003271 assert(FT && "SynthesizeBlockFunc: No function proto");
3272 S += '(';
3273 // first add the implicit argument.
3274 S += StructRef + " *__cself, ";
3275 std::string ParamStr;
3276 for (BlockDecl::param_iterator AI = BD->param_begin(),
3277 E = BD->param_end(); AI != E; ++AI) {
3278 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003279 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003280 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003281 (void)convertBlockPointerToFunctionPointer(QT);
3282 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003283 S += ParamStr;
3284 }
3285 if (FT->isVariadic()) {
3286 if (!BD->param_empty()) S += ", ";
3287 S += "...";
3288 }
3289 S += ')';
3290 }
3291 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003292
Steve Naroff677ab3a2008-10-27 17:20:55 +00003293 // Create local declarations to avoid rewriting all closure decl ref exprs.
3294 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003295 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003296 E = BlockByRefDecls.end(); I != E; ++I) {
3297 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003298 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003299 std::string TypeString;
3300 RewriteByRefString(TypeString, Name, (*I));
3301 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003302 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003303 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003304 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003305 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003306 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003307 E = BlockByCopyDecls.end(); I != E; ++I) {
3308 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003309 // Handle nested closure invocation. For example:
3310 //
3311 // void (^myImportedClosure)(void);
3312 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003313 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003314 // void (^anotherClosure)(void);
3315 // anotherClosure = ^(void) {
3316 // myImportedClosure(); // import and invoke the closure
3317 // };
3318 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003319 if (isTopLevelBlockPointerType((*I)->getType())) {
3320 RewriteBlockPointerTypeVariable(S, (*I));
3321 S += " = (";
3322 RewriteBlockPointerType(S, (*I)->getType());
3323 S += ")";
3324 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3325 }
3326 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003327 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003328 QualType QT = (*I)->getType();
3329 if (HasLocalVariableExternalStorage(*I))
3330 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003331 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003332 S += Name + " = __cself->" +
3333 (*I)->getNameAsString() + "; // bound by copy\n";
3334 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003335 }
3336 std::string RewrittenStr = RewrittenBlockExprs[CE];
3337 const char *cstr = RewrittenStr.c_str();
3338 while (*cstr++ != '{') ;
3339 S += cstr;
3340 S += "\n";
3341 return S;
3342}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003343
Steve Naroff677ab3a2008-10-27 17:20:55 +00003344std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003345 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003346 std::string Tag) {
3347 std::string StructRef = "struct " + Tag;
3348 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003349
Steve Naroff677ab3a2008-10-27 17:20:55 +00003350 S += funcName;
3351 S += "_block_copy_" + utostr(i);
3352 S += "(" + StructRef;
3353 S += "*dst, " + StructRef;
3354 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003355 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003356 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00003357 S += VD->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003358 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003359 S += VD->getNameAsString();
3360 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003361 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003362 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003363 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003364 else
3365 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003366 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003367 S += "}\n";
3368
Steve Naroff677ab3a2008-10-27 17:20:55 +00003369 S += "\nstatic void __";
3370 S += funcName;
3371 S += "_block_dispose_" + utostr(i);
3372 S += "(" + StructRef;
3373 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003374 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003375 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003376 S += VD->getNameAsString();
3377 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003378 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003379 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003380 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003381 else
3382 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003383 }
Mike Stump11289f42009-09-09 15:08:12 +00003384 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003385 return S;
3386}
3387
Steve Naroff30484702009-12-06 21:14:13 +00003388std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3389 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003390 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003391 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003392
Steve Naroff677ab3a2008-10-27 17:20:55 +00003393 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003394 S += " struct " + Desc;
3395 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003396
Steve Naroff30484702009-12-06 21:14:13 +00003397 Constructor += "(void *fp, "; // Invoke function pointer.
3398 Constructor += "struct " + Desc; // Descriptor pointer.
3399 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003400
Steve Naroff677ab3a2008-10-27 17:20:55 +00003401 if (BlockDeclRefs.size()) {
3402 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003403 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003404 E = BlockByCopyDecls.end(); I != E; ++I) {
3405 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003406 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003407 std::string ArgName = "_" + FieldName;
3408 // Handle nested closure invocation. For example:
3409 //
3410 // void (^myImportedBlock)(void);
3411 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003412 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003413 // void (^anotherBlock)(void);
3414 // anotherBlock = ^(void) {
3415 // myImportedBlock(); // import and invoke the closure
3416 // };
3417 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003418 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003419 S += "struct __block_impl *";
3420 Constructor += ", void *" + ArgName;
3421 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003422 QualType QT = (*I)->getType();
3423 if (HasLocalVariableExternalStorage(*I))
3424 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003425 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3426 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003427 Constructor += ", " + ArgName;
3428 }
3429 S += FieldName + ";\n";
3430 }
3431 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003432 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003433 E = BlockByRefDecls.end(); I != E; ++I) {
3434 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003435 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003436 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003437 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003438 std::string TypeString;
3439 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003440 TypeString += " *";
3441 FieldName = TypeString + FieldName;
3442 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003443 Constructor += ", " + ArgName;
3444 }
3445 S += FieldName + "; // by ref\n";
3446 }
3447 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003448 Constructor += ", int flags=0)";
3449 // Initialize all "by copy" arguments.
3450 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003451 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003452 E = BlockByCopyDecls.end(); I != E; ++I) {
3453 std::string Name = (*I)->getNameAsString();
3454 if (firsTime) {
3455 Constructor += " : ";
3456 firsTime = false;
3457 }
3458 else
3459 Constructor += ", ";
3460 if (isTopLevelBlockPointerType((*I)->getType()))
3461 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3462 else
3463 Constructor += Name + "(_" + Name + ")";
3464 }
3465 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003466 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003467 E = BlockByRefDecls.end(); I != E; ++I) {
3468 std::string Name = (*I)->getNameAsString();
3469 if (firsTime) {
3470 Constructor += " : ";
3471 firsTime = false;
3472 }
3473 else
3474 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003475 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003476 }
3477
3478 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003479 if (GlobalVarDecl)
3480 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3481 else
3482 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003483 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003484
Steve Naroff30484702009-12-06 21:14:13 +00003485 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003486 } else {
3487 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003488 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003489 if (GlobalVarDecl)
3490 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3491 else
3492 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003493 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3494 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003495 }
3496 Constructor += " ";
3497 Constructor += "}\n";
3498 S += Constructor;
3499 S += "};\n";
3500 return S;
3501}
3502
Steve Naroff30484702009-12-06 21:14:13 +00003503std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3504 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003505 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003506 unsigned hasCopy) {
3507 std::string S = "\nstatic struct " + DescTag;
3508
3509 S += " {\n unsigned long reserved;\n";
3510 S += " unsigned long Block_size;\n";
3511 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003512 S += " void (*copy)(struct ";
3513 S += ImplTag; S += "*, struct ";
3514 S += ImplTag; S += "*);\n";
3515
3516 S += " void (*dispose)(struct ";
3517 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003518 }
3519 S += "} ";
3520
3521 S += DescTag + "_DATA = { 0, sizeof(struct ";
3522 S += ImplTag + ")";
3523 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003524 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3525 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003526 }
3527 S += "};\n";
3528 return S;
3529}
3530
Steve Naroff677ab3a2008-10-27 17:20:55 +00003531void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003532 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003533 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003534 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003535 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003536 bool RewriteSC = (GlobalVarDecl &&
3537 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003538 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003539 GlobalVarDecl->getType().getCVRQualifiers());
3540 if (RewriteSC) {
3541 std::string SC(" void __");
3542 SC += GlobalVarDecl->getNameAsString();
3543 SC += "() {}";
3544 InsertText(FunLocStart, SC);
3545 }
3546
Steve Naroff677ab3a2008-10-27 17:20:55 +00003547 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003548 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3549 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003550 // Need to copy-in the inner copied-in variables not actually used in this
3551 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003552 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003553 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003554 ValueDecl *VD = Exp->getDecl();
3555 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003556 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003557 BlockByCopyDeclsPtrSet.insert(VD);
3558 BlockByCopyDecls.push_back(VD);
3559 }
John McCall113bee02012-03-10 09:33:50 +00003560 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003561 BlockByRefDeclsPtrSet.insert(VD);
3562 BlockByRefDecls.push_back(VD);
3563 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003564 // imported objects in the inner blocks not used in the outer
3565 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003566 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003567 VD->getType()->isObjCObjectPointerType() ||
3568 VD->getType()->isBlockPointerType())
3569 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003570 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003571
Daniel Dunbar56df9772010-08-17 22:39:59 +00003572 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3573 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003574
Steve Naroff30484702009-12-06 21:14:13 +00003575 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003576
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003577 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003578
Steve Naroff30484702009-12-06 21:14:13 +00003579 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003581 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003582
3583 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003584 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003585 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003586 }
Steve Naroff30484702009-12-06 21:14:13 +00003587 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3588 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003589 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003590
Steve Naroff677ab3a2008-10-27 17:20:55 +00003591 BlockDeclRefs.clear();
3592 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003593 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003594 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003595 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003596 ImportedBlockDecls.clear();
3597 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003598 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003599 // Must insert any 'const/volatile/static here. Since it has been
3600 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003601 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003602 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003603 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003604 if (GlobalVarDecl->getType().isConstQualified())
3605 SC += "const ";
3606 if (GlobalVarDecl->getType().isVolatileQualified())
3607 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003608 if (GlobalVarDecl->getType().isRestrictQualified())
3609 SC += "restrict ";
3610 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003611 }
3612
Steve Naroff677ab3a2008-10-27 17:20:55 +00003613 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003614 InnerDeclRefsCount.clear();
3615 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003616 RewrittenBlockExprs.clear();
3617}
3618
3619void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3620 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003621 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003622
Steve Naroff677ab3a2008-10-27 17:20:55 +00003623 SynthesizeBlockLiterals(FunLocStart, FuncName);
3624}
3625
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003626static void BuildUniqueMethodName(std::string &Name,
3627 ObjCMethodDecl *MD) {
3628 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003629 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003630 Name += "__" + MD->getSelector().getAsString();
3631 // Convert colons to underscores.
3632 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00003633 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003634 Name.replace(loc, 1, "_");
3635}
3636
Steve Naroff677ab3a2008-10-27 17:20:55 +00003637void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003638 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3639 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003640 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003641 std::string FuncName;
3642 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003643 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003644}
3645
3646void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003647 for (Stmt *SubStmt : S->children())
3648 if (SubStmt) {
3649 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003650 GetBlockDeclRefExprs(CBE->getBody());
3651 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003652 GetBlockDeclRefExprs(SubStmt);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003653 }
3654 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003656 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003657 HasLocalVariableExternalStorage(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003658 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003659 BlockDeclRefs.push_back(DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003660}
3661
Craig Topper5603df42013-07-05 19:34:19 +00003662void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3663 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00003664 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003665 for (Stmt *SubStmt : S->children())
3666 if (SubStmt) {
3667 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003668 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003669 GetInnerBlockDeclRefExprs(CBE->getBody(),
3670 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003671 InnerContexts);
3672 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003673 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003674 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003675 }
3676 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003678 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003679 HasLocalVariableExternalStorage(DRE->getDecl())) {
3680 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00003681 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00003682 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003683 if (Var->isFunctionOrMethodVarDecl())
3684 ImportedLocalExternalDecls.insert(Var);
3685 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003686 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003687}
3688
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003689/// convertFunctionTypeOfBlocks - This routine converts a function type
3690/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003691/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003692/// all block pointers to function pointers.
3693QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3694 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3695 // FTP will be null for closures that don't take arguments.
3696 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003697 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003698 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003699 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003700
3701 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003702 for (auto &I : FTP->param_types()) {
3703 QualType t = I;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003704 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003705 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003706 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003707 ArgTypes.push_back(t);
3708 }
3709 }
3710 QualType FuncType;
3711 // FIXME. Does this work if block takes no argument but has a return type
3712 // which is of block type?
3713 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003714 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003715 else FuncType = QualType(FT, 0);
3716 return FuncType;
3717}
3718
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003719Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003720 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00003721 const BlockPointerType *CPT = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003722
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003723 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003724 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003725 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003726 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003727 }
3728 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3729 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3730 }
3731 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3732 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3733 else if (const ConditionalOperator *CEXPR =
3734 dyn_cast<ConditionalOperator>(BlockExp)) {
3735 Expr *LHSExp = CEXPR->getLHS();
3736 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3737 Expr *RHSExp = CEXPR->getRHS();
3738 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3739 Expr *CONDExp = CEXPR->getCond();
3740 ConditionalOperator *CondExpr =
3741 new (Context) ConditionalOperator(CONDExp,
3742 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003743 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003744 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003745 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003746 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3747 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003748 } else if (const PseudoObjectExpr *POE
3749 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3750 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003751 } else {
Craig Topper0da20762016-04-24 02:08:22 +00003752 assert(false && "RewriteBlockClass: Bad type");
Steve Naroff677ab3a2008-10-27 17:20:55 +00003753 }
3754 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003755 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003756 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003757 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003758 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003759
Abramo Bagnara6150c882010-05-11 21:36:43 +00003760 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003761 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003762 &Context->Idents.get("__block_impl"));
3763 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764
Steve Naroff350b6652008-10-30 10:07:53 +00003765 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003766 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003767
Steve Naroff350b6652008-10-30 10:07:53 +00003768 // Push the block argument type.
3769 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003770 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003771 for (auto &I : FTP->param_types()) {
3772 QualType t = I;
Steve Naroff350b6652008-10-30 10:07:53 +00003773 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003774 if (!convertBlockPointerToFunctionPointer(t))
3775 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003776 ArgTypes.push_back(t);
3777 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003778 }
Steve Naroff350b6652008-10-30 10:07:53 +00003779 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003780 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003781
Steve Naroff350b6652008-10-30 10:07:53 +00003782 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003783
John McCall97513962010-01-15 18:39:57 +00003784 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003785 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003786 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003787 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003788 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3789 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003790 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003791
Craig Topper8ae12032014-05-07 06:21:57 +00003792 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003793 SourceLocation(),
3794 &Context->Idents.get("FuncPtr"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003795 Context->VoidPtrTy, nullptr,
3796 /*BitWidth=*/nullptr, /*Mutable=*/true,
3797 ICIS_NoInit);
3798 MemberExpr *ME =
3799 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
3800 FD->getType(), VK_LValue, OK_Ordinary);
3801
3802 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3803 CK_BitCast, ME);
3804 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003805
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003806 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003807 // Add the implicit argument.
3808 BlkExprs.push_back(BlkCast);
3809 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003810 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003811 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003812 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003813 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003814 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003815 Exp->getType(), VK_RValue,
3816 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003817 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003818}
3819
Steve Naroffd9803712009-04-29 16:37:50 +00003820// We need to return the rewritten expression to handle cases where the
3821// BlockDeclRefExpr is embedded in another expression being rewritten.
3822// For example:
3823//
3824// int main() {
3825// __block Foo *f;
3826// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003827//
Steve Naroffd9803712009-04-29 16:37:50 +00003828// void (^myblock)() = ^() {
3829// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3830// i = 77;
3831// };
3832//}
John McCall113bee02012-03-10 09:33:50 +00003833Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003834 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003835 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003836 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003837 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003838 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00003839
3840 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003841 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003842 &Context->Idents.get("__forwarding"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003843 Context->VoidPtrTy, nullptr,
3844 /*BitWidth=*/nullptr, /*Mutable=*/true,
3845 ICIS_NoInit);
3846 MemberExpr *ME = new (Context)
3847 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
3848 FD->getType(), VK_LValue, OK_Ordinary);
3849
3850 StringRef Name = VD->getName();
3851 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003852 &Context->Idents.get(Name),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003853 Context->VoidPtrTy, nullptr,
3854 /*BitWidth=*/nullptr, /*Mutable=*/true,
3855 ICIS_NoInit);
3856 ME =
3857 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
3858 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3859
3860 // Need parens to enforce precedence.
3861 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3862 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003863 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003864 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003865 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003866}
3867
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003868// Rewrites the imported local variable V with external storage
3869// (static, extern, etc.) as *V
3870//
3871Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3872 ValueDecl *VD = DRE->getDecl();
3873 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3874 if (!ImportedLocalExternalDecls.count(Var))
3875 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003876 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3877 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003878 DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003879 // Need parens to enforce precedence.
3880 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3881 Exp);
3882 ReplaceStmt(DRE, PE);
3883 return PE;
3884}
3885
Steve Naroffc989a7b2008-11-03 23:29:32 +00003886void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3887 SourceLocation LocStart = CE->getLParenLoc();
3888 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003889
3890 // Need to avoid trying to rewrite synthesized casts.
3891 if (LocStart.isInvalid())
3892 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003893 // Need to avoid trying to rewrite casts contained in macros.
3894 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3895 return;
Mike Stump11289f42009-09-09 15:08:12 +00003896
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 const char *startBuf = SM->getCharacterData(LocStart);
3898 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003899 QualType QT = CE->getType();
3900 const Type* TypePtr = QT->getAs<Type>();
3901 if (isa<TypeOfExprType>(TypePtr)) {
3902 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3903 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3904 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003905 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003906 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003907 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003908 return;
3909 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 // advance the location to startArgList.
3911 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003912
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913 while (*argPtr++ && (argPtr < endBuf)) {
3914 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003915 case '^':
3916 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003917 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003918 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003919 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 }
3921 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922}
3923
3924void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3925 SourceLocation DeclLoc = FD->getLocation();
3926 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003927
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 // We have 1 or more arguments that have closure pointers.
3929 const char *startBuf = SM->getCharacterData(DeclLoc);
3930 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003931
Steve Naroff677ab3a2008-10-27 17:20:55 +00003932 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003933
Steve Naroff677ab3a2008-10-27 17:20:55 +00003934 parenCount++;
3935 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003936 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00003938
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00003940
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941 while (*argPtr++ && parenCount) {
3942 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003943 case '^':
3944 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003945 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003946 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003947 break;
3948 case '(':
3949 parenCount++;
3950 break;
3951 case ')':
3952 parenCount--;
3953 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003954 }
3955 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003956}
3957
3958bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003959 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003960 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00003962 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003964 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00003966 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 }
3968 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003969 for (const auto &I : FTP->param_types())
3970 if (isTopLevelBlockPointerType(I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003971 return true;
3972 }
3973 return false;
3974}
3975
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003976bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3977 const FunctionProtoType *FTP;
3978 const PointerType *PT = QT->getAs<PointerType>();
3979 if (PT) {
3980 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3981 } else {
3982 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3983 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3984 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3985 }
3986 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003987 for (const auto &I : FTP->param_types()) {
3988 if (I->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003989 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003990 if (I->isObjCObjectPointerType() &&
3991 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian733dde62010-11-03 23:50:34 +00003992 return true;
3993 }
3994
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003995 }
3996 return false;
3997}
3998
Ted Kremenek5a201952009-02-07 01:47:29 +00003999void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4000 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 const char *argPtr = strchr(Name, '(');
4002 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004003
Steve Naroff677ab3a2008-10-27 17:20:55 +00004004 LParen = argPtr; // output the start.
4005 argPtr++; // skip past the left paren.
4006 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004007
Steve Naroff677ab3a2008-10-27 17:20:55 +00004008 while (*argPtr && parenCount) {
4009 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004010 case '(': parenCount++; break;
4011 case ')': parenCount--; break;
4012 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004013 }
4014 if (parenCount) argPtr++;
4015 }
4016 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4017 RParen = argPtr; // output the end
4018}
4019
4020void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4022 RewriteBlockPointerFunctionArgs(FD);
4023 return;
Mike Stump11289f42009-09-09 15:08:12 +00004024 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004025 // Handle Variables and Typedefs.
4026 SourceLocation DeclLoc = ND->getLocation();
4027 QualType DeclT;
4028 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4029 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004030 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 DeclT = TDD->getUnderlyingType();
4032 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4033 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004034 else
David Blaikie83d382b2011-09-23 05:06:16 +00004035 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004036
Steve Naroff677ab3a2008-10-27 17:20:55 +00004037 const char *startBuf = SM->getCharacterData(DeclLoc);
4038 const char *endBuf = startBuf;
4039 // scan backward (from the decl location) for the end of the previous decl.
4040 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4041 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004042 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004043 std::string buf;
4044 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004045 // *startBuf != '^' if we are dealing with a pointer to function that
4046 // may take block argument types (which will be handled below).
4047 if (*startBuf == '^') {
4048 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004049 buf = '*';
4050 startBuf++;
4051 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004053 while (*startBuf != ')') {
4054 buf += *startBuf;
4055 startBuf++;
4056 OrigLength++;
4057 }
4058 buf += ')';
4059 OrigLength++;
4060
4061 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4062 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004063 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004064 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004065 DeclLoc = ND->getLocation();
4066 startBuf = SM->getCharacterData(DeclLoc);
4067 const char *argListBegin, *argListEnd;
4068 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4069 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004070 if (*argListBegin == '^')
4071 buf += '*';
4072 else if (*argListBegin == '<') {
4073 buf += "/*";
4074 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004075 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004076 while (*argListBegin != '>') {
4077 buf += *argListBegin++;
4078 OrigLength++;
4079 }
4080 buf += *argListBegin;
4081 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004082 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004083 else
4084 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004085 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004086 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004087 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004088 buf += ')';
4089 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004091 ReplaceText(Start, OrigLength, buf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004092}
4093
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004094/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4095/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4096/// struct Block_byref_id_object *src) {
4097/// _Block_object_assign (&_dest->object, _src->object,
4098/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4099/// [|BLOCK_FIELD_IS_WEAK]) // object
4100/// _Block_object_assign(&_dest->object, _src->object,
4101/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4102/// [|BLOCK_FIELD_IS_WEAK]) // block
4103/// }
4104/// And:
4105/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4106/// _Block_object_dispose(_src->object,
4107/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4108/// [|BLOCK_FIELD_IS_WEAK]) // object
4109/// _Block_object_dispose(_src->object,
4110/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4111/// [|BLOCK_FIELD_IS_WEAK]) // block
4112/// }
4113
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004114std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4115 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004116 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004117 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004118 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004119 CopyDestroyCache.insert(flag);
4120 S = "static void __Block_byref_id_object_copy_";
4121 S += utostr(flag);
4122 S += "(void *dst, void *src) {\n";
4123
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004124 // offset into the object pointer is computed as:
4125 // void * + void* + int + int + void* + void *
4126 unsigned IntSize =
4127 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4128 unsigned VoidPtrSize =
4129 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4130
Ken Dyckd9c83e62011-04-30 16:08:27 +00004131 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004132 S += " _Block_object_assign((char*)dst + ";
4133 S += utostr(offset);
4134 S += ", *(void * *) ((char*)src + ";
4135 S += utostr(offset);
4136 S += "), ";
4137 S += utostr(flag);
4138 S += ");\n}\n";
4139
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004140 S += "static void __Block_byref_id_object_dispose_";
4141 S += utostr(flag);
4142 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004143 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4144 S += utostr(offset);
4145 S += "), ";
4146 S += utostr(flag);
4147 S += ");\n}\n";
4148 return S;
4149}
4150
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004151/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4152/// the declaration into:
4153/// struct __Block_byref_ND {
4154/// void *__isa; // NULL for everything except __weak pointers
4155/// struct __Block_byref_ND *__forwarding;
4156/// int32_t __flags;
4157/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004158/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4159/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004160/// typex ND;
4161/// };
4162///
4163/// It then replaces declaration of ND variable with:
4164/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4165/// __size=sizeof(struct __Block_byref_ND),
4166/// ND=initializer-if-any};
4167///
4168///
4169void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004170 // Insert declaration for the function in which block literal is
4171 // used.
4172 if (CurFunctionDeclToDeclareForBlock)
4173 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004174 int flag = 0;
4175 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004176 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004177 if (DeclLoc.isInvalid())
4178 // If type location is missing, it is because of missing type (a warning).
4179 // Use variable's location which is good for this case.
4180 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004181 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004182 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004183 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004184 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004185 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004186 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004187 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004188 ByrefType += " {\n";
4189 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004190 RewriteByRefString(ByrefType, Name, ND);
4191 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004192 ByrefType += " int __flags;\n";
4193 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004194 // Add void *__Block_byref_id_object_copy;
4195 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004196 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004197 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004198 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004199 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4200 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004201 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004202
4203 QualType T = Ty;
4204 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004205 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004206
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004207 ByrefType += " " + Name + ";\n";
4208 ByrefType += "};\n";
4209 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004210 SourceLocation FunLocStart;
4211 if (CurFunctionDef)
4212 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4213 else {
4214 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4215 FunLocStart = CurMethodDef->getLocStart();
4216 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004217 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004218 if (Ty.isObjCGCWeak()) {
4219 flag |= BLOCK_FIELD_IS_WEAK;
4220 isa = 1;
4221 }
4222
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004223 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004224 flag = BLOCK_BYREF_CALLER;
4225 QualType Ty = ND->getType();
4226 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4227 if (Ty->isBlockPointerType())
4228 flag |= BLOCK_FIELD_IS_BLOCK;
4229 else
4230 flag |= BLOCK_FIELD_IS_OBJECT;
4231 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004232 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004233 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004234 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004235
4236 // struct __Block_byref_ND ND =
4237 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4238 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00004239 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004240 unsigned flags = 0;
4241 if (HasCopyAndDispose)
4242 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004243 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004244 ByrefType.clear();
4245 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004246 std::string ForwardingCastType("(");
4247 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004248 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004249 ByrefType += " " + Name + " = {(void*)";
4250 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004251 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004252 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004253 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004254 ByrefType += "sizeof(";
4255 RewriteByRefString(ByrefType, Name, ND);
4256 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004257 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004258 ByrefType += ", __Block_byref_id_object_copy_";
4259 ByrefType += utostr(flag);
4260 ByrefType += ", __Block_byref_id_object_dispose_";
4261 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004262 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004263 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004264 unsigned nameSize = Name.size();
Simon Pilgrim2c518802017-03-30 14:13:19 +00004265 // for block or function pointer declaration. Name is already
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004266 // part of the declaration.
4267 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4268 nameSize = 1;
4269 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004270 }
4271 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004272 SourceLocation startLoc;
4273 Expr *E = ND->getInit();
4274 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4275 startLoc = ECE->getLParenLoc();
4276 else
4277 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004278 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004279 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004280 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004281 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004282 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004283 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004284 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004285 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004286 ByrefType += "sizeof(";
4287 RewriteByRefString(ByrefType, Name, ND);
4288 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004289 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004290 ByrefType += "__Block_byref_id_object_copy_";
4291 ByrefType += utostr(flag);
4292 ByrefType += ", __Block_byref_id_object_dispose_";
4293 ByrefType += utostr(flag);
4294 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004295 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004296 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004297
4298 // Complete the newly synthesized compound expression by inserting a right
4299 // curly brace before the end of the declaration.
4300 // FIXME: This approach avoids rewriting the initializer expression. It
4301 // also assumes there is only one declarator. For example, the following
4302 // isn't currently supported by this routine (in general):
4303 //
4304 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4305 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004306 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4307 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004308 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4309 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004310 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004311
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004312 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004313 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004314}
4315
Mike Stump11289f42009-09-09 15:08:12 +00004316void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 // Add initializers for any closure decl refs.
4318 GetBlockDeclRefExprs(Exp->getBody());
4319 if (BlockDeclRefs.size()) {
4320 // Unique all "by copy" declarations.
4321 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004322 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004323 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4324 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4325 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4326 }
4327 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 // Unique all "by ref" declarations.
4329 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004330 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004331 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4332 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4333 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4334 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004335 }
4336 // Find any imported blocks...they will need special attention.
4337 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004338 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004339 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004340 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004341 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004342 }
4343}
4344
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004345FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004346 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004347 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004348 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00004349 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004350 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004351}
4352
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004353Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004354 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004355 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004356 Blocks.push_back(Exp);
4357
4358 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004359
4360 // Add inner imported variables now used in current block.
4361 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004362 if (!InnerBlockDeclRefs.empty()) {
4363 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004364 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004365 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004366 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004367 // We need to save the copied-in variables in nested
4368 // blocks because it is needed at the end for some of the API generations.
4369 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004370 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4371 BlockDeclRefs.push_back(Exp);
4372 BlockByCopyDeclsPtrSet.insert(VD);
4373 BlockByCopyDecls.push_back(VD);
4374 }
John McCall113bee02012-03-10 09:33:50 +00004375 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004376 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4377 BlockDeclRefs.push_back(Exp);
4378 BlockByRefDeclsPtrSet.insert(VD);
4379 BlockByRefDecls.push_back(VD);
4380 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004381 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004382 // Find any imported blocks...they will need special attention.
4383 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004384 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004385 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4386 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4387 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004388 }
4389 InnerDeclRefsCount.push_back(countOfInnerDecls);
4390
Steve Narofff4b992a2008-10-28 20:29:00 +00004391 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004392
Steve Narofff4b992a2008-10-28 20:29:00 +00004393 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004394 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004395 else if (CurMethodDef)
4396 BuildUniqueMethodName(FuncName, CurMethodDef);
4397 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004398 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004399
Steve Narofff4b992a2008-10-28 20:29:00 +00004400 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004401
Steve Narofff4b992a2008-10-28 20:29:00 +00004402 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4403 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004404
Steve Narofff4b992a2008-10-28 20:29:00 +00004405 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004406 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4407 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004408
4409 FunctionDecl *FD;
4410 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004411
Benjamin Kramer60509af2013-09-09 14:48:42 +00004412 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004413 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004414 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004415 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004416
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004417 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004418
Steve Naroffe2514232008-10-29 21:23:59 +00004419 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004420 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004421 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4422 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004423 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004424 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004425 InitExprs.push_back(castExpr);
4426
Steve Naroff30484702009-12-06 21:14:13 +00004427 // Initialize the block descriptor.
4428 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004429
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004430 VarDecl *NewVD = VarDecl::Create(
4431 *Context, TUDecl, SourceLocation(), SourceLocation(),
4432 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004433 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004434 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004435 Context->VoidPtrTy,
4436 VK_LValue,
4437 SourceLocation()),
4438 UO_AddrOf,
4439 Context->getPointerType(Context->VoidPtrTy),
4440 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00004441 SourceLocation(), false);
Steve Naroff30484702009-12-06 21:14:13 +00004442 InitExprs.push_back(DescRefExpr);
4443
Steve Narofff4b992a2008-10-28 20:29:00 +00004444 // Add initializers for any closure decl refs.
4445 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004446 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004447 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004448 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004449 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004450 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004451 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004452 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004453 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004454 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004455 if (HasLocalVariableExternalStorage(*I)) {
4456 QualType QT = (*I)->getType();
4457 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004458 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00004459 OK_Ordinary, SourceLocation(),
4460 false);
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004461 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004462 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004463 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004464 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004465 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004466 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004467 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004468 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004469 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004470 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004471 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004472 if (HasLocalVariableExternalStorage(*I)) {
4473 QualType QT = (*I)->getType();
4474 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004475 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00004476 OK_Ordinary, SourceLocation(),
4477 false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004478 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004479 }
Mike Stump11289f42009-09-09 15:08:12 +00004480 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004481 }
4482 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004483 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004484 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004485 ValueDecl *ND = (*I);
4486 std::string Name(ND->getNameAsString());
4487 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004488 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004489 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4490 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004491 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004492 SourceLocation(), SourceLocation(),
4493 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004494 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4495 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4496
Daniel Dunbar56df9772010-08-17 22:39:59 +00004497 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004498 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004499 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004500 bool isNestedCapturedVar = false;
4501 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00004502 for (const auto &CI : block->captures()) {
4503 const VarDecl *variable = CI.getVariable();
4504 if (variable == ND && CI.isNested()) {
4505 assert (CI.isByRef() &&
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004506 "SynthBlockInitExpr - captured block variable is not byref");
4507 isNestedCapturedVar = true;
4508 break;
4509 }
4510 }
4511 // captured nested byref variable has its address passed. Do not take
4512 // its address again.
4513 if (!isNestedCapturedVar)
Aaron Ballmana5038552018-01-09 13:07:03 +00004514 Exp = new (Context) UnaryOperator(
4515 Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_RValue,
4516 OK_Ordinary, SourceLocation(), false);
John McCallf608deb2010-11-15 09:46:46 +00004517 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004518 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004519 }
4520 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004521 if (ImportedBlockDecls.size()) {
4522 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4523 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004524 unsigned IntSize =
4525 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004526 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4527 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004528 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004529 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004530 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004531 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004532 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004533 Context->getPointerType(NewRep->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00004534 VK_RValue, OK_Ordinary, SourceLocation(), false);
John McCallf608deb2010-11-15 09:46:46 +00004535 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004536 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004537 BlockDeclRefs.clear();
4538 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004539 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004540 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004541 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004542 ImportedBlockDecls.clear();
4543 return NewRep;
4544}
4545
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004546bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4547 if (const ObjCForCollectionStmt * CS =
4548 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4549 return CS->getElement() == DS;
4550 return false;
4551}
4552
Steve Narofff4b992a2008-10-28 20:29:00 +00004553//===----------------------------------------------------------------------===//
4554// Function Body / Expression rewriting
4555//===----------------------------------------------------------------------===//
4556
4557Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004558 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004559 isa<DoStmt>(S) || isa<ForStmt>(S))
4560 Stmts.push_back(S);
4561 else if (isa<ObjCForCollectionStmt>(S)) {
4562 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004563 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
John McCallfe96e0b2011-11-06 09:01:30 +00004566 // Pseudo-object operations and ivar references need special
4567 // treatment because we're going to recursively rewrite them.
4568 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4569 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4570 return RewritePropertyOrImplicitSetter(PseudoOp);
4571 } else {
4572 return RewritePropertyOrImplicitGetter(PseudoOp);
4573 }
4574 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4575 return RewriteObjCIvarRefExpr(IvarRefExpr);
4576 }
4577
Steve Narofff4b992a2008-10-28 20:29:00 +00004578 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004579
Steve Narofff4b992a2008-10-28 20:29:00 +00004580 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00004581 for (Stmt *&childStmt : S->children())
4582 if (childStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004583 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004584 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004585 childStmt = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004586 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
Steve Narofff4b992a2008-10-28 20:29:00 +00004589 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004590 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004591 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4592 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004593 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004594 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004595 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004597 Stmt *SaveCurrentBody = CurrentBody;
4598 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00004599 PropParentMap = nullptr;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004600 // block literal on rhs of a property-dot-sytax assignment
4601 // must be replaced by its synthesize ast so getRewrittenText
4602 // works as expected. In this case, what actually ends up on RHS
4603 // is the blockTranscribed which is the helper function for the
4604 // block literal; as in: self.c = ^() {[ace ARR];};
4605 bool saveDisableReplaceStmt = DisableReplaceStmt;
4606 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004607 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004608 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004609 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00004610 PropParentMap = nullptr;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004611 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004612 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004613 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004614 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004615
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004616 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4617
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004619 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004620 return blockTranscribed;
4621 }
4622 // Handle specific things.
4623 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4624 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004625
Steve Narofff4b992a2008-10-28 20:29:00 +00004626 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4627 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004628
Steve Narofff4b992a2008-10-28 20:29:00 +00004629 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4630 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004631
Steve Narofff4b992a2008-10-28 20:29:00 +00004632 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004633#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 // Before we rewrite it, put the original message expression in a comment.
4635 SourceLocation startLoc = MessExpr->getLocStart();
4636 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004637
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 const char *startBuf = SM->getCharacterData(startLoc);
4639 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004640
Steve Narofff4b992a2008-10-28 20:29:00 +00004641 std::string messString;
4642 messString += "// ";
4643 messString.append(startBuf, endBuf-startBuf+1);
4644 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004645
4646 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004648 // InsertText(startLoc, messString);
Steve Narofff4b992a2008-10-28 20:29:00 +00004649 // Tried this, but it didn't work either...
4650 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004651#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 return RewriteMessageExpr(MessExpr);
4653 }
Mike Stump11289f42009-09-09 15:08:12 +00004654
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4656 return RewriteObjCTryStmt(StmtTry);
4657
4658 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4659 return RewriteObjCSynchronizedStmt(StmtTry);
4660
4661 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4662 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004663
Steve Narofff4b992a2008-10-28 20:29:00 +00004664 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4665 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004666
4667 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004668 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004669 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004670 OrigStmtRange.getEnd());
4671 if (BreakStmt *StmtBreakStmt =
4672 dyn_cast<BreakStmt>(S))
4673 return RewriteBreakStmt(StmtBreakStmt);
4674 if (ContinueStmt *StmtContinueStmt =
4675 dyn_cast<ContinueStmt>(S))
4676 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004677
4678 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004679 // and cast exprs.
4680 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4681 // FIXME: What we're doing here is modifying the type-specifier that
4682 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004683 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004684 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4685 // the context of an ObjCForCollectionStmt. For example:
4686 // NSArray *someArray;
4687 // for (id <FooProtocol> index in someArray) ;
4688 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4689 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004690 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004691 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004692
Steve Narofff4b992a2008-10-28 20:29:00 +00004693 // Blocks rewrite rules.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004694 for (auto *SD : DS->decls()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004695 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004696 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004698 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004699 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004700 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004701 if (VD->hasAttr<BlocksAttr>()) {
4702 static unsigned uniqueByrefDeclCount = 0;
4703 assert(!BlockByRefDeclNo.count(ND) &&
4704 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4705 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004706 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004707 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004708 else
4709 RewriteTypeOfDecl(VD);
4710 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004711 }
Richard Smithdda56e42011-04-15 14:24:37 +00004712 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004713 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004715 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004716 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4717 }
4718 }
4719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720
Steve Narofff4b992a2008-10-28 20:29:00 +00004721 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4722 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004723
4724 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4726 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004727 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4728 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004729 && "Statement stack mismatch");
4730 Stmts.pop_back();
4731 }
4732 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4734 ValueDecl *VD = DRE->getDecl();
4735 if (VD->hasAttr<BlocksAttr>())
4736 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004737 if (HasLocalVariableExternalStorage(VD))
4738 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004739 }
4740
Steve Narofff4b992a2008-10-28 20:29:00 +00004741 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004742 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004743 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004744 ReplaceStmt(S, BlockCall);
4745 return BlockCall;
4746 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004747 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004748 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 RewriteCastExpr(CE);
4750 }
4751#if 0
4752 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004753 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4754 ICE->getSubExpr(),
4755 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004756 // Get the new text.
4757 std::string SStr;
4758 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004759 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004760 const std::string &Str = Buf.str();
4761
4762 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004763 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Steve Narofff4b992a2008-10-28 20:29:00 +00004764 delete S;
4765 return Replacement;
4766 }
4767#endif
4768 // Return this stmt unmodified.
4769 return S;
4770}
4771
Steve Naroffe70a52a2009-12-05 15:55:59 +00004772void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004773 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004774 if (isTopLevelBlockPointerType(FD->getType()))
4775 RewriteBlockPointerDecl(FD);
4776 if (FD->getType()->isObjCQualifiedIdType() ||
4777 FD->getType()->isObjCQualifiedInterfaceType())
4778 RewriteObjCQualifiedInterfaceTypes(FD);
4779 }
4780}
4781
Steve Narofff4b992a2008-10-28 20:29:00 +00004782/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4783/// main file of the input.
4784void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004785 switch (D->getKind()) {
4786 case Decl::Function: {
4787 FunctionDecl *FD = cast<FunctionDecl>(D);
4788 if (FD->isOverloadedOperator())
4789 return;
Mike Stump11289f42009-09-09 15:08:12 +00004790
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004791 // Since function prototypes don't have ParmDecl's, we check the function
4792 // prototype. This enables us to rewrite function declarations and
4793 // definitions using the same code.
4794 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004795
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004796 if (!FD->isThisDeclarationADefinition())
4797 break;
4798
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004799 // FIXME: If this should support Obj-C++, support CXXTryStmt
4800 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4801 CurFunctionDef = FD;
4802 CurFunctionDeclToDeclareForBlock = FD;
4803 CurrentBody = Body;
4804 Body =
4805 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4806 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004807 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004808 if (PropParentMap) {
4809 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004810 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004811 }
4812 // This synthesizes and inserts the block "impl" struct, invoke function,
4813 // and any copy/dispose helper functions.
4814 InsertBlockLiteralsWithinFunction(FD);
Craig Topper8ae12032014-05-07 06:21:57 +00004815 CurFunctionDef = nullptr;
4816 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004817 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004818 break;
Mike Stump11289f42009-09-09 15:08:12 +00004819 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004820 case Decl::ObjCMethod: {
4821 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4822 if (CompoundStmt *Body = MD->getCompoundBody()) {
4823 CurMethodDef = MD;
4824 CurrentBody = Body;
4825 Body =
4826 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4827 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004828 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004829 if (PropParentMap) {
4830 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004831 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004832 }
4833 InsertBlockLiteralsWithinMethod(MD);
Craig Topper8ae12032014-05-07 06:21:57 +00004834 CurMethodDef = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004835 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004836 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004838 case Decl::ObjCImplementation: {
4839 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4840 ClassImplementation.push_back(CI);
4841 break;
4842 }
4843 case Decl::ObjCCategoryImpl: {
4844 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4845 CategoryImplementation.push_back(CI);
4846 break;
4847 }
4848 case Decl::Var: {
4849 VarDecl *VD = cast<VarDecl>(D);
4850 RewriteObjCQualifiedInterfaceTypes(VD);
4851 if (isTopLevelBlockPointerType(VD->getType()))
4852 RewriteBlockPointerDecl(VD);
4853 else if (VD->getType()->isFunctionPointerType()) {
4854 CheckFunctionPointerDecl(VD->getType(), VD);
4855 if (VD->getInit()) {
4856 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4857 RewriteCastExpr(CE);
4858 }
4859 }
4860 } else if (VD->getType()->isRecordType()) {
4861 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4862 if (RD->isCompleteDefinition())
4863 RewriteRecordBody(RD);
4864 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004866 GlobalVarDecl = VD;
4867 CurrentBody = VD->getInit();
4868 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00004869 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004870 if (PropParentMap) {
4871 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004872 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004873 }
4874 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00004875 GlobalVarDecl = nullptr;
4876
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004877 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004878 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004879 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004880 }
4881 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004882 break;
4883 }
4884 case Decl::TypeAlias:
4885 case Decl::Typedef: {
4886 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4887 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4888 RewriteBlockPointerDecl(TD);
4889 else if (TD->getUnderlyingType()->isFunctionPointerType())
4890 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4891 }
4892 break;
4893 }
4894 case Decl::CXXRecord:
4895 case Decl::Record: {
4896 RecordDecl *RD = cast<RecordDecl>(D);
4897 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004898 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004899 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004901 default:
4902 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004903 }
4904 // Nothing yet.
4905}
4906
Chris Lattnercf169832009-03-28 04:11:33 +00004907void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004908 if (Diags.hasErrorOccurred())
4909 return;
Mike Stump11289f42009-09-09 15:08:12 +00004910
Steve Narofff4b992a2008-10-28 20:29:00 +00004911 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004912
Steve Naroffd9803712009-04-29 16:37:50 +00004913 // Here's a great place to add any extra declarations that may be needed.
4914 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00004915 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4916 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
Steve Naroffd9803712009-04-29 16:37:50 +00004917
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004918 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004919 if (ClassImplementation.size() || CategoryImplementation.size())
4920 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004921
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4923 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004924 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 Rewrite.getRewriteBufferFor(MainFileID)) {
4926 //printf("Changed:\n");
4927 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4928 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004929 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004931
Steve Naroffd9803712009-04-29 16:37:50 +00004932 if (ClassImplementation.size() || CategoryImplementation.size() ||
4933 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004934 // Rewrite Objective-c meta data*
4935 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00004936 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004937 // Emit metadata.
4938 *OutFile << ResultStr;
4939 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004940 OutFile->flush();
4941}
Fariborz Jahanian83077422011-12-08 18:25:15 +00004942
4943void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4944 InitializeCommon(context);
4945
4946 // declaring objc_selector outside the parameter list removes a silly
4947 // scope related warning...
4948 if (IsHeader)
4949 Preamble = "#pragma once\n";
4950 Preamble += "struct objc_selector; struct objc_class;\n";
4951 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4952 Preamble += "struct objc_object *superClass; ";
4953 if (LangOpts.MicrosoftExt) {
4954 // Add a constructor for creating temporary objects.
4955 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4956 ": ";
4957 Preamble += "object(o), superClass(s) {} ";
4958 }
4959 Preamble += "};\n";
4960 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4961 Preamble += "typedef struct objc_object Protocol;\n";
4962 Preamble += "#define _REWRITER_typedef_Protocol\n";
4963 Preamble += "#endif\n";
4964 if (LangOpts.MicrosoftExt) {
4965 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4966 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4967 } else
4968 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4969 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4970 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4971 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4972 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4973 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4974 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4975 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4976 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4977 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4978 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4979 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4980 Preamble += "(const char *);\n";
4981 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4982 Preamble += "(struct objc_class *);\n";
4983 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4984 Preamble += "(const char *);\n";
4985 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4986 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4987 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4988 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4989 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4990 Preamble += "(struct objc_class *, struct objc_object *);\n";
4991 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00004992 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4993 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00004994 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4995 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4996 Preamble += "struct __objcFastEnumerationState {\n\t";
4997 Preamble += "unsigned long state;\n\t";
4998 Preamble += "void **itemsPtr;\n\t";
4999 Preamble += "unsigned long *mutationsPtr;\n\t";
5000 Preamble += "unsigned long extra[5];\n};\n";
5001 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5002 Preamble += "#define __FASTENUMERATIONSTATE\n";
5003 Preamble += "#endif\n";
5004 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5005 Preamble += "struct __NSConstantStringImpl {\n";
5006 Preamble += " int *isa;\n";
5007 Preamble += " int flags;\n";
5008 Preamble += " char *str;\n";
5009 Preamble += " long length;\n";
5010 Preamble += "};\n";
5011 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5012 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5013 Preamble += "#else\n";
5014 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5015 Preamble += "#endif\n";
5016 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5017 Preamble += "#endif\n";
5018 // Blocks preamble.
5019 Preamble += "#ifndef BLOCK_IMPL\n";
5020 Preamble += "#define BLOCK_IMPL\n";
5021 Preamble += "struct __block_impl {\n";
5022 Preamble += " void *isa;\n";
5023 Preamble += " int Flags;\n";
5024 Preamble += " int Reserved;\n";
5025 Preamble += " void *FuncPtr;\n";
5026 Preamble += "};\n";
5027 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5028 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5029 Preamble += "extern \"C\" __declspec(dllexport) "
5030 "void _Block_object_assign(void *, const void *, const int);\n";
5031 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5032 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5033 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5034 Preamble += "#else\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5036 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5037 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5039 Preamble += "#endif\n";
5040 Preamble += "#endif\n";
5041 if (LangOpts.MicrosoftExt) {
5042 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5043 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5044 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5045 Preamble += "#define __attribute__(X)\n";
5046 Preamble += "#endif\n";
5047 Preamble += "#define __weak\n";
5048 }
5049 else {
5050 Preamble += "#define __block\n";
5051 Preamble += "#define __weak\n";
5052 }
5053 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5054 // as this avoids warning in any 64bit/32bit compilation model.
5055 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5056}
5057
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00005058/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian83077422011-12-08 18:25:15 +00005059/// ivar offset.
5060void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5061 std::string &Result) {
5062 if (ivar->isBitField()) {
5063 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5064 // place all bitfields at offset 0.
5065 Result += "0";
5066 } else {
5067 Result += "__OFFSETOFIVAR__(struct ";
5068 Result += ivar->getContainingInterface()->getNameAsString();
5069 if (LangOpts.MicrosoftExt)
5070 Result += "_IMPL";
5071 Result += ", ";
5072 Result += ivar->getNameAsString();
5073 Result += ")";
5074 }
5075}
5076
5077/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5078void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5079 ObjCProtocolDecl *PDecl, StringRef prefix,
5080 StringRef ClassName, std::string &Result) {
5081 static bool objc_protocol_methods = false;
5082
5083 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005084 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005085 /* struct protocol_methods {
5086 SEL _cmd;
5087 char *method_types;
5088 }
5089 */
5090 Result += "\nstruct _protocol_methods {\n";
5091 Result += "\tstruct objc_selector *_cmd;\n";
5092 Result += "\tchar *method_types;\n";
5093 Result += "};\n";
5094
5095 objc_protocol_methods = true;
5096 }
5097 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005098 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005099 return;
5100
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005101 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5102 PDecl = Def;
5103
Fariborz Jahanian83077422011-12-08 18:25:15 +00005104 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5105 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5106 PDecl->instmeth_end());
5107 /* struct _objc_protocol_method_list {
5108 int protocol_method_count;
5109 struct protocol_methods protocols[];
5110 }
5111 */
5112 Result += "\nstatic struct {\n";
5113 Result += "\tint protocol_method_count;\n";
5114 Result += "\tstruct _protocol_methods protocol_methods[";
5115 Result += utostr(NumMethods);
5116 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5117 Result += PDecl->getNameAsString();
5118 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5119 "{\n\t" + utostr(NumMethods) + "\n";
5120
5121 // Output instance methods declared in this protocol.
5122 for (ObjCProtocolDecl::instmeth_iterator
5123 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5124 I != E; ++I) {
5125 if (I == PDecl->instmeth_begin())
5126 Result += "\t ,{{(struct objc_selector *)\"";
5127 else
5128 Result += "\t ,{(struct objc_selector *)\"";
5129 Result += (*I)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005130 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005131 Result += "\", \"";
5132 Result += MethodTypeString;
5133 Result += "\"}\n";
5134 }
5135 Result += "\t }\n};\n";
5136 }
5137
5138 // Output class methods declared in this protocol.
5139 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5140 PDecl->classmeth_end());
5141 if (NumMethods > 0) {
5142 /* struct _objc_protocol_method_list {
5143 int protocol_method_count;
5144 struct protocol_methods protocols[];
5145 }
5146 */
5147 Result += "\nstatic struct {\n";
5148 Result += "\tint protocol_method_count;\n";
5149 Result += "\tstruct _protocol_methods protocol_methods[";
5150 Result += utostr(NumMethods);
5151 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5152 Result += PDecl->getNameAsString();
5153 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5154 "{\n\t";
5155 Result += utostr(NumMethods);
5156 Result += "\n";
5157
5158 // Output instance methods declared in this protocol.
5159 for (ObjCProtocolDecl::classmeth_iterator
5160 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5161 I != E; ++I) {
5162 if (I == PDecl->classmeth_begin())
5163 Result += "\t ,{{(struct objc_selector *)\"";
5164 else
5165 Result += "\t ,{(struct objc_selector *)\"";
5166 Result += (*I)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005167 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005168 Result += "\", \"";
5169 Result += MethodTypeString;
5170 Result += "\"}\n";
5171 }
5172 Result += "\t }\n};\n";
5173 }
5174
5175 // Output:
5176 /* struct _objc_protocol {
5177 // Objective-C 1.0 extensions
5178 struct _objc_protocol_extension *isa;
5179 char *protocol_name;
5180 struct _objc_protocol **protocol_list;
5181 struct _objc_protocol_method_list *instance_methods;
5182 struct _objc_protocol_method_list *class_methods;
5183 };
5184 */
5185 static bool objc_protocol = false;
5186 if (!objc_protocol) {
5187 Result += "\nstruct _objc_protocol {\n";
5188 Result += "\tstruct _objc_protocol_extension *isa;\n";
5189 Result += "\tchar *protocol_name;\n";
5190 Result += "\tstruct _objc_protocol **protocol_list;\n";
5191 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5192 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5193 Result += "};\n";
5194
5195 objc_protocol = true;
5196 }
5197
5198 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5199 Result += PDecl->getNameAsString();
5200 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5201 "{\n\t0, \"";
5202 Result += PDecl->getNameAsString();
5203 Result += "\", 0, ";
5204 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5205 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5206 Result += PDecl->getNameAsString();
5207 Result += ", ";
5208 }
5209 else
5210 Result += "0, ";
5211 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5212 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5213 Result += PDecl->getNameAsString();
5214 Result += "\n";
5215 }
5216 else
5217 Result += "0\n";
5218 Result += "};\n";
5219
5220 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00005221 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005222 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian83077422011-12-08 18:25:15 +00005223}
5224
5225void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5226 const ObjCList<ObjCProtocolDecl> &Protocols,
5227 StringRef prefix, StringRef ClassName,
5228 std::string &Result) {
5229 if (Protocols.empty()) return;
5230
5231 for (unsigned i = 0; i != Protocols.size(); i++)
5232 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5233
5234 // Output the top lovel protocol meta-data for the class.
5235 /* struct _objc_protocol_list {
5236 struct _objc_protocol_list *next;
5237 int protocol_count;
5238 struct _objc_protocol *class_protocols[];
5239 }
5240 */
5241 Result += "\nstatic struct {\n";
5242 Result += "\tstruct _objc_protocol_list *next;\n";
5243 Result += "\tint protocol_count;\n";
5244 Result += "\tstruct _objc_protocol *class_protocols[";
5245 Result += utostr(Protocols.size());
5246 Result += "];\n} _OBJC_";
5247 Result += prefix;
5248 Result += "_PROTOCOLS_";
5249 Result += ClassName;
5250 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5251 "{\n\t0, ";
5252 Result += utostr(Protocols.size());
5253 Result += "\n";
5254
5255 Result += "\t,{&_OBJC_PROTOCOL_";
5256 Result += Protocols[0]->getNameAsString();
5257 Result += " \n";
5258
5259 for (unsigned i = 1; i != Protocols.size(); i++) {
5260 Result += "\t ,&_OBJC_PROTOCOL_";
5261 Result += Protocols[i]->getNameAsString();
5262 Result += "\n";
5263 }
5264 Result += "\t }\n};\n";
5265}
5266
5267void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5268 std::string &Result) {
5269 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5270
5271 // Explicitly declared @interface's are already synthesized.
5272 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005273 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005274 // produce correct synthesis as yet.
5275 RewriteObjCInternalStruct(CDecl, Result);
5276 }
5277
5278 // Build _objc_ivar_list metadata for classes ivars if needed
5279 unsigned NumIvars = !IDecl->ivar_empty()
5280 ? IDecl->ivar_size()
5281 : (CDecl ? CDecl->ivar_size() : 0);
5282 if (NumIvars > 0) {
5283 static bool objc_ivar = false;
5284 if (!objc_ivar) {
5285 /* struct _objc_ivar {
5286 char *ivar_name;
5287 char *ivar_type;
5288 int ivar_offset;
5289 };
5290 */
5291 Result += "\nstruct _objc_ivar {\n";
5292 Result += "\tchar *ivar_name;\n";
5293 Result += "\tchar *ivar_type;\n";
5294 Result += "\tint ivar_offset;\n";
5295 Result += "};\n";
5296
5297 objc_ivar = true;
5298 }
5299
5300 /* struct {
5301 int ivar_count;
5302 struct _objc_ivar ivar_list[nIvars];
5303 };
5304 */
5305 Result += "\nstatic struct {\n";
5306 Result += "\tint ivar_count;\n";
5307 Result += "\tstruct _objc_ivar ivar_list[";
5308 Result += utostr(NumIvars);
5309 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5310 Result += IDecl->getNameAsString();
5311 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5312 "{\n\t";
5313 Result += utostr(NumIvars);
5314 Result += "\n";
5315
5316 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5317 SmallVector<ObjCIvarDecl *, 8> IVars;
5318 if (!IDecl->ivar_empty()) {
Aaron Ballmand6d25de2014-03-14 15:16:45 +00005319 for (auto *IV : IDecl->ivars())
5320 IVars.push_back(IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005321 IVI = IDecl->ivar_begin();
5322 IVE = IDecl->ivar_end();
5323 } else {
5324 IVI = CDecl->ivar_begin();
5325 IVE = CDecl->ivar_end();
5326 }
5327 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005328 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005329 Result += "\", \"";
5330 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005331 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005332 QuoteDoublequotes(TmpString, StrEncoding);
5333 Result += StrEncoding;
5334 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005335 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005336 Result += "}\n";
5337 for (++IVI; IVI != IVE; ++IVI) {
5338 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005339 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005340 Result += "\", \"";
5341 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005342 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005343 QuoteDoublequotes(TmpString, StrEncoding);
5344 Result += StrEncoding;
5345 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005346 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005347 Result += "}\n";
5348 }
5349
5350 Result += "\t }\n};\n";
5351 }
5352
5353 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005354 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005355
5356 // If any of our property implementations have associated getters or
5357 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005358 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005359 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005360 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005361 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005362 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005363 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005364 if (!PD)
5365 continue;
5366 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5367 if (!Getter->isDefined())
5368 InstanceMethods.push_back(Getter);
5369 if (PD->isReadOnly())
5370 continue;
5371 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5372 if (!Setter->isDefined())
5373 InstanceMethods.push_back(Setter);
5374 }
5375 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5376 true, "", IDecl->getName(), Result);
5377
5378 // Build _objc_method_list for class's class methods if needed
5379 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5380 false, "", IDecl->getName(), Result);
5381
5382 // Protocols referenced in class declaration?
5383 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5384 "CLASS", CDecl->getName(), Result);
5385
5386 // Declaration of class/meta-class metadata
5387 /* struct _objc_class {
5388 struct _objc_class *isa; // or const char *root_class_name when metadata
5389 const char *super_class_name;
5390 char *name;
5391 long version;
5392 long info;
5393 long instance_size;
5394 struct _objc_ivar_list *ivars;
5395 struct _objc_method_list *methods;
5396 struct objc_cache *cache;
5397 struct objc_protocol_list *protocols;
5398 const char *ivar_layout;
5399 struct _objc_class_ext *ext;
5400 };
5401 */
5402 static bool objc_class = false;
5403 if (!objc_class) {
5404 Result += "\nstruct _objc_class {\n";
5405 Result += "\tstruct _objc_class *isa;\n";
5406 Result += "\tconst char *super_class_name;\n";
5407 Result += "\tchar *name;\n";
5408 Result += "\tlong version;\n";
5409 Result += "\tlong info;\n";
5410 Result += "\tlong instance_size;\n";
5411 Result += "\tstruct _objc_ivar_list *ivars;\n";
5412 Result += "\tstruct _objc_method_list *methods;\n";
5413 Result += "\tstruct objc_cache *cache;\n";
5414 Result += "\tstruct _objc_protocol_list *protocols;\n";
5415 Result += "\tconst char *ivar_layout;\n";
5416 Result += "\tstruct _objc_class_ext *ext;\n";
5417 Result += "};\n";
5418 objc_class = true;
5419 }
5420
5421 // Meta-class metadata generation.
Craig Topper8ae12032014-05-07 06:21:57 +00005422 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005423 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5424 while (SuperClass) {
5425 RootClass = SuperClass;
5426 SuperClass = SuperClass->getSuperClass();
5427 }
5428 SuperClass = CDecl->getSuperClass();
5429
5430 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5431 Result += CDecl->getNameAsString();
5432 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5433 "{\n\t(struct _objc_class *)\"";
5434 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5435 Result += "\"";
5436
5437 if (SuperClass) {
5438 Result += ", \"";
5439 Result += SuperClass->getNameAsString();
5440 Result += "\", \"";
5441 Result += CDecl->getNameAsString();
5442 Result += "\"";
5443 }
5444 else {
5445 Result += ", 0, \"";
5446 Result += CDecl->getNameAsString();
5447 Result += "\"";
5448 }
5449 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5450 // 'info' field is initialized to CLS_META(2) for metaclass
5451 Result += ", 0,2, sizeof(struct _objc_class), 0";
5452 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5453 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5454 Result += IDecl->getNameAsString();
5455 Result += "\n";
5456 }
5457 else
5458 Result += ", 0\n";
5459 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5460 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5461 Result += CDecl->getNameAsString();
5462 Result += ",0,0\n";
5463 }
5464 else
5465 Result += "\t,0,0,0,0\n";
5466 Result += "};\n";
5467
5468 // class metadata generation.
5469 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5470 Result += CDecl->getNameAsString();
5471 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5472 "{\n\t&_OBJC_METACLASS_";
5473 Result += CDecl->getNameAsString();
5474 if (SuperClass) {
5475 Result += ", \"";
5476 Result += SuperClass->getNameAsString();
5477 Result += "\", \"";
5478 Result += CDecl->getNameAsString();
5479 Result += "\"";
5480 }
5481 else {
5482 Result += ", 0, \"";
5483 Result += CDecl->getNameAsString();
5484 Result += "\"";
5485 }
5486 // 'info' field is initialized to CLS_CLASS(1) for class
5487 Result += ", 0,1";
5488 if (!ObjCSynthesizedStructs.count(CDecl))
5489 Result += ",0";
5490 else {
5491 // class has size. Must synthesize its size.
5492 Result += ",sizeof(struct ";
5493 Result += CDecl->getNameAsString();
5494 if (LangOpts.MicrosoftExt)
5495 Result += "_IMPL";
5496 Result += ")";
5497 }
5498 if (NumIvars > 0) {
5499 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5500 Result += CDecl->getNameAsString();
5501 Result += "\n\t";
5502 }
5503 else
5504 Result += ",0";
5505 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5506 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5507 Result += CDecl->getNameAsString();
5508 Result += ", 0\n\t";
5509 }
5510 else
5511 Result += ",0,0";
5512 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5513 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5514 Result += CDecl->getNameAsString();
5515 Result += ", 0,0\n";
5516 }
5517 else
5518 Result += ",0,0,0\n";
5519 Result += "};\n";
5520}
5521
5522void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5523 int ClsDefCount = ClassImplementation.size();
5524 int CatDefCount = CategoryImplementation.size();
5525
5526 // For each implemented class, write out all its meta data.
5527 for (int i = 0; i < ClsDefCount; i++)
5528 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5529
5530 // For each implemented category, write out all its meta data.
5531 for (int i = 0; i < CatDefCount; i++)
5532 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5533
5534 // Write objc_symtab metadata
5535 /*
5536 struct _objc_symtab
5537 {
5538 long sel_ref_cnt;
5539 SEL *refs;
5540 short cls_def_cnt;
5541 short cat_def_cnt;
5542 void *defs[cls_def_cnt + cat_def_cnt];
5543 };
5544 */
5545
5546 Result += "\nstruct _objc_symtab {\n";
5547 Result += "\tlong sel_ref_cnt;\n";
5548 Result += "\tSEL *refs;\n";
5549 Result += "\tshort cls_def_cnt;\n";
5550 Result += "\tshort cat_def_cnt;\n";
5551 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5552 Result += "};\n\n";
5553
5554 Result += "static struct _objc_symtab "
5555 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5556 Result += "\t0, 0, " + utostr(ClsDefCount)
5557 + ", " + utostr(CatDefCount) + "\n";
5558 for (int i = 0; i < ClsDefCount; i++) {
5559 Result += "\t,&_OBJC_CLASS_";
5560 Result += ClassImplementation[i]->getNameAsString();
5561 Result += "\n";
5562 }
5563
5564 for (int i = 0; i < CatDefCount; i++) {
5565 Result += "\t,&_OBJC_CATEGORY_";
5566 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5567 Result += "_";
5568 Result += CategoryImplementation[i]->getNameAsString();
5569 Result += "\n";
5570 }
5571
5572 Result += "};\n\n";
5573
5574 // Write objc_module metadata
5575
5576 /*
5577 struct _objc_module {
5578 long version;
5579 long size;
5580 const char *name;
5581 struct _objc_symtab *symtab;
5582 }
5583 */
5584
5585 Result += "\nstruct _objc_module {\n";
5586 Result += "\tlong version;\n";
5587 Result += "\tlong size;\n";
5588 Result += "\tconst char *name;\n";
5589 Result += "\tstruct _objc_symtab *symtab;\n";
5590 Result += "};\n\n";
5591 Result += "static struct _objc_module "
5592 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5593 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5594 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5595 Result += "};\n\n";
5596
5597 if (LangOpts.MicrosoftExt) {
5598 if (ProtocolExprDecls.size()) {
5599 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5600 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Craig Topperc6914d02014-08-25 04:15:02 +00005601 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005602 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005603 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005604 Result += " = &_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005605 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005606 Result += ";\n";
5607 }
5608 Result += "#pragma data_seg(pop)\n\n";
5609 }
5610 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5611 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5612 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5613 Result += "&_OBJC_MODULES;\n";
5614 Result += "#pragma data_seg(pop)\n\n";
5615 }
5616}
5617
5618/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5619/// implementation.
5620void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5621 std::string &Result) {
5622 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5623 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005624 ObjCCategoryDecl *CDecl
5625 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005626
5627 std::string FullCategoryName = ClassDecl->getNameAsString();
5628 FullCategoryName += '_';
5629 FullCategoryName += IDecl->getNameAsString();
5630
5631 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005632 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005633
5634 // If any of our property implementations have associated getters or
5635 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005636 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005637 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005638 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005639 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005640 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005641 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005642 if (!PD)
5643 continue;
5644 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5645 InstanceMethods.push_back(Getter);
5646 if (PD->isReadOnly())
5647 continue;
5648 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5649 InstanceMethods.push_back(Setter);
5650 }
5651 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005652 true, "CATEGORY_", FullCategoryName, Result);
5653
Fariborz Jahanian83077422011-12-08 18:25:15 +00005654 // Build _objc_method_list for class's class methods if needed
5655 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005656 false, "CATEGORY_", FullCategoryName, Result);
5657
Fariborz Jahanian83077422011-12-08 18:25:15 +00005658 // Protocols referenced in class declaration?
5659 // Null CDecl is case of a category implementation with no category interface
5660 if (CDecl)
5661 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5662 FullCategoryName, Result);
5663 /* struct _objc_category {
5664 char *category_name;
5665 char *class_name;
5666 struct _objc_method_list *instance_methods;
5667 struct _objc_method_list *class_methods;
5668 struct _objc_protocol_list *protocols;
5669 // Objective-C 1.0 extensions
5670 uint32_t size; // sizeof (struct _objc_category)
5671 struct _objc_property_list *instance_properties; // category's own
5672 // @property decl.
5673 };
5674 */
5675
5676 static bool objc_category = false;
5677 if (!objc_category) {
5678 Result += "\nstruct _objc_category {\n";
5679 Result += "\tchar *category_name;\n";
5680 Result += "\tchar *class_name;\n";
5681 Result += "\tstruct _objc_method_list *instance_methods;\n";
5682 Result += "\tstruct _objc_method_list *class_methods;\n";
5683 Result += "\tstruct _objc_protocol_list *protocols;\n";
5684 Result += "\tunsigned int size;\n";
5685 Result += "\tstruct _objc_property_list *instance_properties;\n";
5686 Result += "};\n";
5687 objc_category = true;
5688 }
5689 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5690 Result += FullCategoryName;
5691 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5692 Result += IDecl->getNameAsString();
5693 Result += "\"\n\t, \"";
5694 Result += ClassDecl->getNameAsString();
5695 Result += "\"\n";
5696
5697 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5698 Result += "\t, (struct _objc_method_list *)"
5699 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5700 Result += FullCategoryName;
5701 Result += "\n";
5702 }
5703 else
5704 Result += "\t, 0\n";
5705 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5706 Result += "\t, (struct _objc_method_list *)"
5707 "&_OBJC_CATEGORY_CLASS_METHODS_";
5708 Result += FullCategoryName;
5709 Result += "\n";
5710 }
5711 else
5712 Result += "\t, 0\n";
5713
5714 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5715 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5716 Result += FullCategoryName;
5717 Result += "\n";
5718 }
5719 else
5720 Result += "\t, 0\n";
5721 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5722}
5723
5724// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5725/// class methods.
5726template<typename MethodIterator>
5727void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5728 MethodIterator MethodEnd,
5729 bool IsInstanceMethod,
5730 StringRef prefix,
5731 StringRef ClassName,
5732 std::string &Result) {
5733 if (MethodBegin == MethodEnd) return;
5734
5735 if (!objc_impl_method) {
5736 /* struct _objc_method {
5737 SEL _cmd;
5738 char *method_types;
5739 void *_imp;
5740 }
5741 */
5742 Result += "\nstruct _objc_method {\n";
5743 Result += "\tSEL _cmd;\n";
5744 Result += "\tchar *method_types;\n";
5745 Result += "\tvoid *_imp;\n";
5746 Result += "};\n";
5747
5748 objc_impl_method = true;
5749 }
5750
5751 // Build _objc_method_list for class's methods if needed
5752
5753 /* struct {
5754 struct _objc_method_list *next_method;
5755 int method_count;
5756 struct _objc_method method_list[];
5757 }
5758 */
5759 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5760 Result += "\nstatic struct {\n";
5761 Result += "\tstruct _objc_method_list *next_method;\n";
5762 Result += "\tint method_count;\n";
5763 Result += "\tstruct _objc_method method_list[";
5764 Result += utostr(NumMethods);
5765 Result += "];\n} _OBJC_";
5766 Result += prefix;
5767 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5768 Result += "_METHODS_";
5769 Result += ClassName;
5770 Result += " __attribute__ ((used, section (\"__OBJC, __";
5771 Result += IsInstanceMethod ? "inst" : "cls";
5772 Result += "_meth\")))= ";
5773 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5774
5775 Result += "\t,{{(SEL)\"";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005776 Result += (*MethodBegin)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005777 std::string MethodTypeString =
5778 Context->getObjCEncodingForMethodDecl(*MethodBegin);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005779 Result += "\", \"";
5780 Result += MethodTypeString;
5781 Result += "\", (void *)";
5782 Result += MethodInternalNames[*MethodBegin];
5783 Result += "}\n";
5784 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5785 Result += "\t ,{(SEL)\"";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005786 Result += (*MethodBegin)->getSelector().getAsString();
John McCall843dfcc2016-11-29 21:57:00 +00005787 std::string MethodTypeString =
5788 Context->getObjCEncodingForMethodDecl(*MethodBegin);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005789 Result += "\", \"";
5790 Result += MethodTypeString;
5791 Result += "\", (void *)";
5792 Result += MethodInternalNames[*MethodBegin];
5793 Result += "}\n";
5794 }
5795 Result += "\t }\n};\n";
5796}
5797
5798Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5799 SourceRange OldRange = IV->getSourceRange();
5800 Expr *BaseExpr = IV->getBase();
5801
5802 // Rewrite the base, but without actually doing replaces.
5803 {
5804 DisableReplaceStmtScope S(*this);
5805 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5806 IV->setBase(BaseExpr);
5807 }
5808
5809 ObjCIvarDecl *D = IV->getDecl();
5810
5811 Expr *Replacement = IV;
5812 if (CurMethodDef) {
5813 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5814 const ObjCInterfaceType *iFaceDecl =
5815 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5816 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5817 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005818 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005819 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5820 clsDeclared);
5821 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5822
5823 // Synthesize an explicit cast to gain access to the ivar.
5824 std::string RecName = clsDeclared->getIdentifier()->getName();
5825 RecName += "_IMPL";
5826 IdentifierInfo *II = &Context->Idents.get(RecName);
5827 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5828 SourceLocation(), SourceLocation(),
5829 II);
5830 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5831 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5832 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5833 CK_BitCast,
5834 IV->getBase());
5835 // Don't forget the parens to enforce the proper binding.
5836 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5837 OldRange.getEnd(),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00005838 castExpr);
5839 if (IV->isFreeIvar() &&
5840 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5841 MemberExpr *ME = new (Context)
5842 MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(),
5843 D->getType(), VK_LValue, OK_Ordinary);
5844 Replacement = ME;
5845 } else {
5846 IV->setBase(PE);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005847 }
5848 }
5849 } else { // we are outside a method.
5850 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5851
5852 // Explicit ivar refs need to have a cast inserted.
5853 // FIXME: consider sharing some of this code with the code above.
5854 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5855 const ObjCInterfaceType *iFaceDecl =
5856 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5857 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005858 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005859 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5860 clsDeclared);
5861 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5862
5863 // Synthesize an explicit cast to gain access to the ivar.
5864 std::string RecName = clsDeclared->getIdentifier()->getName();
5865 RecName += "_IMPL";
5866 IdentifierInfo *II = &Context->Idents.get(RecName);
5867 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5868 SourceLocation(), SourceLocation(),
5869 II);
5870 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5871 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5872 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5873 CK_BitCast,
5874 IV->getBase());
5875 // Don't forget the parens to enforce the proper binding.
5876 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5877 IV->getBase()->getLocEnd(), castExpr);
5878 // Cannot delete IV->getBase(), since PE points to it.
5879 // Replace the old base with the cast. This is important when doing
5880 // embedded rewrites. For example, [newInv->_container addObject:0].
5881 IV->setBase(PE);
5882 }
5883 }
5884
5885 ReplaceStmtWithRange(IV, Replacement, OldRange);
5886 return Replacement;
5887}
Alp Toker0621cb22014-07-16 16:48:33 +00005888
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005889#endif // CLANG_ENABLE_OBJC_REWRITER