blob: c46ba9832c0de38b621d290219c226e557c00fb5 [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
Fariborz Jahanian11671902012-02-07 17:11:38 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Fariborz Jahanian11671902012-02-07 17:11:38 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Hacks and fun related to the code rewriter.
10//
11//===----------------------------------------------------------------------===//
12
Ted Kremenekcdf81492012-09-01 05:09:24 +000013#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000014#include "clang/AST/AST.h"
15#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000017#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
NAKAMURA Takumi7f633df2017-07-18 08:55:03 +000023#include "clang/Config/config.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +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"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
NAKAMURA Takumid9739822017-10-18 05:21:17 +000033#if CLANG_ENABLE_OBJC_REWRITER
Alp Toker0621cb22014-07-16 16:48:33 +000034
Fariborz Jahanian11671902012-02-07 17:11:38 +000035using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
Fangrui Song6907ce22018-07-30 19:24:48 +000041
Fariborz Jahanian11671902012-02-07 17:11:38 +000042 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
Fangrui Song6907ce22018-07-30 19:24:48 +000046 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
Fariborz Jahanian11671902012-02-07 17:11:38 +000047 __block variable */
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 helpers */
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 support routines */
52 BLOCK_BYREF_CURRENT_MAX = 256
53 };
Fangrui Song6907ce22018-07-30 19:24:48 +000054
Fariborz Jahanian11671902012-02-07 17:11:38 +000055 enum {
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 };
Fangrui Song6907ce22018-07-30 19:24:48 +000063
Fariborz Jahanian11671902012-02-07 17:11:38 +000064 Rewriter Rewrite;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
67 ASTContext *Context;
68 SourceManager *SM;
69 TranslationUnitDecl *TUDecl;
70 FileID MainFileID;
71 const char *MainFileStart, *MainFileEnd;
72 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
Peter Collingbourne03f89072016-07-15 00:55:40 +000075 std::unique_ptr<raw_ostream> OutFile;
Fariborz Jahanian11671902012-02-07 17:11:38 +000076 std::string Preamble;
Fangrui Song6907ce22018-07-30 19:24:48 +000077
Fariborz Jahanian11671902012-02-07 17:11:38 +000078 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000080 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000082 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000083 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
87
88 // ObjC foreach break/continue generation support.
89 int BcLabelCount;
Fangrui Song6907ce22018-07-30 19:24:48 +000090
Fariborz Jahanian11671902012-02-07 17:11:38 +000091 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +000096
Fariborz Jahanian11671902012-02-07 17:11:38 +000097 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000107 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000108 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000109
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
Fangrui Song6907ce22018-07-30 19:24:48 +0000120
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fangrui Song6907ce22018-07-30 19:24:48 +0000123
Fariborz Jahanian11671902012-02-07 17:11:38 +0000124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000128
Fariborz Jahanian11671902012-02-07 17:11:38 +0000129 llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000135
John McCall113bee02012-03-10 09:33:50 +0000136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137
138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000146
Fariborz Jahanian11671902012-02-07 17:11:38 +0000147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
Mandeep Singh Granga2baff02017-07-06 18:49:57 +0000149 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fangrui Song6907ce22018-07-30 19:24:48 +0000158
Fariborz Jahanian11671902012-02-07 17:11:38 +0000159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000167 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000168 bool objc_impl_method;
Fangrui Song6907ce22018-07-30 19:24:48 +0000169
Fariborz Jahanian11671902012-02-07 17:11:38 +0000170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000174
Fariborz Jahanian11671902012-02-07 17:11:38 +0000175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000188
Fariborz Jahanian11671902012-02-07 17:11:38 +0000189 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000190 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193 if (!Class->isThisDeclarationADefinition()) {
194 RewriteForwardClassDecl(D);
195 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000196 } else {
197 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000198 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000199 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000200 }
201 }
202
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
206 break;
207 }
208 }
209
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211 // Under modern abi, we cannot translate body of the function
212 // yet until all class extensions and its implementation is seen.
213 // This is because they may introduce new bitfields which must go
214 // into their grouping struct.
215 if (FDecl->isThisDeclarationADefinition() &&
216 // Not c functions defined inside an objc container.
217 !FDecl->isTopLevelDeclInObjCContainer()) {
218 FunctionDefinitionsSeen.push_back(FDecl);
219 break;
220 }
221 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000222 HandleTopLevelSingleDecl(*I);
223 }
224 return true;
225 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000226
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231 RewriteBlockPointerDecl(TD);
232 else if (TD->getUnderlyingType()->isFunctionPointerType())
233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234 else
235 RewriteObjCQualifiedInterfaceTypes(TD);
236 }
237 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000238 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000239
Fariborz Jahanian11671902012-02-07 17:11:38 +0000240 void HandleTopLevelSingleDecl(Decl *D);
241 void HandleDeclInMainFile(Decl *D);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000242 RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243 DiagnosticsEngine &D, const LangOptions &LOpts,
244 bool silenceMacroWarn, bool LineInfo);
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000246 ~RewriteModernObjC() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000247
248 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000249
250 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000251 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000255 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000256
257 Stmt *ReplacingStmt = ReplacedNodes[Old];
258 if (ReplacingStmt)
259 return; // We can't rewrite the same node twice.
260
Fariborz Jahanian11671902012-02-07 17:11:38 +0000261 if (DisableReplaceStmt)
262 return;
263
264 // Measure the old text.
265 int Size = Rewrite.getRangeSize(SrcRange);
266 if (Size == -1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000267 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000269 return;
270 }
271 // Get the new text.
272 std::string SStr;
273 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000274 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000275 const std::string &Str = S.str();
276
277 // If replacement succeeded or warning disabled return with no warning.
278 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279 ReplacedNodes[Old] = New;
280 return;
281 }
282 if (SilenceRewriteMacroWarning)
283 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000284 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000286 }
287
288 void InsertText(SourceLocation Loc, StringRef Str,
289 bool InsertAfter = true) {
290 // If insertion succeeded or warning disabled return with no warning.
291 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292 SilenceRewriteMacroWarning)
293 return;
294
295 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296 }
297
298 void ReplaceText(SourceLocation Start, unsigned OrigLength,
299 StringRef Str) {
300 // If removal succeeded or warning disabled return with no warning.
301 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302 SilenceRewriteMacroWarning)
303 return;
304
305 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306 }
307
308 // Syntactic Rewriting.
309 void RewriteRecordBody(RecordDecl *RD);
310 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000311 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000312 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000314 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000315 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fangrui Song6907ce22018-07-30 19:24:48 +0000316 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000317 const std::string &typedefString);
318 void RewriteImplementations();
319 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320 ObjCImplementationDecl *IMD,
321 ObjCCategoryImplDecl *CID);
322 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323 void RewriteImplementationDecl(Decl *Dcl);
324 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325 ObjCMethodDecl *MDecl, std::string &ResultStr);
326 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327 const FunctionType *&FPRetType);
328 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329 ValueDecl *VD, bool def=false);
330 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000333 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000334 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335 void RewriteProperty(ObjCPropertyDecl *prop);
336 void RewriteFunctionDecl(FunctionDecl *FD);
337 void RewriteBlockPointerType(std::string& Str, QualType Type);
338 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000339 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000340 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341 void RewriteTypeOfDecl(VarDecl *VD);
342 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +0000343
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000344 std::string getIvarAccessString(ObjCIvarDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000345
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346 // Expression Rewriting.
347 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000354 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000355 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000356 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000357 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000358 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000360 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000361 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364 SourceLocation OrigEnd);
365 Stmt *RewriteBreakStmt(BreakStmt *S);
366 Stmt *RewriteContinueStmt(ContinueStmt *S);
367 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000368 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fangrui Song6907ce22018-07-30 19:24:48 +0000369
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000370 // Computes ivar bitfield group no.
371 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372 // Names field decl. for ivar bitfield group.
373 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374 // Names struct type for ivar bitfield group.
375 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376 // Names symbol for ivar bitfield group field offset.
377 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378 // Given an ivar bitfield, it builds (or finds) its group record type.
379 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380 QualType SynthesizeBitfieldGroupStructType(
381 ObjCIvarDecl *IV,
382 SmallVectorImpl<ObjCIvarDecl *> &IVars);
Fangrui Song6907ce22018-07-30 19:24:48 +0000383
Fariborz Jahanian11671902012-02-07 17:11:38 +0000384 // Block rewriting.
385 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000386
Fariborz Jahanian11671902012-02-07 17:11:38 +0000387 // Block specific rewrite rules.
388 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000389 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000390 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000391 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fangrui Song6907ce22018-07-30 19:24:48 +0000393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000396
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000397 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000398 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000399 bool &IsNamedDefinition);
Fangrui Song6907ce22018-07-30 19:24:48 +0000400 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000401 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000402
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000403 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000404
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000405 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000407
408 void Initialize(ASTContext &context) override;
409
Benjamin Kramer474261a2012-06-02 10:20:41 +0000410 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000411 // rewriting routines on the new ASTs.
412 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000413 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000414 SourceLocation StartLoc=SourceLocation(),
415 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000416
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000417 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +0000418 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000419 SmallVectorImpl<QualType> &ArgTypes,
420 SmallVectorImpl<Expr*> &MsgExprs,
421 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000422
423 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000426
Fariborz Jahanian11671902012-02-07 17:11:38 +0000427 void SynthCountByEnumWithState(std::string &buf);
428 void SynthMsgSendFunctionDecl();
429 void SynthMsgSendSuperFunctionDecl();
430 void SynthMsgSendStretFunctionDecl();
431 void SynthMsgSendFpretFunctionDecl();
432 void SynthMsgSendSuperStretFunctionDecl();
433 void SynthGetClassFunctionDecl();
434 void SynthGetMetaClassFunctionDecl();
435 void SynthGetSuperClassFunctionDecl();
436 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000437 void SynthSuperConstructorFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000438
Fariborz Jahanian11671902012-02-07 17:11:38 +0000439 // Rewriting metadata
440 template<typename MethodIterator>
441 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442 MethodIterator MethodEnd,
443 bool IsInstanceMethod,
444 StringRef prefix,
445 StringRef ClassName,
446 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000447 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000450 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000451 void RewriteClassSetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000452
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000456 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000457 void RewriteCategorySetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000458
Fariborz Jahanian11671902012-02-07 17:11:38 +0000459 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463
Fangrui Song6907ce22018-07-30 19:24:48 +0000464
Fariborz Jahanian11671902012-02-07 17:11:38 +0000465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
Fangrui Song6907ce22018-07-30 19:24:48 +0000470 std::string SynthesizeBlockImpl(BlockExpr *CE,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471 std::string Tag, std::string Desc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000472 std::string SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000481 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000493 void GetInnerBlockDeclRefExprs(Stmt *S,
494 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000495 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
Simon Pilgrimb1504942019-10-16 10:50:06 +0000508 const auto *BPT = T->castAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000514
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000515 bool convertObjCTypeToCStyleType(QualType &T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000516
Fariborz Jahanian11671902012-02-07 17:11:38 +0000517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000521
Fariborz Jahanian11671902012-02-07 17:11:38 +0000522 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
Fangrui Song6907ce22018-07-30 19:24:48 +0000525 T = isConst ? Context->getObjCIdType().withConst()
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000526 : Context->getObjCIdType();
527 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000540
Fariborz Jahanian11671902012-02-07 17:11:38 +0000541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000543 if (!LangOpts.ObjC)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000559
Fariborz Jahanian11671902012-02-07 17:11:38 +0000560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
Fangrui Song6907ce22018-07-30 19:24:48 +0000564
Fariborz Jahanian11671902012-02-07 17:11:38 +0000565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000575 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000581 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000590 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000591
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000595 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000597
598 StringLiteral *getStringLiteral(StringRef Str) {
599 QualType StrType = Context->getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +0000600 Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
601 ArrayType::Normal, 0);
Benjamin Kramerfc188422014-02-25 12:26:11 +0000602 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603 /*Pascal=*/false, StrType, SourceLocation());
604 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000605 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000606} // end anonymous namespace
Fariborz Jahanian11671902012-02-07 17:11:38 +0000607
608void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609 NamedDecl *D) {
610 if (const FunctionProtoType *fproto
611 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000612 for (const auto &I : fproto->param_types())
613 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000614 // All the args are checked/rewritten. Don't call twice!
615 RewriteBlockPointerDecl(D);
616 break;
617 }
618 }
619}
620
621void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622 const PointerType *PT = funcType->getAs<PointerType>();
623 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625}
626
627static bool IsHeaderFile(const std::string &Filename) {
628 std::string::size_type DotPos = Filename.rfind('.');
629
630 if (DotPos == std::string::npos) {
631 // no file extension
632 return false;
633 }
634
635 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636 // C header: .h
637 // C++ header: .hh or .H;
638 return Ext == "h" || Ext == "hh" || Ext == "H";
639}
640
Peter Collingbourne03f89072016-07-15 00:55:40 +0000641RewriteModernObjC::RewriteModernObjC(std::string inFile,
642 std::unique_ptr<raw_ostream> OS,
643 DiagnosticsEngine &D,
644 const LangOptions &LOpts,
645 bool silenceMacroWarn, bool LineInfo)
646 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000648 IsHeader = IsHeaderFile(inFile);
649 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000651 // FIXME. This should be an error. But if block is not called, it is OK. And it
652 // may break including some headers.
653 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654 "rewriting block literal declared in global scope is not implemented");
Fangrui Song6907ce22018-07-30 19:24:48 +0000655
Fariborz Jahanian11671902012-02-07 17:11:38 +0000656 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657 DiagnosticsEngine::Warning,
658 "rewriter doesn't support user-specified control flow semantics "
659 "for @try/@finally (code may not execute properly)");
660}
661
David Blaikie6beb6aa2014-08-10 19:56:51 +0000662std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000663 const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664 DiagnosticsEngine &Diags, const LangOptions &LOpts,
665 bool SilenceRewriteMacroWarning, bool LineInfo) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000666 return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000667 LOpts, SilenceRewriteMacroWarning,
668 LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000669}
670
671void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672 Context = &context;
673 SM = &Context->getSourceManager();
674 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000675 MsgSendFunctionDecl = nullptr;
676 MsgSendSuperFunctionDecl = nullptr;
677 MsgSendStretFunctionDecl = nullptr;
678 MsgSendSuperStretFunctionDecl = nullptr;
679 MsgSendFpretFunctionDecl = nullptr;
680 GetClassFunctionDecl = nullptr;
681 GetMetaClassFunctionDecl = nullptr;
682 GetSuperClassFunctionDecl = nullptr;
683 SelGetUidFunctionDecl = nullptr;
684 CFStringFunctionDecl = nullptr;
685 ConstantStringClassReference = nullptr;
686 NSStringRecord = nullptr;
687 CurMethodDef = nullptr;
688 CurFunctionDef = nullptr;
689 GlobalVarDecl = nullptr;
690 GlobalConstructionExp = nullptr;
691 SuperStructDecl = nullptr;
692 ProtocolTypeDecl = nullptr;
693 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000694 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000695 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000696 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000697 PropParentMap = nullptr;
698 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 DisableReplaceStmt = false;
700 objc_impl_method = false;
701
702 // Get the ID and start/end of the main file.
703 MainFileID = SM->getMainFileID();
704 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705 MainFileStart = MainBuf->getBufferStart();
706 MainFileEnd = MainBuf->getBufferEnd();
707
David Blaikiebbafb8a2012-03-11 07:00:24 +0000708 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000709}
710
711//===----------------------------------------------------------------------===//
712// Top Level Driver Code
713//===----------------------------------------------------------------------===//
714
715void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716 if (Diags.hasErrorOccurred())
717 return;
718
719 // Two cases: either the decl could be in the main file, or it could be in a
720 // #included file. If the former, rewrite it now. If the later, check to see
721 // if we rewrote the #include/#import.
722 SourceLocation Loc = D->getLocation();
723 Loc = SM->getExpansionLoc(Loc);
724
725 // If this is for a builtin, ignore it.
726 if (Loc.isInvalid()) return;
727
728 // Look for built-in declarations that we need to refer during the rewrite.
729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730 RewriteFunctionDecl(FD);
731 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732 // declared in <Foundation/NSString.h>
733 if (FVD->getName() == "_NSConstantStringClassReference") {
734 ConstantStringClassReference = FVD;
735 return;
736 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000737 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738 RewriteCategoryDecl(CD);
739 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740 if (PD->isThisDeclarationADefinition())
741 RewriteProtocolDecl(PD);
742 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743 // Recurse into linkage specifications
744 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745 DIEnd = LSD->decls_end();
746 DI != DIEnd; ) {
747 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748 if (!IFace->isThisDeclarationADefinition()) {
749 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000750 SourceLocation StartLoc = IFace->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000751 do {
752 if (isa<ObjCInterfaceDecl>(*DI) &&
753 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000754 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000755 DG.push_back(*DI);
756 else
757 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000758
Fariborz Jahanian11671902012-02-07 17:11:38 +0000759 ++DI;
760 } while (DI != DIEnd);
761 RewriteForwardClassDecl(DG);
762 continue;
763 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000764 else {
765 // Keep track of all interface declarations seen.
766 ObjCInterfacesSeen.push_back(IFace);
767 ++DI;
768 continue;
769 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000770 }
771
772 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773 if (!Proto->isThisDeclarationADefinition()) {
774 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000775 SourceLocation StartLoc = Proto->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000776 do {
777 if (isa<ObjCProtocolDecl>(*DI) &&
778 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000779 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000780 DG.push_back(*DI);
781 else
782 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000783
Fariborz Jahanian11671902012-02-07 17:11:38 +0000784 ++DI;
785 } while (DI != DIEnd);
786 RewriteForwardProtocolDecl(DG);
787 continue;
788 }
789 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000790
Fariborz Jahanian11671902012-02-07 17:11:38 +0000791 HandleTopLevelSingleDecl(*DI);
792 ++DI;
793 }
794 }
795 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000796 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000797 return HandleDeclInMainFile(D);
798}
799
800//===----------------------------------------------------------------------===//
801// Syntactic (non-AST) Rewriting Code
802//===----------------------------------------------------------------------===//
803
804void RewriteModernObjC::RewriteInclude() {
805 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806 StringRef MainBuf = SM->getBufferData(MainFileID);
807 const char *MainBufStart = MainBuf.begin();
808 const char *MainBufEnd = MainBuf.end();
809 size_t ImportLen = strlen("import");
810
811 // Loop over the whole file, looking for includes.
812 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
813 if (*BufPtr == '#') {
814 if (++BufPtr == MainBufEnd)
815 return;
816 while (*BufPtr == ' ' || *BufPtr == '\t')
817 if (++BufPtr == MainBufEnd)
818 return;
819 if (!strncmp(BufPtr, "import", ImportLen)) {
820 // replace import with include
821 SourceLocation ImportLoc =
822 LocStart.getLocWithOffset(BufPtr-MainBufStart);
823 ReplaceText(ImportLoc, ImportLen, "include");
824 BufPtr += ImportLen;
825 }
826 }
827 }
828}
829
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000830static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831 ObjCIvarDecl *IvarDecl, std::string &Result) {
832 Result += "OBJC_IVAR_$_";
833 Result += IDecl->getName();
834 Result += "$";
835 Result += IvarDecl->getName();
836}
837
Fangrui Song6907ce22018-07-30 19:24:48 +0000838std::string
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000839RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +0000841
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000842 // Build name of symbol holding ivar offset.
843 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000844 if (D->isBitField())
845 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846 else
847 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +0000848
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000849 std::string S = "(*(";
850 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000851 if (D->isBitField())
852 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000853
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000854 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000855 RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000856 RD = RD->getDefinition();
857 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858 // decltype(((Foo_IMPL*)0)->bar) *
Simon Pilgrimb1504942019-10-16 10:50:06 +0000859 auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000860 // ivar in class extensions requires special treatment.
861 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862 CDecl = CatDecl->getClassInterface();
Benjamin Krameradcd0262020-01-28 20:23:46 +0100863 std::string RecName = std::string(CDecl->getName());
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000864 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000865 RecordDecl *RD =
866 RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
867 SourceLocation(), &Context->Idents.get(RecName));
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000868 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +0000869 unsigned UnsignedIntSize =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000870 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871 Expr *Zero = IntegerLiteral::Create(*Context,
872 llvm::APInt(UnsignedIntSize, 0),
873 Context->UnsignedIntTy, SourceLocation());
874 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000877 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000878 SourceLocation(),
879 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000880 IvarT, nullptr,
881 /*BitWidth=*/nullptr, /*Mutable=*/true,
882 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +0000883 MemberExpr *ME = MemberExpr::CreateImplicit(
884 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000885 IvarT = Context->getDecltypeType(ME, ME->getType());
886 }
887 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000888 convertObjCTypeToCStyleType(IvarT);
889 QualType castT = Context->getPointerType(IvarT);
890 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891 S += TypeString;
892 S += ")";
Fangrui Song6907ce22018-07-30 19:24:48 +0000893
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000894 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895 S += "((char *)self + ";
896 S += IvarOffsetName;
897 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000898 if (D->isBitField()) {
899 S += ".";
900 S += D->getNameAsString();
901 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000902 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000903 return S;
904}
905
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000906/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907/// been found in the class implementation. In this case, it must be synthesized.
908static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909 ObjCPropertyDecl *PD,
910 bool getter) {
Adrian Prantl2073dd22019-11-04 14:28:14 -0800911 auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
912 : PD->getSetterName());
913 return !OMD || OMD->isSynthesizedAccessorStub();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000914}
915
Fariborz Jahanian11671902012-02-07 17:11:38 +0000916void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917 ObjCImplementationDecl *IMD,
918 ObjCCategoryImplDecl *CID) {
919 static bool objcGetPropertyDefined = false;
920 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000921 SourceLocation startGetterSetterLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +0000922
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000923 if (PID->getBeginLoc().isValid()) {
924 SourceLocation startLoc = PID->getBeginLoc();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000925 InsertText(startLoc, "// ");
926 const char *startBuf = SM->getCharacterData(startLoc);
927 assert((*startBuf == '@') && "bogus @synthesize location");
928 const char *semiBuf = strchr(startBuf, ';');
929 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
930 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000931 } else
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000932 startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000933
934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935 return; // FIXME: is this correct?
936
937 // Generate the 'getter' function.
938 ObjCPropertyDecl *PD = PID->getPropertyDecl();
939 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000940 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000941
Bill Wendling44426052012-12-20 19:22:21 +0000942 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000943 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Puyan Lotfi9721fbf2020-04-23 02:20:56 -0400944 bool GenGetProperty =
945 !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
946 (Attributes & (ObjCPropertyAttribute::kind_retain |
947 ObjCPropertyAttribute::kind_copy));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000948 std::string Getr;
949 if (GenGetProperty && !objcGetPropertyDefined) {
950 objcGetPropertyDefined = true;
951 // FIXME. Is this attribute correct in all cases?
952 Getr = "\nextern \"C\" __declspec(dllimport) "
953 "id objc_getProperty(id, SEL, long, bool);\n";
954 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000955 RewriteObjCMethodDecl(OID->getContainingInterface(),
Adrian Prantl2073dd22019-11-04 14:28:14 -0800956 PID->getGetterMethodDecl(), Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957 Getr += "{ ";
958 // Synthesize an explicit cast to gain access to the ivar.
959 // See objc-act.c:objc_synthesize_new_getter() for details.
960 if (GenGetProperty) {
961 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
962 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000963 const FunctionType *FPRetType = nullptr;
Adrian Prantl2073dd22019-11-04 14:28:14 -0800964 RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000965 FPRetType);
966 Getr += " _TYPE";
967 if (FPRetType) {
968 Getr += ")"; // close the precedence "scope" for "*".
Fangrui Song6907ce22018-07-30 19:24:48 +0000969
Fariborz Jahanian11671902012-02-07 17:11:38 +0000970 // Now, emit the argument types (if any).
971 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
972 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000973 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000974 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000975 std::string ParamStr =
976 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000977 Getr += ParamStr;
978 }
979 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000980 if (FT->getNumParams())
981 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000982 Getr += "...";
983 }
984 Getr += ")";
985 } else
986 Getr += "()";
987 }
988 Getr += ";\n";
989 Getr += "return (_TYPE)";
990 Getr += "objc_getProperty(self, _cmd, ";
991 RewriteIvarOffsetComputation(OID, Getr);
992 Getr += ", 1)";
993 }
994 else
995 Getr += "return " + getIvarAccessString(OID);
996 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000997 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000998 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000999
1000 if (PD->isReadOnly() ||
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001001 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001002 return;
1003
1004 // Generate the 'setter' function.
1005 std::string Setr;
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04001006 bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
1007 ObjCPropertyAttribute::kind_copy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001008 if (GenSetProperty && !objcSetPropertyDefined) {
1009 objcSetPropertyDefined = true;
1010 // FIXME. Is this attribute correct in all cases?
1011 Setr = "\nextern \"C\" __declspec(dllimport) "
1012 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1013 }
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00001014
Fangrui Song6907ce22018-07-30 19:24:48 +00001015 RewriteObjCMethodDecl(OID->getContainingInterface(),
Adrian Prantl2073dd22019-11-04 14:28:14 -08001016 PID->getSetterMethodDecl(), Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 Setr += "{ ";
1018 // Synthesize an explicit cast to initialize the ivar.
1019 // See objc-act.c:objc_synthesize_new_setter() for details.
1020 if (GenSetProperty) {
1021 Setr += "objc_setProperty (self, _cmd, ";
1022 RewriteIvarOffsetComputation(OID, Setr);
1023 Setr += ", (id)";
1024 Setr += PD->getName();
1025 Setr += ", ";
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04001026 if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001027 Setr += "0, ";
1028 else
1029 Setr += "1, ";
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04001030 if (Attributes & ObjCPropertyAttribute::kind_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001031 Setr += "1)";
1032 else
1033 Setr += "0)";
1034 }
1035 else {
1036 Setr += getIvarAccessString(OID) + " = ";
1037 Setr += PD->getName();
1038 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001039 Setr += "; }\n";
1040 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001041}
1042
1043static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1044 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001045 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001046 typedefString += ForwardDecl->getNameAsString();
1047 typedefString += "\n";
1048 typedefString += "#define _REWRITER_typedef_";
1049 typedefString += ForwardDecl->getNameAsString();
1050 typedefString += "\n";
1051 typedefString += "typedef struct objc_object ";
1052 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001053 // typedef struct { } _objc_exc_Classname;
1054 typedefString += ";\ntypedef struct {} _objc_exc_";
1055 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001056 typedefString += ";\n#endif\n";
1057}
1058
1059void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1060 const std::string &typedefString) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001061 SourceLocation startLoc = ClassDecl->getBeginLoc();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001062 const char *startBuf = SM->getCharacterData(startLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001063 const char *semiPtr = strchr(startBuf, ';');
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001064 // Replace the @class with typedefs corresponding to the classes.
Fangrui Song6907ce22018-07-30 19:24:48 +00001065 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001066}
1067
1068void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1069 std::string typedefString;
1070 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001071 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1072 if (I == D.begin()) {
1073 // Translate to typedef's that forward reference structs with the same name
1074 // as the class. As a convenience, we include the original declaration
1075 // as a comment.
1076 typedefString += "// @class ";
1077 typedefString += ForwardDecl->getNameAsString();
1078 typedefString += ";";
1079 }
1080 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001081 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001082 else
1083 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001084 }
1085 DeclGroupRef::iterator I = D.begin();
1086 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1087}
1088
1089void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001090 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001091 std::string typedefString;
1092 for (unsigned i = 0; i < D.size(); i++) {
1093 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1094 if (i == 0) {
1095 typedefString += "// @class ";
1096 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001097 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001098 }
1099 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1100 }
1101 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1102}
1103
1104void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1105 // When method is a synthesized one, such as a getter/setter there is
1106 // nothing to rewrite.
1107 if (Method->isImplicit())
1108 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001109 SourceLocation LocStart = Method->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001110 SourceLocation LocEnd = Method->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001111
1112 if (SM->getExpansionLineNumber(LocEnd) >
1113 SM->getExpansionLineNumber(LocStart)) {
1114 InsertText(LocStart, "#if 0\n");
1115 ReplaceText(LocEnd, 1, ";\n#endif\n");
1116 } else {
1117 InsertText(LocStart, "// ");
1118 }
1119}
1120
1121void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1122 SourceLocation Loc = prop->getAtLoc();
1123
1124 ReplaceText(Loc, 0, "// ");
1125 // FIXME: handle properties that are declared across multiple lines.
1126}
1127
1128void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001129 SourceLocation LocStart = CatDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001130
1131 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001132 if (CatDecl->getIvarRBraceLoc().isValid()) {
1133 ReplaceText(LocStart, 1, "/** ");
1134 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1135 }
1136 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001137 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001138 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001139
Manman Rena7a8b1f2016-01-26 18:05:23 +00001140 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001141 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001142
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001143 for (auto *I : CatDecl->instance_methods())
1144 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001145 for (auto *I : CatDecl->class_methods())
1146 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001147
1148 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001149 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001150 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001151}
1152
1153void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001154 SourceLocation LocStart = PDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001155 assert(PDecl->isThisDeclarationADefinition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001156
Fariborz Jahanian11671902012-02-07 17:11:38 +00001157 // FIXME: handle protocol headers that are declared across multiple lines.
1158 ReplaceText(LocStart, 0, "// ");
1159
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001160 for (auto *I : PDecl->instance_methods())
1161 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001162 for (auto *I : PDecl->class_methods())
1163 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001164 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001165 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001166
Fariborz Jahanian11671902012-02-07 17:11:38 +00001167 // Lastly, comment out the @end.
1168 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001169 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001170
1171 // Must comment out @optional/@required
1172 const char *startBuf = SM->getCharacterData(LocStart);
1173 const char *endBuf = SM->getCharacterData(LocEnd);
1174 for (const char *p = startBuf; p < endBuf; p++) {
1175 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1176 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1177 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1178
1179 }
1180 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1181 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1182 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1183
1184 }
1185 }
1186}
1187
1188void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001189 SourceLocation LocStart = (*D.begin())->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001190 if (LocStart.isInvalid())
1191 llvm_unreachable("Invalid SourceLocation");
1192 // FIXME: handle forward protocol that are declared across multiple lines.
1193 ReplaceText(LocStart, 0, "// ");
1194}
1195
Fangrui Song6907ce22018-07-30 19:24:48 +00001196void
Craig Topper5603df42013-07-05 19:34:19 +00001197RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001198 SourceLocation LocStart = DG[0]->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001199 if (LocStart.isInvalid())
1200 llvm_unreachable("Invalid SourceLocation");
1201 // FIXME: handle forward protocol that are declared across multiple lines.
1202 ReplaceText(LocStart, 0, "// ");
1203}
1204
1205void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1206 const FunctionType *&FPRetType) {
1207 if (T->isObjCQualifiedIdType())
1208 ResultStr += "id";
1209 else if (T->isFunctionPointerType() ||
1210 T->isBlockPointerType()) {
1211 // needs special handling, since pointer-to-functions have special
1212 // syntax (where a decaration models use).
1213 QualType retType = T;
1214 QualType PointeeTy;
1215 if (const PointerType* PT = retType->getAs<PointerType>())
1216 PointeeTy = PT->getPointeeType();
1217 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1218 PointeeTy = BPT->getPointeeType();
1219 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001220 ResultStr +=
1221 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001222 ResultStr += "(*";
1223 }
1224 } else
1225 ResultStr += T.getAsString(Context->getPrintingPolicy());
1226}
1227
1228void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1229 ObjCMethodDecl *OMD,
1230 std::string &ResultStr) {
1231 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001232 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001233 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001234 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001235 ResultStr += " ";
1236
1237 // Unique method name
1238 std::string NameStr;
1239
1240 if (OMD->isInstanceMethod())
1241 NameStr += "_I_";
1242 else
1243 NameStr += "_C_";
1244
1245 NameStr += IDecl->getNameAsString();
1246 NameStr += "_";
1247
1248 if (ObjCCategoryImplDecl *CID =
1249 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1250 NameStr += CID->getNameAsString();
1251 NameStr += "_";
1252 }
1253 // Append selector names, replacing ':' with '_'
1254 {
1255 std::string selString = OMD->getSelector().getAsString();
1256 int len = selString.size();
1257 for (int i = 0; i < len; i++)
1258 if (selString[i] == ':')
1259 selString[i] = '_';
1260 NameStr += selString;
1261 }
1262 // Remember this name for metadata emission
1263 MethodInternalNames[OMD] = NameStr;
1264 ResultStr += NameStr;
1265
1266 // Rewrite arguments
1267 ResultStr += "(";
1268
1269 // invisible arguments
1270 if (OMD->isInstanceMethod()) {
1271 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1272 selfTy = Context->getPointerType(selfTy);
1273 if (!LangOpts.MicrosoftExt) {
1274 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1275 ResultStr += "struct ";
1276 }
1277 // When rewriting for Microsoft, explicitly omit the structure name.
1278 ResultStr += IDecl->getNameAsString();
1279 ResultStr += " *";
1280 }
1281 else
1282 ResultStr += Context->getObjCClassType().getAsString(
1283 Context->getPrintingPolicy());
1284
1285 ResultStr += " self, ";
1286 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1287 ResultStr += " _cmd";
1288
1289 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001290 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001291 ResultStr += ", ";
1292 if (PDecl->getType()->isObjCQualifiedIdType()) {
1293 ResultStr += "id ";
1294 ResultStr += PDecl->getNameAsString();
1295 } else {
1296 std::string Name = PDecl->getNameAsString();
1297 QualType QT = PDecl->getType();
1298 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001299 (void)convertBlockPointerToFunctionPointer(QT);
1300 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001301 ResultStr += Name;
1302 }
1303 }
1304 if (OMD->isVariadic())
1305 ResultStr += ", ...";
1306 ResultStr += ") ";
1307
1308 if (FPRetType) {
1309 ResultStr += ")"; // close the precedence "scope" for "*".
1310
1311 // Now, emit the argument types (if any).
1312 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1313 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001314 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001315 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001316 std::string ParamStr =
1317 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001318 ResultStr += ParamStr;
1319 }
1320 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001321 if (FT->getNumParams())
1322 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001323 ResultStr += "...";
1324 }
1325 ResultStr += ")";
1326 } else {
1327 ResultStr += "()";
1328 }
1329 }
1330}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001331
Fariborz Jahanian11671902012-02-07 17:11:38 +00001332void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1333 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1334 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Simon Pilgrimb1504942019-10-16 10:50:06 +00001335 assert((IMD || CID) && "Unknown implementation type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001336
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001337 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001338 if (IMD->getIvarRBraceLoc().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001339 ReplaceText(IMD->getBeginLoc(), 1, "/** ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001340 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001341 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001342 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001343 InsertText(IMD->getBeginLoc(), "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001344 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001345 }
1346 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001347 InsertText(CID->getBeginLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001348
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001349 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Adrian Prantl2073dd22019-11-04 14:28:14 -08001350 if (!OMD->getBody())
1351 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001352 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001353 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001354 SourceLocation LocStart = OMD->getBeginLoc();
1355 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001356
1357 const char *startBuf = SM->getCharacterData(LocStart);
1358 const char *endBuf = SM->getCharacterData(LocEnd);
1359 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1360 }
1361
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001362 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Adrian Prantl2073dd22019-11-04 14:28:14 -08001363 if (!OMD->getBody())
1364 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001365 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001366 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001367 SourceLocation LocStart = OMD->getBeginLoc();
1368 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001369
1370 const char *startBuf = SM->getCharacterData(LocStart);
1371 const char *endBuf = SM->getCharacterData(LocEnd);
1372 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1373 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001374 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1375 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001376
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001377 InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001378}
1379
1380void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001381 // Do not synthesize more than once.
1382 if (ObjCSynthesizedStructs.count(ClassDecl))
1383 return;
1384 // Make sure super class's are written before current class is written.
1385 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1386 while (SuperClass) {
1387 RewriteInterfaceDecl(SuperClass);
1388 SuperClass = SuperClass->getSuperClass();
1389 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001390 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001391 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001392 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001393 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001394 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
Fangrui Song6907ce22018-07-30 19:24:48 +00001395
Fariborz Jahanianff513382012-02-15 22:01:47 +00001396 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001397 // Mark this typedef as having been written into its c++ equivalent.
1398 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001399
Manman Rena7a8b1f2016-01-26 18:05:23 +00001400 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001401 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001402 for (auto *I : ClassDecl->instance_methods())
1403 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001404 for (auto *I : ClassDecl->class_methods())
1405 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001406
Fariborz Jahanianff513382012-02-15 22:01:47 +00001407 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001408 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001409 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001410 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001411}
1412
1413Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1414 SourceRange OldRange = PseudoOp->getSourceRange();
1415
1416 // We just magically know some things about the structure of this
1417 // expression.
1418 ObjCMessageExpr *OldMsg =
1419 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1420 PseudoOp->getNumSemanticExprs() - 1));
1421
1422 // Because the rewriter doesn't allow us to rewrite rewritten code,
1423 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001424 Expr *Base;
1425 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001426 {
1427 DisableReplaceStmtScope S(*this);
1428
1429 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001430 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001431 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1432 Base = OldMsg->getInstanceReceiver();
1433 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1434 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1435 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001436
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001437 unsigned numArgs = OldMsg->getNumArgs();
1438 for (unsigned i = 0; i < numArgs; i++) {
1439 Expr *Arg = OldMsg->getArg(i);
1440 if (isa<OpaqueValueExpr>(Arg))
1441 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1442 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1443 Args.push_back(Arg);
1444 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001445 }
1446
1447 // TODO: avoid this copy.
1448 SmallVector<SourceLocation, 1> SelLocs;
1449 OldMsg->getSelectorLocs(SelLocs);
1450
Craig Topper8ae12032014-05-07 06:21:57 +00001451 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001452 switch (OldMsg->getReceiverKind()) {
1453 case ObjCMessageExpr::Class:
1454 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455 OldMsg->getValueKind(),
1456 OldMsg->getLeftLoc(),
1457 OldMsg->getClassReceiverTypeInfo(),
1458 OldMsg->getSelector(),
1459 SelLocs,
1460 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001461 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001462 OldMsg->getRightLoc(),
1463 OldMsg->isImplicit());
1464 break;
1465
1466 case ObjCMessageExpr::Instance:
1467 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1468 OldMsg->getValueKind(),
1469 OldMsg->getLeftLoc(),
1470 Base,
1471 OldMsg->getSelector(),
1472 SelLocs,
1473 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001474 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001475 OldMsg->getRightLoc(),
1476 OldMsg->isImplicit());
1477 break;
1478
1479 case ObjCMessageExpr::SuperClass:
1480 case ObjCMessageExpr::SuperInstance:
1481 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1482 OldMsg->getValueKind(),
1483 OldMsg->getLeftLoc(),
1484 OldMsg->getSuperLoc(),
1485 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1486 OldMsg->getSuperType(),
1487 OldMsg->getSelector(),
1488 SelLocs,
1489 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001490 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001491 OldMsg->getRightLoc(),
1492 OldMsg->isImplicit());
1493 break;
1494 }
1495
1496 Stmt *Replacement = SynthMessageExpr(NewMsg);
1497 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1498 return Replacement;
1499}
1500
1501Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1502 SourceRange OldRange = PseudoOp->getSourceRange();
1503
1504 // We just magically know some things about the structure of this
1505 // expression.
1506 ObjCMessageExpr *OldMsg =
1507 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1508
1509 // Because the rewriter doesn't allow us to rewrite rewritten code,
1510 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001511 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001512 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001513 {
1514 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001515 // Rebuild the base expression if we have one.
1516 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1517 Base = OldMsg->getInstanceReceiver();
1518 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1519 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1520 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001521 unsigned numArgs = OldMsg->getNumArgs();
1522 for (unsigned i = 0; i < numArgs; i++) {
1523 Expr *Arg = OldMsg->getArg(i);
1524 if (isa<OpaqueValueExpr>(Arg))
1525 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1526 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1527 Args.push_back(Arg);
1528 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001529 }
1530
1531 // Intentionally empty.
1532 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001533
Craig Topper8ae12032014-05-07 06:21:57 +00001534 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001535 switch (OldMsg->getReceiverKind()) {
1536 case ObjCMessageExpr::Class:
1537 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1538 OldMsg->getValueKind(),
1539 OldMsg->getLeftLoc(),
1540 OldMsg->getClassReceiverTypeInfo(),
1541 OldMsg->getSelector(),
1542 SelLocs,
1543 OldMsg->getMethodDecl(),
1544 Args,
1545 OldMsg->getRightLoc(),
1546 OldMsg->isImplicit());
1547 break;
1548
1549 case ObjCMessageExpr::Instance:
1550 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1551 OldMsg->getValueKind(),
1552 OldMsg->getLeftLoc(),
1553 Base,
1554 OldMsg->getSelector(),
1555 SelLocs,
1556 OldMsg->getMethodDecl(),
1557 Args,
1558 OldMsg->getRightLoc(),
1559 OldMsg->isImplicit());
1560 break;
1561
1562 case ObjCMessageExpr::SuperClass:
1563 case ObjCMessageExpr::SuperInstance:
1564 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1565 OldMsg->getValueKind(),
1566 OldMsg->getLeftLoc(),
1567 OldMsg->getSuperLoc(),
1568 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1569 OldMsg->getSuperType(),
1570 OldMsg->getSelector(),
1571 SelLocs,
1572 OldMsg->getMethodDecl(),
1573 Args,
1574 OldMsg->getRightLoc(),
1575 OldMsg->isImplicit());
1576 break;
1577 }
1578
1579 Stmt *Replacement = SynthMessageExpr(NewMsg);
1580 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1581 return Replacement;
1582}
1583
1584/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001585/// ((NSUInteger (*)
1586/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001587/// (void *)objc_msgSend)((id)l_collection,
1588/// sel_registerName(
1589/// "countByEnumeratingWithState:objects:count:"),
1590/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001591/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001592///
1593void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001594 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1595 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001596 buf += "\n\t\t";
1597 buf += "((id)l_collection,\n\t\t";
1598 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1599 buf += "\n\t\t";
1600 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001601 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001602}
1603
1604/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1605/// statement to exit to its outer synthesized loop.
1606///
1607Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1608 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1609 return S;
1610 // replace break with goto __break_label
1611 std::string buf;
1612
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001613 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001614 buf = "goto __break_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
1616 ReplaceText(startLoc, strlen("break"), buf);
1617
Craig Topper8ae12032014-05-07 06:21:57 +00001618 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001619}
1620
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001621void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1622 SourceLocation Loc,
1623 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001624 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001625 LineString += "\n#line ";
1626 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1627 LineString += utostr(PLoc.getLine());
1628 LineString += " \"";
1629 LineString += Lexer::Stringify(PLoc.getFilename());
1630 LineString += "\"\n";
1631 }
1632}
1633
Fariborz Jahanian11671902012-02-07 17:11:38 +00001634/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1635/// statement to continue with its inner synthesized loop.
1636///
1637Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1638 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1639 return S;
1640 // replace continue with goto __continue_label
1641 std::string buf;
1642
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001643 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001644 buf = "goto __continue_label_";
1645 buf += utostr(ObjCBcLabelNo.back());
1646 ReplaceText(startLoc, strlen("continue"), buf);
1647
Craig Topper8ae12032014-05-07 06:21:57 +00001648 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001649}
1650
1651/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1652/// It rewrites:
1653/// for ( type elem in collection) { stmts; }
1654
1655/// Into:
1656/// {
1657/// type elem;
1658/// struct __objcFastEnumerationState enumState = { 0 };
1659/// id __rw_items[16];
1660/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001661/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001662/// objects:__rw_items count:16];
1663/// if (limit) {
1664/// unsigned long startMutations = *enumState.mutationsPtr;
1665/// do {
1666/// unsigned long counter = 0;
1667/// do {
1668/// if (startMutations != *enumState.mutationsPtr)
1669/// objc_enumerationMutation(l_collection);
1670/// elem = (type)enumState.itemsPtr[counter++];
1671/// stmts;
1672/// __continue_label: ;
1673/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001674/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1675/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001676/// elem = nil;
1677/// __break_label: ;
1678/// }
1679/// else
1680/// elem = nil;
1681/// }
1682///
1683Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1684 SourceLocation OrigEnd) {
1685 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1686 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1687 "ObjCForCollectionStmt Statement stack mismatch");
1688 assert(!ObjCBcLabelNo.empty() &&
1689 "ObjCForCollectionStmt - Label No stack empty");
1690
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001691 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001692 const char *startBuf = SM->getCharacterData(startLoc);
1693 StringRef elementName;
1694 std::string elementTypeAsString;
1695 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001696 // line directive first.
1697 SourceLocation ForEachLoc = S->getForLoc();
1698 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1699 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001700 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1701 // type elem;
1702 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1703 QualType ElementType = cast<ValueDecl>(D)->getType();
1704 if (ElementType->isObjCQualifiedIdType() ||
1705 ElementType->isObjCQualifiedInterfaceType())
1706 // Simply use 'id' for all qualified types.
1707 elementTypeAsString = "id";
1708 else
1709 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1710 buf += elementTypeAsString;
1711 buf += " ";
1712 elementName = D->getName();
1713 buf += elementName;
1714 buf += ";\n\t";
1715 }
1716 else {
1717 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1718 elementName = DR->getDecl()->getName();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001719 ValueDecl *VD = DR->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001720 if (VD->getType()->isObjCQualifiedIdType() ||
1721 VD->getType()->isObjCQualifiedInterfaceType())
1722 // Simply use 'id' for all qualified types.
1723 elementTypeAsString = "id";
1724 else
1725 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1726 }
1727
1728 // struct __objcFastEnumerationState enumState = { 0 };
1729 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1730 // id __rw_items[16];
1731 buf += "id __rw_items[16];\n\t";
1732 // id l_collection = (id)
1733 buf += "id l_collection = (id)";
1734 // Find start location of 'collection' the hard way!
1735 const char *startCollectionBuf = startBuf;
1736 startCollectionBuf += 3; // skip 'for'
1737 startCollectionBuf = strchr(startCollectionBuf, '(');
1738 startCollectionBuf++; // skip '('
1739 // find 'in' and skip it.
1740 while (*startCollectionBuf != ' ' ||
1741 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1742 (*(startCollectionBuf+3) != ' ' &&
1743 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1744 startCollectionBuf++;
1745 startCollectionBuf += 3;
1746
1747 // Replace: "for (type element in" with string constructed thus far.
1748 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1749 // Replace ')' in for '(' type elem in collection ')' with ';'
1750 SourceLocation rightParenLoc = S->getRParenLoc();
1751 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1752 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1753 buf = ";\n\t";
1754
1755 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1756 // objects:__rw_items count:16];
1757 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001758 // NSUInteger limit =
1759 // ((NSUInteger (*)
1760 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001761 // (void *)objc_msgSend)((id)l_collection,
1762 // sel_registerName(
1763 // "countByEnumeratingWithState:objects:count:"),
1764 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001765 // (id *)__rw_items, (NSUInteger)16);
1766 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001767 SynthCountByEnumWithState(buf);
1768 buf += ";\n\t";
1769 /// if (limit) {
1770 /// unsigned long startMutations = *enumState.mutationsPtr;
1771 /// do {
1772 /// unsigned long counter = 0;
1773 /// do {
1774 /// if (startMutations != *enumState.mutationsPtr)
1775 /// objc_enumerationMutation(l_collection);
1776 /// elem = (type)enumState.itemsPtr[counter++];
1777 buf += "if (limit) {\n\t";
1778 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1779 buf += "do {\n\t\t";
1780 buf += "unsigned long counter = 0;\n\t\t";
1781 buf += "do {\n\t\t\t";
1782 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1783 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1784 buf += elementName;
1785 buf += " = (";
1786 buf += elementTypeAsString;
1787 buf += ")enumState.itemsPtr[counter++];";
1788 // Replace ')' in for '(' type elem in collection ')' with all of these.
1789 ReplaceText(lparenLoc, 1, buf);
1790
1791 /// __continue_label: ;
1792 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001793 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1794 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001795 /// elem = nil;
1796 /// __break_label: ;
1797 /// }
1798 /// else
1799 /// elem = nil;
1800 /// }
1801 ///
1802 buf = ";\n\t";
1803 buf += "__continue_label_";
1804 buf += utostr(ObjCBcLabelNo.back());
1805 buf += ": ;";
1806 buf += "\n\t\t";
1807 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001808 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001809 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001810 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001811 buf += elementName;
1812 buf += " = ((";
1813 buf += elementTypeAsString;
1814 buf += ")0);\n\t";
1815 buf += "__break_label_";
1816 buf += utostr(ObjCBcLabelNo.back());
1817 buf += ": ;\n\t";
1818 buf += "}\n\t";
1819 buf += "else\n\t\t";
1820 buf += elementName;
1821 buf += " = ((";
1822 buf += elementTypeAsString;
1823 buf += ")0);\n\t";
1824 buf += "}\n";
1825
1826 // Insert all these *after* the statement body.
1827 // FIXME: If this should support Obj-C++, support CXXTryStmt
1828 if (isa<CompoundStmt>(S->getBody())) {
1829 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1830 InsertText(endBodyLoc, buf);
1831 } else {
1832 /* Need to treat single statements specially. For example:
1833 *
1834 * for (A *a in b) if (stuff()) break;
1835 * for (A *a in b) xxxyy;
1836 *
1837 * The following code simply scans ahead to the semi to find the actual end.
1838 */
1839 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1840 const char *semiBuf = strchr(stmtBuf, ';');
1841 assert(semiBuf && "Can't find ';'");
1842 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1843 InsertText(endBodyLoc, buf);
1844 }
1845 Stmts.pop_back();
1846 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001847 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001848}
1849
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001850static void Write_RethrowObject(std::string &buf) {
1851 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1852 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1853 buf += "\tid rethrow;\n";
1854 buf += "\t} _fin_force_rethow(_rethrow);";
1855}
1856
Fariborz Jahanian11671902012-02-07 17:11:38 +00001857/// RewriteObjCSynchronizedStmt -
1858/// This routine rewrites @synchronized(expr) stmt;
1859/// into:
1860/// objc_sync_enter(expr);
1861/// @try stmt @finally { objc_sync_exit(expr); }
1862///
1863Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1864 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001865 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001866 const char *startBuf = SM->getCharacterData(startLoc);
1867
1868 assert((*startBuf == '@') && "bogus @synchronized location");
1869
1870 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001871 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1872 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001873 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fangrui Song6907ce22018-07-30 19:24:48 +00001874
Fariborz Jahanian11671902012-02-07 17:11:38 +00001875 const char *lparenBuf = startBuf;
1876 while (*lparenBuf != '(') lparenBuf++;
1877 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001878
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001879 buf = "; objc_sync_enter(_sync_obj);\n";
1880 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1881 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1882 buf += "\n\tid sync_exit;";
1883 buf += "\n\t} _sync_exit(_sync_obj);\n";
1884
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001885 // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001886 // the sync expression is typically a message expression that's already
1887 // been rewritten! (which implies the SourceLocation's are invalid).
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001888 SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001889 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1890 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1891 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001892
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001893 SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001894 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1895 assert (*LBraceLocBuf == '{');
1896 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001897
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001898 SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001899 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1900 "bogus @synchronized block");
Fangrui Song6907ce22018-07-30 19:24:48 +00001901
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001902 buf = "} catch (id e) {_rethrow = e;}\n";
1903 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001904 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001905 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001906
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001907 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001908
Craig Topper8ae12032014-05-07 06:21:57 +00001909 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001910}
1911
1912void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1913{
1914 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001915 for (Stmt *SubStmt : S->children())
1916 if (SubStmt)
1917 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001918
1919 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001920 Diags.Report(Context->getFullLoc(S->getBeginLoc()),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001921 TryFinallyContainsReturnDiag);
1922 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001923}
1924
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001925Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1926 SourceLocation startLoc = S->getAtLoc();
1927 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001928 ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001929 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001930
1931 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001932}
1933
Fariborz Jahanian11671902012-02-07 17:11:38 +00001934Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001935 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001936 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001937 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001938 SourceLocation TryLocation = S->getAtTryLoc();
1939 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001940
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001941 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001942 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001943 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001944 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001945 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001946 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001947 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001948 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001949 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001950 const char *startBuf = SM->getCharacterData(startLoc);
1951
1952 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001953 if (finalStmt)
1954 ReplaceText(startLoc, 1, buf);
1955 else
1956 // @try -> try
1957 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00001958
Fariborz Jahanian11671902012-02-07 17:11:38 +00001959 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1960 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001961 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001962
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001963 startLoc = Catch->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001964 bool AtRemoved = false;
1965 if (catchDecl) {
1966 QualType t = catchDecl->getType();
1967 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1968 // Should be a pointer to a class.
1969 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1970 if (IDecl) {
1971 std::string Result;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001972 ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00001973
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001974 startBuf = SM->getCharacterData(startLoc);
1975 assert((*startBuf == '@') && "bogus @catch location");
1976 SourceLocation rParenLoc = Catch->getRParenLoc();
1977 const char *rParenBuf = SM->getCharacterData(rParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001978
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001979 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001980 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001981 Result += " *_"; Result += catchDecl->getNameAsString();
1982 Result += ")";
1983 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1984 // Foo *e = (Foo *)_e;
1985 Result.clear();
1986 Result = "{ ";
1987 Result += IDecl->getNameAsString();
1988 Result += " *"; Result += catchDecl->getNameAsString();
1989 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1990 Result += "_"; Result += catchDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00001991
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001992 Result += "; ";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001993 SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001994 ReplaceText(lBraceLoc, 1, Result);
1995 AtRemoved = true;
1996 }
1997 }
1998 }
1999 if (!AtRemoved)
2000 // @catch -> catch
2001 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00002002
Fariborz Jahanian11671902012-02-07 17:11:38 +00002003 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002004 if (finalStmt) {
2005 buf.clear();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002006 SourceLocation FinallyLoc = finalStmt->getBeginLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002007
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002008 if (noCatch) {
2009 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2010 buf += "catch (id e) {_rethrow = e;}\n";
2011 }
2012 else {
2013 buf += "}\n";
2014 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2015 buf += "catch (id e) {_rethrow = e;}\n";
2016 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002017
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002018 SourceLocation startFinalLoc = finalStmt->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002019 ReplaceText(startFinalLoc, 8, buf);
2020 Stmt *body = finalStmt->getFinallyBody();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002021 SourceLocation startFinalBodyLoc = body->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002022 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002023 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002024 ReplaceText(startFinalBodyLoc, 1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00002025
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002026 SourceLocation endFinalBodyLoc = body->getEndLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002027 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002028 // Now check for any return/continue/go statements within the @try.
2029 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002030 }
2031
Craig Topper8ae12032014-05-07 06:21:57 +00002032 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002033}
2034
2035// This can't be done with ReplaceStmt(S, ThrowExpr), since
2036// the throw expression is typically a message expression that's already
2037// been rewritten! (which implies the SourceLocation's are invalid).
2038Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2039 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002040 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002041 const char *startBuf = SM->getCharacterData(startLoc);
2042
2043 assert((*startBuf == '@') && "bogus @throw location");
2044
2045 std::string buf;
2046 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2047 if (S->getThrowExpr())
2048 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002049 else
2050 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002051
2052 // handle "@ throw" correctly.
2053 const char *wBuf = strchr(startBuf, 'w');
2054 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2055 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2056
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002057 SourceLocation endLoc = S->getEndLoc();
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002058 const char *endBuf = SM->getCharacterData(endLoc);
2059 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002060 assert((*semiBuf == ';') && "@throw: can't find ';'");
2061 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002062 if (S->getThrowExpr())
2063 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002064 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002065}
2066
2067Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2068 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002069 std::string StrEncoding;
2070 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002071 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002072 ReplaceStmt(Exp, Replacement);
2073
2074 // Replace this subexpr in the parent.
2075 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2076 return Replacement;
2077}
2078
2079Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2080 if (!SelGetUidFunctionDecl)
2081 SynthSelGetUidFunctionDecl();
2082 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2083 // Create a call to sel_registerName("selName").
2084 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002085 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002086 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002087 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002088 ReplaceStmt(Exp, SelExp);
2089 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2090 return SelExp;
2091}
2092
Craig Toppercf2126e2015-10-22 03:13:07 +00002093CallExpr *
2094RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2095 ArrayRef<Expr *> Args,
2096 SourceLocation StartLoc,
2097 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002098 // Get the type, we will need to reference it in a couple spots.
2099 QualType msgSendType = FD->getType();
2100
2101 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002102 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2103 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002104
2105 // Now, we cast the reference to a pointer to the objc_msgSend type.
2106 QualType pToFunc = Context->getPointerType(msgSendType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002107 ImplicitCastExpr *ICE =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002108 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002109 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002110
Simon Pilgrimb1504942019-10-16 10:50:06 +00002111 const auto *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002112 CallExpr *Exp = CallExpr::Create(
2113 *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002114 return Exp;
2115}
2116
2117static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2118 const char *&startRef, const char *&endRef) {
2119 while (startBuf < endBuf) {
2120 if (*startBuf == '<')
2121 startRef = startBuf; // mark the start.
2122 if (*startBuf == '>') {
2123 if (startRef && *startRef == '<') {
2124 endRef = startBuf; // mark the end.
2125 return true;
2126 }
2127 return false;
2128 }
2129 startBuf++;
2130 }
2131 return false;
2132}
2133
2134static void scanToNextArgument(const char *&argRef) {
2135 int angle = 0;
2136 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2137 if (*argRef == '<')
2138 angle++;
2139 else if (*argRef == '>')
2140 angle--;
2141 argRef++;
2142 }
2143 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2144}
2145
2146bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2147 if (T->isObjCQualifiedIdType())
2148 return true;
2149 if (const PointerType *PT = T->getAs<PointerType>()) {
2150 if (PT->getPointeeType()->isObjCQualifiedIdType())
2151 return true;
2152 }
2153 if (T->isObjCObjectPointerType()) {
2154 T = T->getPointeeType();
2155 return T->isObjCQualifiedInterfaceType();
2156 }
2157 if (T->isArrayType()) {
2158 QualType ElemTy = Context->getBaseElementType(T);
2159 return needToScanForQualifiers(ElemTy);
2160 }
2161 return false;
2162}
2163
2164void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2165 QualType Type = E->getType();
2166 if (needToScanForQualifiers(Type)) {
2167 SourceLocation Loc, EndLoc;
2168
2169 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2170 Loc = ECE->getLParenLoc();
2171 EndLoc = ECE->getRParenLoc();
2172 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002173 Loc = E->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002174 EndLoc = E->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002175 }
2176 // This will defend against trying to rewrite synthesized expressions.
2177 if (Loc.isInvalid() || EndLoc.isInvalid())
2178 return;
2179
2180 const char *startBuf = SM->getCharacterData(Loc);
2181 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002182 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2186 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2187 // Comment out the protocol references.
2188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
2190 }
2191 }
2192}
2193
2194void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2195 SourceLocation Loc;
2196 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002197 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002198 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2199 Loc = VD->getLocation();
2200 Type = VD->getType();
2201 }
2202 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2203 Loc = FD->getLocation();
2204 // Check for ObjC 'id' and class types that have been adorned with protocol
2205 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2206 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2207 assert(funcType && "missing function type");
2208 proto = dyn_cast<FunctionProtoType>(funcType);
2209 if (!proto)
2210 return;
Alp Toker314cc812014-01-25 16:55:45 +00002211 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002212 }
2213 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2214 Loc = FD->getLocation();
2215 Type = FD->getType();
2216 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002217 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2218 Loc = TD->getLocation();
2219 Type = TD->getUnderlyingType();
2220 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002221 else
2222 return;
2223
2224 if (needToScanForQualifiers(Type)) {
2225 // Since types are unique, we need to scan the buffer.
2226
2227 const char *endBuf = SM->getCharacterData(Loc);
2228 const char *startBuf = endBuf;
2229 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2230 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002231 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002232 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233 // Get the locations of the startRef, endRef.
2234 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2235 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2236 // Comment out the protocol references.
2237 InsertText(LessLoc, "/*");
2238 InsertText(GreaterLoc, "*/");
2239 }
2240 }
2241 if (!proto)
2242 return; // most likely, was a variable
2243 // Now check arguments.
2244 const char *startBuf = SM->getCharacterData(Loc);
2245 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002246 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2247 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002248 // Since types are unique, we need to scan the buffer.
2249
2250 const char *endBuf = startBuf;
2251 // scan forward (from the decl location) for argument types.
2252 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002253 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255 // Get the locations of the startRef, endRef.
2256 SourceLocation LessLoc =
2257 Loc.getLocWithOffset(startRef-startFuncBuf);
2258 SourceLocation GreaterLoc =
2259 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2260 // Comment out the protocol references.
2261 InsertText(LessLoc, "/*");
2262 InsertText(GreaterLoc, "*/");
2263 }
2264 startBuf = ++endBuf;
2265 }
2266 else {
2267 // If the function name is derived from a macro expansion, then the
2268 // argument buffer will not follow the name. Need to speak with Chris.
2269 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2270 startBuf++; // scan forward (from the decl location) for argument types.
2271 startBuf++;
2272 }
2273 }
2274}
2275
2276void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2277 QualType QT = ND->getType();
2278 const Type* TypePtr = QT->getAs<Type>();
2279 if (!isa<TypeOfExprType>(TypePtr))
2280 return;
2281 while (isa<TypeOfExprType>(TypePtr)) {
2282 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2283 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2284 TypePtr = QT->getAs<Type>();
2285 }
2286 // FIXME. This will not work for multiple declarators; as in:
2287 // __typeof__(a) b,c,d;
2288 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2289 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2290 const char *startBuf = SM->getCharacterData(DeclLoc);
2291 if (ND->getInit()) {
2292 std::string Name(ND->getNameAsString());
2293 TypeAsString += " " + Name + " = ";
2294 Expr *E = ND->getInit();
2295 SourceLocation startLoc;
2296 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2297 startLoc = ECE->getLParenLoc();
2298 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002299 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002300 startLoc = SM->getExpansionLoc(startLoc);
2301 const char *endBuf = SM->getCharacterData(startLoc);
2302 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2303 }
2304 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002305 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002306 X = SM->getExpansionLoc(X);
2307 const char *endBuf = SM->getCharacterData(X);
2308 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2309 }
2310}
2311
2312// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2313void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2314 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2315 SmallVector<QualType, 16> ArgTys;
2316 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2317 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002318 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002319 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002320 SourceLocation(),
2321 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002322 SelGetUidIdent, getFuncType,
2323 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002324}
2325
2326void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2327 // declared in <objc/objc.h>
2328 if (FD->getIdentifier() &&
2329 FD->getName() == "sel_registerName") {
2330 SelGetUidFunctionDecl = FD;
2331 return;
2332 }
2333 RewriteObjCQualifiedInterfaceTypes(FD);
2334}
2335
2336void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2337 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2338 const char *argPtr = TypeString.c_str();
2339 if (!strchr(argPtr, '^')) {
2340 Str += TypeString;
2341 return;
2342 }
2343 while (*argPtr) {
2344 Str += (*argPtr == '^' ? '*' : *argPtr);
2345 argPtr++;
2346 }
2347}
2348
2349// FIXME. Consolidate this routine with RewriteBlockPointerType.
2350void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2351 ValueDecl *VD) {
2352 QualType Type = VD->getType();
2353 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2354 const char *argPtr = TypeString.c_str();
2355 int paren = 0;
2356 while (*argPtr) {
2357 switch (*argPtr) {
2358 case '(':
2359 Str += *argPtr;
2360 paren++;
2361 break;
2362 case ')':
2363 Str += *argPtr;
2364 paren--;
2365 break;
2366 case '^':
2367 Str += '*';
2368 if (paren == 1)
2369 Str += VD->getNameAsString();
2370 break;
2371 default:
2372 Str += *argPtr;
2373 break;
2374 }
2375 argPtr++;
2376 }
2377}
2378
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002379void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2380 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2381 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2382 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2383 if (!proto)
2384 return;
Alp Toker314cc812014-01-25 16:55:45 +00002385 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002386 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2387 FdStr += " ";
2388 FdStr += FD->getName();
2389 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002390 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002391 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002392 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002393 RewriteBlockPointerType(FdStr, ArgType);
2394 if (i+1 < numArgs)
2395 FdStr += ", ";
2396 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002397 if (FD->isVariadic()) {
2398 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2399 }
2400 else
2401 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002402 InsertText(FunLocStart, FdStr);
2403}
2404
Benjamin Kramer60509af2013-09-09 14:48:42 +00002405// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2406void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2407 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002408 return;
2409 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2410 SmallVector<QualType, 16> ArgTys;
2411 QualType argT = Context->getObjCIdType();
2412 assert(!argT.isNull() && "Can't find 'id' type");
2413 ArgTys.push_back(argT);
2414 ArgTys.push_back(argT);
2415 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002416 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002417 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002418 SourceLocation(),
2419 SourceLocation(),
2420 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002421 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002422}
2423
2424// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2425void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2427 SmallVector<QualType, 16> ArgTys;
2428 QualType argT = Context->getObjCIdType();
2429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
2431 argT = Context->getObjCSelType();
2432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
2434 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002435 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002436 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002437 SourceLocation(),
2438 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002439 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002440 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002441}
2442
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002443// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002444void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2445 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002446 SmallVector<QualType, 2> ArgTys;
2447 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002449 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002450 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002451 SourceLocation(),
2452 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002453 msgSendIdent, msgSendType,
2454 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002455}
2456
2457// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002468 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002469 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002472 msgSendIdent, msgSendType,
2473 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002474}
2475
2476// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002477// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002478void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2479 IdentifierInfo *msgSendIdent =
2480 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002481 SmallVector<QualType, 2> ArgTys;
2482 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002484 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002485 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2486 SourceLocation(),
2487 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002488 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002489 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002490 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002491}
2492
2493// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2494void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2496 SmallVector<QualType, 16> ArgTys;
2497 QualType argT = Context->getObjCIdType();
2498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
2500 argT = Context->getObjCSelType();
2501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
2503 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002504 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002506 SourceLocation(),
2507 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002508 msgSendIdent, msgSendType,
2509 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002510}
2511
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002512// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513void RewriteModernObjC::SynthGetClassFunctionDecl() {
2514 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2515 SmallVector<QualType, 16> ArgTys;
2516 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002517 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002518 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002519 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002520 SourceLocation(),
2521 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002522 getClassIdent, getClassType,
2523 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002524}
2525
2526// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2527void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
Fangrui Song6907ce22018-07-30 19:24:48 +00002528 IdentifierInfo *getSuperClassIdent =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002529 &Context->Idents.get("class_getSuperclass");
2530 SmallVector<QualType, 16> ArgTys;
2531 ArgTys.push_back(Context->getObjCClassType());
2532 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002533 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002534 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2535 SourceLocation(),
2536 SourceLocation(),
2537 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002538 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002539 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002540}
2541
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002542// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002543void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2544 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2545 SmallVector<QualType, 16> ArgTys;
2546 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002547 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002548 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002549 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002550 SourceLocation(),
2551 SourceLocation(),
2552 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002553 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554}
2555
2556Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002557 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002558 QualType strType = getConstantStringStructType();
2559
2560 std::string S = "__NSConstantStringImpl_";
2561
2562 std::string tmpName = InFileName;
2563 unsigned i;
2564 for (i=0; i < tmpName.length(); i++) {
2565 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002566 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002567 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002568 tmpName[i] = '_';
2569 }
2570 S += tmpName;
2571 S += "_";
2572 S += utostr(NumObjCStringLiterals++);
2573
2574 Preamble += "static __NSConstantStringImpl " + S;
2575 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2576 Preamble += "0x000007c8,"; // utf8_str
2577 // The pretty printer for StringLiteral handles escape characters properly.
2578 std::string prettyBufS;
2579 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002580 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002581 Preamble += prettyBuf.str();
2582 Preamble += ",";
2583 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2584
2585 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2586 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002587 strType, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002588 DeclRefExpr *DRE = new (Context)
2589 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2590 Expr *Unop = new (Context)
2591 UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2592 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002593 // cast to NSConstantString *
2594 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2595 CK_CPointerToObjCPointerCast, Unop);
2596 ReplaceStmt(Exp, cast);
2597 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2598 return cast;
2599}
2600
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002601Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2602 unsigned IntSize =
2603 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00002604
2605 Expr *FlagExp = IntegerLiteral::Create(*Context,
2606 llvm::APInt(IntSize, Exp->getValue()),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002607 Context->IntTy, Exp->getLocation());
2608 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2609 CK_BitCast, FlagExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002610 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002611 cast);
2612 ReplaceStmt(Exp, PE);
2613 return PE;
2614}
2615
Patrick Beard0caa3942012-04-19 00:25:12 +00002616Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002617 // synthesize declaration of helper functions needed in this routine.
2618 if (!SelGetUidFunctionDecl)
2619 SynthSelGetUidFunctionDecl();
2620 // use objc_msgSend() for all.
2621 if (!MsgSendFunctionDecl)
2622 SynthMsgSendFunctionDecl();
2623 if (!GetClassFunctionDecl)
2624 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002625
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002626 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002627 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002628 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002629
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002630 // Synthesize a call to objc_msgSend().
2631 SmallVector<Expr*, 4> MsgExprs;
2632 SmallVector<Expr*, 4> ClsExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002633
Patrick Beard0caa3942012-04-19 00:25:12 +00002634 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2635 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2636 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002637
Patrick Beard0caa3942012-04-19 00:25:12 +00002638 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002639 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002640 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002641 StartLoc, EndLoc);
2642 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002643
Patrick Beard0caa3942012-04-19 00:25:12 +00002644 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002645 // it will be the 2nd argument.
2646 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002647 SelExprs.push_back(
2648 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002649 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002650 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002651 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002652
Patrick Beard0caa3942012-04-19 00:25:12 +00002653 // User provided sub-expression is the 3rd, and last, argument.
2654 Expr *subExpr = Exp->getSubExpr();
2655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002656 QualType type = ICE->getType();
2657 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2658 CastKind CK = CK_BitCast;
2659 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2660 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002661 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002662 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002663 MsgExprs.push_back(subExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00002664
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002665 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002666 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002667 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002668 for (const auto PI : BoxingMethod->parameters())
2669 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002670
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002671 QualType returnType = Exp->getType();
2672 // Get the type, we will need to reference it in a couple spots.
2673 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002674
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002675 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002676 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2677 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002678
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002679 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2680 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002681
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002682 // Now do the "normal" pointer to function cast.
2683 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002684 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002685 castType = Context->getPointerType(castType);
2686 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2687 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002688
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002689 // Don't forget the parens to enforce the proper binding.
2690 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002691
Simon Pilgrim7bfc3bf2020-03-12 16:49:35 +00002692 auto *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002693 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2694 VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002695 ReplaceStmt(Exp, CE);
2696 return CE;
2697}
2698
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002699Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2700 // synthesize declaration of helper functions needed in this routine.
2701 if (!SelGetUidFunctionDecl)
2702 SynthSelGetUidFunctionDecl();
2703 // use objc_msgSend() for all.
2704 if (!MsgSendFunctionDecl)
2705 SynthMsgSendFunctionDecl();
2706 if (!GetClassFunctionDecl)
2707 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002708
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002709 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002710 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002711 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002712
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002713 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002714 QualType IntQT = Context->IntTy;
2715 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002716 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002717 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002718 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002719 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2720 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002721
2722 SmallVector<Expr*, 16> InitExprs;
2723 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002724 unsigned UnsignedIntSize =
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002725 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2726 Expr *count = IntegerLiteral::Create(*Context,
2727 llvm::APInt(UnsignedIntSize, NumElements),
2728 Context->UnsignedIntTy, SourceLocation());
2729 InitExprs.push_back(count);
2730 for (unsigned i = 0; i < NumElements; i++)
2731 InitExprs.push_back(Exp->getElement(i));
Fangrui Song6907ce22018-07-30 19:24:48 +00002732 Expr *NSArrayCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002733 CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2734 SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002735
2736 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002737 SourceLocation(),
2738 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002739 Context->getPointerType(Context->VoidPtrTy),
2740 nullptr, /*BitWidth=*/nullptr,
2741 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00002742 MemberExpr *ArrayLiteralME =
2743 MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2744 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002745 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002746 CStyleCastExpr * ArrayLiteralObjects =
2747 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002748 Context->getPointerType(ConstIdT),
2749 CK_BitCast,
2750 ArrayLiteralME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002751
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002752 // Synthesize a call to objc_msgSend().
2753 SmallVector<Expr*, 32> MsgExprs;
2754 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002755 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002756
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002757 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002758 ObjCInterfaceDecl *Class =
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002759 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002760
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002761 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002762 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002763 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002764 StartLoc, EndLoc);
2765 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002766
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002767 // Create a call to sel_registerName("arrayWithObjects:count:").
2768 // it will be the 2nd argument.
2769 SmallVector<Expr*, 4> SelExprs;
2770 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002771 SelExprs.push_back(
2772 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002773 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002774 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002775 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002776
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002777 // (const id [])objects
2778 MsgExprs.push_back(ArrayLiteralObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002779
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002780 // (NSUInteger)cnt
2781 Expr *cnt = IntegerLiteral::Create(*Context,
2782 llvm::APInt(UnsignedIntSize, NumElements),
2783 Context->UnsignedIntTy, SourceLocation());
2784 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002785
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002786 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002787 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002788 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002789 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002790 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002791
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002792 QualType returnType = Exp->getType();
2793 // Get the type, we will need to reference it in a couple spots.
2794 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002795
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002796 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002797 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2798 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002799
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002800 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2801 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002802
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002803 // Now do the "normal" pointer to function cast.
2804 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002805 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002806 castType = Context->getPointerType(castType);
2807 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2808 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002809
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002810 // Don't forget the parens to enforce the proper binding.
2811 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002812
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002813 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002814 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2815 VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002816 ReplaceStmt(Exp, CE);
2817 return CE;
2818}
2819
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002820Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2821 // synthesize declaration of helper functions needed in this routine.
2822 if (!SelGetUidFunctionDecl)
2823 SynthSelGetUidFunctionDecl();
2824 // use objc_msgSend() for all.
2825 if (!MsgSendFunctionDecl)
2826 SynthMsgSendFunctionDecl();
2827 if (!GetClassFunctionDecl)
2828 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002829
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002830 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002831 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002832 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002833
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002834 // Build the expression: __NSContainer_literal(int, ...).arr
2835 QualType IntQT = Context->IntTy;
2836 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002837 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002838 std::string NSDictFName("__NSContainer_literal");
2839 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002840 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2841 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002842
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002843 SmallVector<Expr*, 16> KeyExprs;
2844 SmallVector<Expr*, 16> ValueExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002845
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002846 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002847 unsigned UnsignedIntSize =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002848 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2849 Expr *count = IntegerLiteral::Create(*Context,
2850 llvm::APInt(UnsignedIntSize, NumElements),
2851 Context->UnsignedIntTy, SourceLocation());
2852 KeyExprs.push_back(count);
2853 ValueExprs.push_back(count);
2854 for (unsigned i = 0; i < NumElements; i++) {
2855 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2856 KeyExprs.push_back(Element.Key);
2857 ValueExprs.push_back(Element.Value);
2858 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002859
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002860 // (const id [])objects
Fangrui Song6907ce22018-07-30 19:24:48 +00002861 Expr *NSValueCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002862 CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2863 SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002864
2865 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002866 SourceLocation(),
2867 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002868 Context->getPointerType(Context->VoidPtrTy),
2869 nullptr, /*BitWidth=*/nullptr,
2870 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00002871 MemberExpr *DictLiteralValueME =
2872 MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2873 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002874 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002875 CStyleCastExpr * DictValueObjects =
2876 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002877 Context->getPointerType(ConstIdT),
2878 CK_BitCast,
2879 DictLiteralValueME);
2880 // (const id <NSCopying> [])keys
Bruno Riccic5885cf2018-12-21 15:20:32 +00002881 Expr *NSKeyCallExpr = CallExpr::Create(
2882 *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002883
Richard Smithdcf17de2019-06-06 23:24:15 +00002884 MemberExpr *DictLiteralKeyME =
2885 MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2886 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002887
Fangrui Song6907ce22018-07-30 19:24:48 +00002888 CStyleCastExpr * DictKeyObjects =
2889 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002890 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002891 CK_BitCast,
2892 DictLiteralKeyME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002893
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002894 // Synthesize a call to objc_msgSend().
2895 SmallVector<Expr*, 32> MsgExprs;
2896 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002897 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002898
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002899 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002900 ObjCInterfaceDecl *Class =
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002901 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002902
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002903 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002904 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002905 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002906 StartLoc, EndLoc);
2907 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002908
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002909 // Create a call to sel_registerName("arrayWithObjects:count:").
2910 // it will be the 2nd argument.
2911 SmallVector<Expr*, 4> SelExprs;
2912 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002913 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002914 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002915 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002916 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002917
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 // (const id [])objects
2919 MsgExprs.push_back(DictValueObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002920
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 // (const id <NSCopying> [])keys
2922 MsgExprs.push_back(DictKeyObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002923
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002924 // (NSUInteger)cnt
2925 Expr *cnt = IntegerLiteral::Create(*Context,
2926 llvm::APInt(UnsignedIntSize, NumElements),
2927 Context->UnsignedIntTy, SourceLocation());
2928 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002929
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002930 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002931 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002932 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002933 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002934 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002935 if (const PointerType* PT = T->getAs<PointerType>()) {
2936 QualType PointeeTy = PT->getPointeeType();
2937 convertToUnqualifiedObjCType(PointeeTy);
2938 T = Context->getPointerType(PointeeTy);
2939 }
2940 ArgTypes.push_back(T);
2941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002942
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002943 QualType returnType = Exp->getType();
2944 // Get the type, we will need to reference it in a couple spots.
2945 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002946
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002947 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002948 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2949 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002950
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002951 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2952 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002953
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002954 // Now do the "normal" pointer to function cast.
2955 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002956 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002957 castType = Context->getPointerType(castType);
2958 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2959 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002960
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 // Don't forget the parens to enforce the proper binding.
2962 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002963
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002964 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002965 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2966 VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002967 ReplaceStmt(Exp, CE);
2968 return CE;
2969}
2970
Fangrui Song6907ce22018-07-30 19:24:48 +00002971// struct __rw_objc_super {
2972// struct objc_object *object; struct objc_object *superClass;
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002973// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002974QualType RewriteModernObjC::getSuperStructType() {
2975 if (!SuperStructDecl) {
2976 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2977 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002978 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002979 QualType FieldTypes[2];
2980
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002981 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002982 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002983 // struct objc_object *superClass;
2984 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002985
2986 // Create fields
2987 for (unsigned i = 0; i < 2; ++i) {
2988 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2989 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002990 SourceLocation(), nullptr,
2991 FieldTypes[i], nullptr,
2992 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002993 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002994 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002995 }
2996
2997 SuperStructDecl->completeDefinition();
2998 }
2999 return Context->getTagDeclType(SuperStructDecl);
3000}
3001
3002QualType RewriteModernObjC::getConstantStringStructType() {
3003 if (!ConstantStringDecl) {
3004 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3005 SourceLocation(), SourceLocation(),
3006 &Context->Idents.get("__NSConstantStringImpl"));
3007 QualType FieldTypes[4];
3008
3009 // struct objc_object *receiver;
3010 FieldTypes[0] = Context->getObjCIdType();
3011 // int flags;
3012 FieldTypes[1] = Context->IntTy;
3013 // char *str;
3014 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3015 // long length;
3016 FieldTypes[3] = Context->LongTy;
3017
3018 // Create fields
3019 for (unsigned i = 0; i < 4; ++i) {
3020 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3021 ConstantStringDecl,
3022 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003023 SourceLocation(), nullptr,
3024 FieldTypes[i], nullptr,
3025 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003026 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003027 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003028 }
3029
3030 ConstantStringDecl->completeDefinition();
3031 }
3032 return Context->getTagDeclType(ConstantStringDecl);
3033}
3034
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003035/// getFunctionSourceLocation - returns start location of a function
3036/// definition. Complication arises when function has declared as
3037/// extern "C" or extern "C" {...}
3038static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3039 FunctionDecl *FD) {
3040 if (FD->isExternC() && !FD->isMain()) {
3041 const DeclContext *DC = FD->getDeclContext();
3042 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3043 // if it is extern "C" {...}, return function decl's own location.
3044 if (!LSD->getRBraceLoc().isValid())
3045 return LSD->getExternLoc();
3046 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003047 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003048 R.RewriteBlockLiteralFunctionDecl(FD);
3049 return FD->getTypeSpecStartLoc();
3050}
3051
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003052void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003053
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003054 SourceLocation Location = D->getLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003055
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003056 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003057 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003058 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3059 LineString += utostr(PLoc.getLine());
3060 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003061 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003062 if (isa<ObjCMethodDecl>(D))
3063 LineString += "\"";
3064 else LineString += "\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003065
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003066 Location = D->getBeginLoc();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003067 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3068 if (FD->isExternC() && !FD->isMain()) {
3069 const DeclContext *DC = FD->getDeclContext();
3070 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3071 // if it is extern "C" {...}, return function decl's own location.
3072 if (!LSD->getRBraceLoc().isValid())
3073 Location = LSD->getExternLoc();
3074 }
3075 }
3076 InsertText(Location, LineString);
3077 }
3078}
3079
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003080/// SynthMsgSendStretCallExpr - This routine translates message expression
3081/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3082/// nil check on receiver must be performed before calling objc_msgSend_stret.
3083/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3084/// msgSendType - function type of objc_msgSend_stret(...)
3085/// returnType - Result type of the method being synthesized.
3086/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003087/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003088/// starting with receiver.
3089/// Method - Method being rewritten.
3090Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +00003091 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003092 SmallVectorImpl<QualType> &ArgTypes,
3093 SmallVectorImpl<Expr*> &MsgExprs,
3094 ObjCMethodDecl *Method) {
3095 // Now do the "normal" pointer to function cast.
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003096 QualType FuncType = getSimpleFunctionType(
3097 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3098 QualType castType = Context->getPointerType(FuncType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003099
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003100 // build type for containing the objc_msgSend_stret object.
3101 static unsigned stretCount=0;
3102 std::string name = "__Stret"; name += utostr(stretCount);
Fangrui Song6907ce22018-07-30 19:24:48 +00003103 std::string str =
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003104 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003105 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003106 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003107 str += " {\n\t";
3108 str += name;
3109 str += "(id receiver, SEL sel";
3110 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003111 std::string ArgName = "arg"; ArgName += utostr(i);
3112 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3113 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003114 }
3115 // could be vararg.
3116 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003117 std::string ArgName = "arg"; ArgName += utostr(i);
3118 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3119 Context->getPrintingPolicy());
3120 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003121 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003122
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003123 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003124 str += "\t unsigned size = sizeof(";
3125 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003126
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003127 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003128
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003129 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3130 str += ")(void *)objc_msgSend)(receiver, sel";
3131 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3132 str += ", arg"; str += utostr(i);
3133 }
3134 // could be vararg.
3135 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3136 str += ", arg"; str += utostr(i);
3137 }
3138 str+= ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003139
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003140 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003141 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3142 str += "\t else\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003143
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003144 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3145 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3146 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3147 str += ", arg"; str += utostr(i);
3148 }
3149 // could be vararg.
3150 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3151 str += ", arg"; str += utostr(i);
3152 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003153 str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003154
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003155 str += "\t}\n";
3156 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3157 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003158 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003159 SourceLocation FunLocStart;
3160 if (CurFunctionDef)
3161 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3162 else {
3163 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003164 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003165 }
3166
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003167 InsertText(FunLocStart, str);
3168 ++stretCount;
Fangrui Song6907ce22018-07-30 19:24:48 +00003169
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003170 // AST for __Stretn(receiver, args).s;
3171 IdentifierInfo *ID = &Context->Idents.get(name);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003172 FunctionDecl *FD =
3173 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3174 ID, FuncType, nullptr, SC_Extern, false, false);
Bruno Riccic5885cf2018-12-21 15:20:32 +00003175 DeclRefExpr *DRE = new (Context)
3176 DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3177 CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3178 VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003179
3180 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003181 SourceLocation(),
3182 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003183 returnType, nullptr,
3184 /*BitWidth=*/nullptr,
3185 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00003186 MemberExpr *ME = MemberExpr::CreateImplicit(
3187 *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003188
3189 return ME;
3190}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003191
Fariborz Jahanian11671902012-02-07 17:11:38 +00003192Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3193 SourceLocation StartLoc,
3194 SourceLocation EndLoc) {
3195 if (!SelGetUidFunctionDecl)
3196 SynthSelGetUidFunctionDecl();
3197 if (!MsgSendFunctionDecl)
3198 SynthMsgSendFunctionDecl();
3199 if (!MsgSendSuperFunctionDecl)
3200 SynthMsgSendSuperFunctionDecl();
3201 if (!MsgSendStretFunctionDecl)
3202 SynthMsgSendStretFunctionDecl();
3203 if (!MsgSendSuperStretFunctionDecl)
3204 SynthMsgSendSuperStretFunctionDecl();
3205 if (!MsgSendFpretFunctionDecl)
3206 SynthMsgSendFpretFunctionDecl();
3207 if (!GetClassFunctionDecl)
3208 SynthGetClassFunctionDecl();
3209 if (!GetSuperClassFunctionDecl)
3210 SynthGetSuperClassFunctionDecl();
3211 if (!GetMetaClassFunctionDecl)
3212 SynthGetMetaClassFunctionDecl();
3213
3214 // default to objc_msgSend().
3215 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3216 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003217 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003218 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003219 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003220 if (resultType->isRecordType())
3221 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3222 else if (resultType->isRealFloatingType())
3223 MsgSendFlavor = MsgSendFpretFunctionDecl;
3224 }
3225
3226 // Synthesize a call to objc_msgSend().
3227 SmallVector<Expr*, 8> MsgExprs;
3228 switch (Exp->getReceiverKind()) {
3229 case ObjCMessageExpr::SuperClass: {
3230 MsgSendFlavor = MsgSendSuperFunctionDecl;
3231 if (MsgSendStretFlavor)
3232 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3233 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3234
3235 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3236
3237 SmallVector<Expr*, 4> InitExprs;
3238
3239 // set the receiver to self, the first argument to all methods.
3240 InitExprs.push_back(
3241 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3242 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003243 new (Context) DeclRefExpr(*Context,
3244 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003245 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003246 Context->getObjCIdType(),
3247 VK_RValue,
3248 SourceLocation()))
3249 ); // set the 'receiver'.
3250
3251 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3252 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003253 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003254 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003255 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003256 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003257 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003258 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003259 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003260 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003261
Fariborz Jahanian11671902012-02-07 17:11:38 +00003262 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3263 // To turn off a warning, type-cast to 'id'
3264 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3265 NoTypeInfoCStyleCastExpr(Context,
3266 Context->getObjCIdType(),
3267 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003268 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003269 QualType superType = getSuperStructType();
3270 Expr *SuperRep;
3271
3272 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003273 SynthSuperConstructorFunctionDecl();
3274 // Simulate a constructor call...
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003275 DeclRefExpr *DRE = new (Context)
3276 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3277 VK_LValue, SourceLocation());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003278 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3279 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003280 // The code for super is a little tricky to prevent collision with
3281 // the structure definition in the header. The rewriter has it's own
3282 // internal definition (__rw_objc_super) that is uses. This is why
3283 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003284 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003285 //
3286 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3287 Context->getPointerType(SuperRep->getType()),
3288 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003289 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003290 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3291 Context->getPointerType(superType),
3292 CK_BitCast, SuperRep);
3293 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003294 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003295 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003296 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003297 SourceLocation());
3298 TypeSourceInfo *superTInfo
3299 = Context->getTrivialTypeSourceInfo(superType);
3300 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3301 superType, VK_LValue,
3302 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003303 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003304 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3305 Context->getPointerType(SuperRep->getType()),
3306 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003307 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003308 }
3309 MsgExprs.push_back(SuperRep);
3310 break;
3311 }
3312
3313 case ObjCMessageExpr::Class: {
3314 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003315 ObjCInterfaceDecl *Class
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003316 = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003317 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003318 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003319 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003320 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003321 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3322 Context->getObjCIdType(),
3323 CK_BitCast, Cls);
3324 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003325 break;
3326 }
3327
3328 case ObjCMessageExpr::SuperInstance:{
3329 MsgSendFlavor = MsgSendSuperFunctionDecl;
3330 if (MsgSendStretFlavor)
3331 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3332 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3333 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3334 SmallVector<Expr*, 4> InitExprs;
3335
3336 InitExprs.push_back(
3337 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3338 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003339 new (Context) DeclRefExpr(*Context,
3340 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003341 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003342 Context->getObjCIdType(),
3343 VK_RValue, SourceLocation()))
3344 ); // set the 'receiver'.
Fangrui Song6907ce22018-07-30 19:24:48 +00003345
Fariborz Jahanian11671902012-02-07 17:11:38 +00003346 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3347 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003348 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003349 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003350 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003352 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003353 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003354 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003355 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003356
Fariborz Jahanian11671902012-02-07 17:11:38 +00003357 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3358 // To turn off a warning, type-cast to 'id'
3359 InitExprs.push_back(
3360 // set 'super class', using class_getSuperclass().
3361 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3362 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003363 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003364 QualType superType = getSuperStructType();
3365 Expr *SuperRep;
3366
3367 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003368 SynthSuperConstructorFunctionDecl();
3369 // Simulate a constructor call...
Bruno Riccic5885cf2018-12-21 15:20:32 +00003370 DeclRefExpr *DRE = new (Context)
3371 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3372 VK_LValue, SourceLocation());
3373 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3374 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003375 // The code for super is a little tricky to prevent collision with
3376 // the structure definition in the header. The rewriter has it's own
3377 // internal definition (__rw_objc_super) that is uses. This is why
3378 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003379 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 //
3381 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3382 Context->getPointerType(SuperRep->getType()),
3383 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003384 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003385 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3386 Context->getPointerType(superType),
3387 CK_BitCast, SuperRep);
3388 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003389 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003390 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003391 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003392 SourceLocation());
3393 TypeSourceInfo *superTInfo
3394 = Context->getTrivialTypeSourceInfo(superType);
3395 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3396 superType, VK_RValue, ILE,
3397 false);
3398 }
3399 MsgExprs.push_back(SuperRep);
3400 break;
3401 }
3402
3403 case ObjCMessageExpr::Instance: {
3404 // Remove all type-casts because it may contain objc-style types; e.g.
3405 // Foo<Proto> *.
3406 Expr *recExpr = Exp->getInstanceReceiver();
3407 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3408 recExpr = CE->getSubExpr();
3409 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3410 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3411 ? CK_BlockPointerToObjCPointerCast
3412 : CK_CPointerToObjCPointerCast;
3413
3414 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3415 CK, recExpr);
3416 MsgExprs.push_back(recExpr);
3417 break;
3418 }
3419 }
3420
3421 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3422 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003423 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003424 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003425 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003426 MsgExprs.push_back(SelExp);
3427
3428 // Now push any user supplied arguments.
3429 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3430 Expr *userExpr = Exp->getArg(i);
3431 // Make all implicit casts explicit...ICE comes in handy:-)
3432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3433 // Reuse the ICE type, it is exactly what the doctor ordered.
3434 QualType type = ICE->getType();
3435 if (needToScanForQualifiers(type))
3436 type = Context->getObjCIdType();
3437 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3438 (void)convertBlockPointerToFunctionPointer(type);
3439 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3440 CastKind CK;
Fangrui Song6907ce22018-07-30 19:24:48 +00003441 if (SubExpr->getType()->isIntegralType(*Context) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003442 type->isBooleanType()) {
3443 CK = CK_IntegralToBoolean;
3444 } else if (type->isObjCObjectPointerType()) {
3445 if (SubExpr->getType()->isBlockPointerType()) {
3446 CK = CK_BlockPointerToObjCPointerCast;
3447 } else if (SubExpr->getType()->isPointerType()) {
3448 CK = CK_CPointerToObjCPointerCast;
3449 } else {
3450 CK = CK_BitCast;
3451 }
3452 } else {
3453 CK = CK_BitCast;
3454 }
3455
3456 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3457 }
3458 // Make id<P...> cast into an 'id' cast.
3459 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3460 if (CE->getType()->isObjCQualifiedIdType()) {
3461 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3462 userExpr = CE->getSubExpr();
3463 CastKind CK;
3464 if (userExpr->getType()->isIntegralType(*Context)) {
3465 CK = CK_IntegralToPointer;
3466 } else if (userExpr->getType()->isBlockPointerType()) {
3467 CK = CK_BlockPointerToObjCPointerCast;
3468 } else if (userExpr->getType()->isPointerType()) {
3469 CK = CK_CPointerToObjCPointerCast;
3470 } else {
3471 CK = CK_BitCast;
3472 }
3473 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3474 CK, userExpr);
3475 }
3476 }
3477 MsgExprs.push_back(userExpr);
3478 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3479 // out the argument in the original expression (since we aren't deleting
3480 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3481 //Exp->setArg(i, 0);
3482 }
3483 // Generate the funky cast.
3484 CastExpr *cast;
3485 SmallVector<QualType, 8> ArgTypes;
3486 QualType returnType;
3487
3488 // Push 'id' and 'SEL', the 2 implicit arguments.
3489 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3490 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3491 else
3492 ArgTypes.push_back(Context->getObjCIdType());
3493 ArgTypes.push_back(Context->getObjCSelType());
3494 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3495 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003496 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003497 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003498 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003499 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003500 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3501 (void)convertBlockPointerToFunctionPointer(t);
3502 ArgTypes.push_back(t);
3503 }
3504 returnType = Exp->getType();
3505 convertToUnqualifiedObjCType(returnType);
3506 (void)convertBlockPointerToFunctionPointer(returnType);
3507 } else {
3508 returnType = Context->getObjCIdType();
3509 }
3510 // Get the type, we will need to reference it in a couple spots.
3511 QualType msgSendType = MsgSendFlavor->getType();
3512
3513 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003514 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3515 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003516
3517 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3518 // If we don't do this cast, we get the following bizarre warning/note:
3519 // xx.m:13: warning: function called through a non-compatible type
3520 // xx.m:13: note: if this code is reached, the program will abort
3521 cast = NoTypeInfoCStyleCastExpr(Context,
3522 Context->getPointerType(Context->VoidTy),
3523 CK_BitCast, DRE);
3524
3525 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003526 // If we don't have a method decl, force a variadic cast.
3527 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003528 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003529 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003530 castType = Context->getPointerType(castType);
3531 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3532 cast);
3533
3534 // Don't forget the parens to enforce the proper binding.
3535 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3536
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003537 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00003538 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3539 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003540 Stmt *ReplacingStmt = CE;
3541 if (MsgSendStretFlavor) {
3542 // We have the method which returns a struct/union. Must also generate
3543 // call to objc_msgSend_stret and hang both varieties on a conditional
3544 // expression which dictate which one to envoke depending on size of
3545 // method's return type.
3546
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003547 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3548 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003549 ArgTypes, MsgExprs,
3550 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003551 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003552 }
3553 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3554 return ReplacingStmt;
3555}
3556
3557Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003558 Stmt *ReplacingStmt =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003559 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003560
3561 // Now do the actual rewrite.
3562 ReplaceStmt(Exp, ReplacingStmt);
3563
3564 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3565 return ReplacingStmt;
3566}
3567
3568// typedef struct objc_object Protocol;
3569QualType RewriteModernObjC::getProtocolType() {
3570 if (!ProtocolTypeDecl) {
3571 TypeSourceInfo *TInfo
3572 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3573 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3574 SourceLocation(), SourceLocation(),
3575 &Context->Idents.get("Protocol"),
3576 TInfo);
3577 }
3578 return Context->getTypeDeclType(ProtocolTypeDecl);
3579}
3580
3581/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3582/// a synthesized/forward data reference (to the protocol's metadata).
3583/// The forward references (and metadata) are generated in
3584/// RewriteModernObjC::HandleTranslationUnit().
3585Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003586 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003587 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003588 IdentifierInfo *ID = &Context->Idents.get(Name);
3589 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003590 SourceLocation(), ID, getProtocolType(),
3591 nullptr, SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003592 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3593 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3594 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003595 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003596 ReplaceStmt(Exp, castExpr);
3597 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3598 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3599 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003600}
3601
Fangrui Song6907ce22018-07-30 19:24:48 +00003602/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3603/// is defined inside an objective-c class. If so, it returns true.
3604bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003605 TagDecl *Tag,
3606 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003607 if (!IDecl)
3608 return false;
3609 SourceLocation TagLocation;
3610 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3611 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003612 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003613 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003614 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003615 TagLocation = RD->getLocation();
3616 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003617 IDecl->getLocation(), TagLocation);
3618 }
3619 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3620 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3621 return false;
3622 IsNamedDefinition = true;
3623 TagLocation = ED->getLocation();
3624 return Context->getSourceManager().isBeforeInTranslationUnit(
3625 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003626 }
3627 return false;
3628}
3629
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003630/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003631/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003632bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003633 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003634 if (isa<TypedefType>(Type)) {
3635 Result += "\t";
3636 return false;
3637 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003638
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003639 if (Type->isArrayType()) {
3640 QualType ElemTy = Context->getBaseElementType(Type);
3641 return RewriteObjCFieldDeclType(ElemTy, Result);
3642 }
3643 else if (Type->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003644 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003645 if (RD->isCompleteDefinition()) {
3646 if (RD->isStruct())
3647 Result += "\n\tstruct ";
3648 else if (RD->isUnion())
3649 Result += "\n\tunion ";
3650 else
3651 assert(false && "class not allowed as an ivar type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003652
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003653 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003654 if (GlobalDefinedTags.count(RD)) {
3655 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003656 Result += " ";
3657 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003658 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003659 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003660 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003661 RewriteObjCFieldDecl(FD, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003662 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003663 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003664 }
3665 }
3666 else if (Type->isEnumeralType()) {
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003667 EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003668 if (ED->isCompleteDefinition()) {
3669 Result += "\n\tenum ";
3670 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003671 if (GlobalDefinedTags.count(ED)) {
3672 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003673 Result += " ";
3674 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003675 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003676
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003677 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003678 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003679 Result += "\t"; Result += EC->getName(); Result += " = ";
3680 llvm::APSInt Val = EC->getInitVal();
3681 Result += Val.toString(10);
3682 Result += ",\n";
3683 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003684 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003685 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003686 }
3687 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003688
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003689 Result += "\t";
3690 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003691 return false;
3692}
3693
3694
3695/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3696/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003697void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003698 std::string &Result) {
3699 QualType Type = fieldDecl->getType();
3700 std::string Name = fieldDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003701
3702 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003703 if (!EleboratedType)
3704 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003705 Result += Name;
3706 if (fieldDecl->isBitField()) {
3707 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3708 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003709 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003710 const ArrayType *AT = Context->getAsArrayType(Type);
3711 do {
3712 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003713 Result += "[";
3714 llvm::APInt Dim = CAT->getSize();
3715 Result += utostr(Dim.getZExtValue());
3716 Result += "]";
3717 }
Eli Friedman07bab732012-12-13 01:43:21 +00003718 AT = Context->getAsArrayType(AT->getElementType());
3719 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003720 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003721
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003722 Result += ";\n";
3723}
3724
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003725/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3726/// named aggregate types into the input buffer.
Fangrui Song6907ce22018-07-30 19:24:48 +00003727void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003728 std::string &Result) {
3729 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003730 if (isa<TypedefType>(Type))
3731 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003732 if (Type->isArrayType())
3733 Type = Context->getBaseElementType(Type);
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003734
3735 auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003736
3737 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003738 if (Type->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003739 TD = Type->castAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003740 }
3741 else if (Type->isEnumeralType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003742 TD = Type->castAs<EnumType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003743 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003744
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003745 if (TD) {
3746 if (GlobalDefinedTags.count(TD))
3747 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003748
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003749 bool IsNamedDefinition = false;
3750 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3751 RewriteObjCFieldDeclType(Type, Result);
3752 Result += ";";
3753 }
3754 if (IsNamedDefinition)
3755 GlobalDefinedTags.insert(TD);
3756 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003757}
3758
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003759unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3760 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3761 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3762 return IvarGroupNumber[IV];
3763 }
3764 unsigned GroupNo = 0;
3765 SmallVector<const ObjCIvarDecl *, 8> IVars;
3766 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3767 IVD; IVD = IVD->getNextIvar())
3768 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003769
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003770 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3771 if (IVars[i]->isBitField()) {
3772 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3773 while (i < e && IVars[i]->isBitField())
3774 IvarGroupNumber[IVars[i++]] = GroupNo;
3775 if (i < e)
3776 --i;
3777 }
3778
3779 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3780 return IvarGroupNumber[IV];
3781}
3782
3783QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3784 ObjCIvarDecl *IV,
3785 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3786 std::string StructTagName;
3787 ObjCIvarBitfieldGroupType(IV, StructTagName);
3788 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3789 Context->getTranslationUnitDecl(),
3790 SourceLocation(), SourceLocation(),
3791 &Context->Idents.get(StructTagName));
3792 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3793 ObjCIvarDecl *Ivar = IVars[i];
3794 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3795 &Context->Idents.get(Ivar->getName()),
3796 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003797 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3798 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003799 }
3800 RD->completeDefinition();
3801 return Context->getTagDeclType(RD);
3802}
3803
3804QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3805 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3806 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3807 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3808 if (GroupRecordType.count(tuple))
3809 return GroupRecordType[tuple];
Fangrui Song6907ce22018-07-30 19:24:48 +00003810
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003811 SmallVector<ObjCIvarDecl *, 8> IVars;
3812 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3813 IVD; IVD = IVD->getNextIvar()) {
3814 if (IVD->isBitField())
3815 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3816 else {
3817 if (!IVars.empty()) {
3818 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3819 // Generate the struct type for this group of bitfield ivars.
3820 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3821 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3822 IVars.clear();
3823 }
3824 }
3825 }
3826 if (!IVars.empty()) {
3827 // Do the last one.
3828 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3829 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3830 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3831 }
3832 QualType RetQT = GroupRecordType[tuple];
3833 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
Fangrui Song6907ce22018-07-30 19:24:48 +00003834
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003835 return RetQT;
3836}
3837
3838/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3839/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3840void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3841 std::string &Result) {
3842 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3843 Result += CDecl->getName();
3844 Result += "__GRBF_";
3845 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3846 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003847}
3848
3849/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3850/// Name of the struct would be: classname__T_n where n is the group number for
3851/// this ivar.
3852void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3853 std::string &Result) {
3854 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3855 Result += CDecl->getName();
3856 Result += "__T_";
3857 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3858 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003859}
3860
3861/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3862/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3863/// this ivar.
3864void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3865 std::string &Result) {
3866 Result += "OBJC_IVAR_$_";
3867 ObjCIvarBitfieldGroupDecl(IV, Result);
3868}
3869
3870#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3871 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3872 ++IX; \
3873 if (IX < ENDIX) \
3874 --IX; \
3875}
3876
Fariborz Jahanian11671902012-02-07 17:11:38 +00003877/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3878/// an objective-c class with ivars.
3879void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3880 std::string &Result) {
3881 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3882 assert(CDecl->getName() != "" &&
3883 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003884 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003885 SmallVector<ObjCIvarDecl *, 8> IVars;
3886 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003887 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003888 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003889
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003890 SourceLocation LocStart = CDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003891 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00003892
Fariborz Jahanian11671902012-02-07 17:11:38 +00003893 const char *startBuf = SM->getCharacterData(LocStart);
3894 const char *endBuf = SM->getCharacterData(LocEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +00003895
Fariborz Jahanian11671902012-02-07 17:11:38 +00003896 // If no ivars and no root or if its root, directly or indirectly,
3897 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003898 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003899 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3900 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3901 ReplaceText(LocStart, endBuf-startBuf, Result);
3902 return;
3903 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003904
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003905 // Insert named struct/union definitions inside class to
3906 // outer scope. This follows semantics of locally defined
3907 // struct/unions in objective-c classes.
3908 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3909 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003910
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003911 // Insert named structs which are syntheized to group ivar bitfields
3912 // to outer scope as well.
3913 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3914 if (IVars[i]->isBitField()) {
3915 ObjCIvarDecl *IV = IVars[i];
3916 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3917 RewriteObjCFieldDeclType(QT, Result);
3918 Result += ";";
3919 // skip over ivar bitfields in this group.
3920 SKIP_BITFIELDS(i , e, IVars);
3921 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003922
Fariborz Jahanian11671902012-02-07 17:11:38 +00003923 Result += "\nstruct ";
3924 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003925 Result += "_IMPL {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003926
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003927 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003928 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3929 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3930 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003931 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003932
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003933 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3934 if (IVars[i]->isBitField()) {
3935 ObjCIvarDecl *IV = IVars[i];
3936 Result += "\tstruct ";
3937 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3938 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3939 // skip over ivar bitfields in this group.
3940 SKIP_BITFIELDS(i , e, IVars);
3941 }
3942 else
3943 RewriteObjCFieldDecl(IVars[i], Result);
3944 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003945
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003946 Result += "};\n";
3947 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3948 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003949 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003950 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003951 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003952}
3953
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003954/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3955/// have been referenced in an ivar access expression.
3956void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3957 std::string &Result) {
3958 // write out ivar offset symbols which have been referenced in an ivar
3959 // access expression.
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003960 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3961
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003962 if (Ivars.empty())
3963 return;
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003964
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003965 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003966 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003967 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3968 unsigned GroupNo = 0;
3969 if (IvarDecl->isBitField()) {
3970 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3971 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3972 continue;
3973 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003974 Result += "\n";
3975 if (LangOpts.MicrosoftExt)
3976 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003977 Result += "extern \"C\" ";
Fangrui Song6907ce22018-07-30 19:24:48 +00003978 if (LangOpts.MicrosoftExt &&
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003979 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003980 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3981 Result += "__declspec(dllimport) ";
3982
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003983 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003984 if (IvarDecl->isBitField()) {
3985 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3986 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3987 }
3988 else
3989 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003990 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003991 }
3992}
3993
Fariborz Jahanian11671902012-02-07 17:11:38 +00003994//===----------------------------------------------------------------------===//
3995// Meta Data Emission
3996//===----------------------------------------------------------------------===//
3997
Fariborz Jahanian11671902012-02-07 17:11:38 +00003998/// RewriteImplementations - This routine rewrites all method implementations
3999/// and emits meta-data.
4000
4001void RewriteModernObjC::RewriteImplementations() {
4002 int ClsDefCount = ClassImplementation.size();
4003 int CatDefCount = CategoryImplementation.size();
4004
4005 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004006 for (int i = 0; i < ClsDefCount; i++) {
4007 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4008 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4009 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004010 assert(false &&
4011 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004012 RewriteImplementationDecl(OIMP);
4013 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004014
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004015 for (int i = 0; i < CatDefCount; i++) {
4016 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4017 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4018 if (CDecl->isImplicitInterfaceDecl())
4019 assert(false &&
4020 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004021 RewriteImplementationDecl(CIMP);
4022 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004023}
4024
Fangrui Song6907ce22018-07-30 19:24:48 +00004025void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004026 const std::string &Name,
4027 ValueDecl *VD, bool def) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004028 assert(BlockByRefDeclNo.count(VD) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004029 "RewriteByRefString: ByRef decl missing");
4030 if (def)
4031 ResultStr += "struct ";
Fangrui Song6907ce22018-07-30 19:24:48 +00004032 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004033 "_" + utostr(BlockByRefDeclNo[VD]) ;
4034}
4035
4036static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4037 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4038 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4039 return false;
4040}
4041
4042std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4043 StringRef funcName,
4044 std::string Tag) {
4045 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004046 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004047 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004048 SourceLocation BlockLoc = CE->getExprLoc();
4049 std::string S;
4050 ConvertSourceLocationToLineDirective(BlockLoc, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00004051
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004052 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4053 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004054
4055 BlockDecl *BD = CE->getBlockDecl();
4056
4057 if (isa<FunctionNoProtoType>(AFT)) {
4058 // No user-supplied arguments. Still need to pass in a pointer to the
4059 // block (to reference imported block decl refs).
4060 S += "(" + StructRef + " *__cself)";
4061 } else if (BD->param_empty()) {
4062 S += "(" + StructRef + " *__cself)";
4063 } else {
4064 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4065 assert(FT && "SynthesizeBlockFunc: No function proto");
4066 S += '(';
4067 // first add the implicit argument.
4068 S += StructRef + " *__cself, ";
4069 std::string ParamStr;
4070 for (BlockDecl::param_iterator AI = BD->param_begin(),
4071 E = BD->param_end(); AI != E; ++AI) {
4072 if (AI != BD->param_begin()) S += ", ";
4073 ParamStr = (*AI)->getNameAsString();
4074 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004075 (void)convertBlockPointerToFunctionPointer(QT);
4076 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004077 S += ParamStr;
4078 }
4079 if (FT->isVariadic()) {
4080 if (!BD->param_empty()) S += ", ";
4081 S += "...";
4082 }
4083 S += ')';
4084 }
4085 S += " {\n";
4086
4087 // Create local declarations to avoid rewriting all closure decl ref exprs.
4088 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004089 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004090 E = BlockByRefDecls.end(); I != E; ++I) {
4091 S += " ";
4092 std::string Name = (*I)->getNameAsString();
4093 std::string TypeString;
4094 RewriteByRefString(TypeString, Name, (*I));
4095 TypeString += " *";
4096 Name = TypeString + Name;
4097 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4098 }
4099 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004100 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004101 E = BlockByCopyDecls.end(); I != E; ++I) {
4102 S += " ";
4103 // Handle nested closure invocation. For example:
4104 //
4105 // void (^myImportedClosure)(void);
4106 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4107 //
4108 // void (^anotherClosure)(void);
4109 // anotherClosure = ^(void) {
4110 // myImportedClosure(); // import and invoke the closure
4111 // };
4112 //
4113 if (isTopLevelBlockPointerType((*I)->getType())) {
4114 RewriteBlockPointerTypeVariable(S, (*I));
4115 S += " = (";
4116 RewriteBlockPointerType(S, (*I)->getType());
4117 S += ")";
4118 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4119 }
4120 else {
4121 std::string Name = (*I)->getNameAsString();
4122 QualType QT = (*I)->getType();
4123 if (HasLocalVariableExternalStorage(*I))
4124 QT = Context->getPointerType(QT);
4125 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00004126 S += Name + " = __cself->" +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004127 (*I)->getNameAsString() + "; // bound by copy\n";
4128 }
4129 }
4130 std::string RewrittenStr = RewrittenBlockExprs[CE];
4131 const char *cstr = RewrittenStr.c_str();
4132 while (*cstr++ != '{') ;
4133 S += cstr;
4134 S += "\n";
4135 return S;
4136}
4137
4138std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4139 StringRef funcName,
4140 std::string Tag) {
4141 std::string StructRef = "struct " + Tag;
4142 std::string S = "static void __";
4143
4144 S += funcName;
4145 S += "_block_copy_" + utostr(i);
4146 S += "(" + StructRef;
4147 S += "*dst, " + StructRef;
4148 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004149 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004150 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004151 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004152 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004153 S += VD->getNameAsString();
4154 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004155 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4156 else if (VD->getType()->isBlockPointerType())
4157 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4158 else
4159 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4160 }
4161 S += "}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004162
Fariborz Jahanian11671902012-02-07 17:11:38 +00004163 S += "\nstatic void __";
4164 S += funcName;
4165 S += "_block_dispose_" + utostr(i);
4166 S += "(" + StructRef;
4167 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004168 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004169 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004170 S += VD->getNameAsString();
4171 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004172 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4173 else if (VD->getType()->isBlockPointerType())
4174 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4175 else
4176 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4177 }
4178 S += "}\n";
4179 return S;
4180}
4181
Fangrui Song6907ce22018-07-30 19:24:48 +00004182std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004183 std::string Desc) {
4184 std::string S = "\nstruct " + Tag;
4185 std::string Constructor = " " + Tag;
4186
4187 S += " {\n struct __block_impl impl;\n";
4188 S += " struct " + Desc;
4189 S += "* Desc;\n";
4190
4191 Constructor += "(void *fp, "; // Invoke function pointer.
4192 Constructor += "struct " + Desc; // Descriptor pointer.
4193 Constructor += " *desc";
4194
4195 if (BlockDeclRefs.size()) {
4196 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004197 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004198 E = BlockByCopyDecls.end(); I != E; ++I) {
4199 S += " ";
4200 std::string FieldName = (*I)->getNameAsString();
4201 std::string ArgName = "_" + FieldName;
4202 // Handle nested closure invocation. For example:
4203 //
4204 // void (^myImportedBlock)(void);
4205 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4206 //
4207 // void (^anotherBlock)(void);
4208 // anotherBlock = ^(void) {
4209 // myImportedBlock(); // import and invoke the closure
4210 // };
4211 //
4212 if (isTopLevelBlockPointerType((*I)->getType())) {
4213 S += "struct __block_impl *";
4214 Constructor += ", void *" + ArgName;
4215 } else {
4216 QualType QT = (*I)->getType();
4217 if (HasLocalVariableExternalStorage(*I))
4218 QT = Context->getPointerType(QT);
4219 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4220 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4221 Constructor += ", " + ArgName;
4222 }
4223 S += FieldName + ";\n";
4224 }
4225 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004226 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004227 E = BlockByRefDecls.end(); I != E; ++I) {
4228 S += " ";
4229 std::string FieldName = (*I)->getNameAsString();
4230 std::string ArgName = "_" + FieldName;
4231 {
4232 std::string TypeString;
4233 RewriteByRefString(TypeString, FieldName, (*I));
4234 TypeString += " *";
4235 FieldName = TypeString + FieldName;
4236 ArgName = TypeString + ArgName;
4237 Constructor += ", " + ArgName;
4238 }
4239 S += FieldName + "; // by ref\n";
4240 }
4241 // Finish writing the constructor.
4242 Constructor += ", int flags=0)";
4243 // Initialize all "by copy" arguments.
4244 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004245 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004246 E = BlockByCopyDecls.end(); I != E; ++I) {
4247 std::string Name = (*I)->getNameAsString();
4248 if (firsTime) {
4249 Constructor += " : ";
4250 firsTime = false;
4251 }
4252 else
4253 Constructor += ", ";
4254 if (isTopLevelBlockPointerType((*I)->getType()))
4255 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4256 else
4257 Constructor += Name + "(_" + Name + ")";
4258 }
4259 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004260 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004261 E = BlockByRefDecls.end(); I != E; ++I) {
4262 std::string Name = (*I)->getNameAsString();
4263 if (firsTime) {
4264 Constructor += " : ";
4265 firsTime = false;
4266 }
4267 else
4268 Constructor += ", ";
4269 Constructor += Name + "(_" + Name + "->__forwarding)";
4270 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004271
Fariborz Jahanian11671902012-02-07 17:11:38 +00004272 Constructor += " {\n";
4273 if (GlobalVarDecl)
4274 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4275 else
4276 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4277 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4278
4279 Constructor += " Desc = desc;\n";
4280 } else {
4281 // Finish writing the constructor.
4282 Constructor += ", int flags=0) {\n";
4283 if (GlobalVarDecl)
4284 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4285 else
4286 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4287 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4288 Constructor += " Desc = desc;\n";
4289 }
4290 Constructor += " ";
4291 Constructor += "}\n";
4292 S += Constructor;
4293 S += "};\n";
4294 return S;
4295}
4296
Fangrui Song6907ce22018-07-30 19:24:48 +00004297std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004298 std::string ImplTag, int i,
4299 StringRef FunName,
4300 unsigned hasCopy) {
4301 std::string S = "\nstatic struct " + DescTag;
Fangrui Song6907ce22018-07-30 19:24:48 +00004302
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004303 S += " {\n size_t reserved;\n";
4304 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004305 if (hasCopy) {
4306 S += " void (*copy)(struct ";
4307 S += ImplTag; S += "*, struct ";
4308 S += ImplTag; S += "*);\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004309
Fariborz Jahanian11671902012-02-07 17:11:38 +00004310 S += " void (*dispose)(struct ";
4311 S += ImplTag; S += "*);\n";
4312 }
4313 S += "} ";
4314
4315 S += DescTag + "_DATA = { 0, sizeof(struct ";
4316 S += ImplTag + ")";
4317 if (hasCopy) {
4318 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4319 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4320 }
4321 S += "};\n";
4322 return S;
4323}
4324
4325void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4326 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004327 bool RewriteSC = (GlobalVarDecl &&
4328 !Blocks.empty() &&
4329 GlobalVarDecl->getStorageClass() == SC_Static &&
4330 GlobalVarDecl->getType().getCVRQualifiers());
4331 if (RewriteSC) {
4332 std::string SC(" void __");
4333 SC += GlobalVarDecl->getNameAsString();
4334 SC += "() {}";
4335 InsertText(FunLocStart, SC);
4336 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004337
Fariborz Jahanian11671902012-02-07 17:11:38 +00004338 // Insert closures that were part of the function.
4339 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4340 CollectBlockDeclRefInfo(Blocks[i]);
4341 // Need to copy-in the inner copied-in variables not actually used in this
4342 // block.
4343 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004344 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004345 ValueDecl *VD = Exp->getDecl();
4346 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004347 if (!VD->hasAttr<BlocksAttr>()) {
4348 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4349 BlockByCopyDeclsPtrSet.insert(VD);
4350 BlockByCopyDecls.push_back(VD);
4351 }
4352 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004353 }
John McCall113bee02012-03-10 09:33:50 +00004354
4355 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004356 BlockByRefDeclsPtrSet.insert(VD);
4357 BlockByRefDecls.push_back(VD);
4358 }
John McCall113bee02012-03-10 09:33:50 +00004359
Fariborz Jahanian11671902012-02-07 17:11:38 +00004360 // imported objects in the inner blocks not used in the outer
4361 // blocks must be copied/disposed in the outer block as well.
Fangrui Song6907ce22018-07-30 19:24:48 +00004362 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004363 VD->getType()->isBlockPointerType())
4364 ImportedBlockDecls.insert(VD);
4365 }
4366
4367 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4368 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4369
4370 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4371
4372 InsertText(FunLocStart, CI);
4373
4374 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4375
4376 InsertText(FunLocStart, CF);
4377
4378 if (ImportedBlockDecls.size()) {
4379 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4380 InsertText(FunLocStart, HF);
4381 }
4382 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4383 ImportedBlockDecls.size() > 0);
4384 InsertText(FunLocStart, BD);
4385
4386 BlockDeclRefs.clear();
4387 BlockByRefDecls.clear();
4388 BlockByRefDeclsPtrSet.clear();
4389 BlockByCopyDecls.clear();
4390 BlockByCopyDeclsPtrSet.clear();
4391 ImportedBlockDecls.clear();
4392 }
4393 if (RewriteSC) {
4394 // Must insert any 'const/volatile/static here. Since it has been
4395 // removed as result of rewriting of block literals.
4396 std::string SC;
4397 if (GlobalVarDecl->getStorageClass() == SC_Static)
4398 SC = "static ";
4399 if (GlobalVarDecl->getType().isConstQualified())
4400 SC += "const ";
4401 if (GlobalVarDecl->getType().isVolatileQualified())
4402 SC += "volatile ";
4403 if (GlobalVarDecl->getType().isRestrictQualified())
4404 SC += "restrict ";
4405 InsertText(FunLocStart, SC);
4406 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004407 if (GlobalConstructionExp) {
4408 // extra fancy dance for global literal expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00004409
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004410 // Always the latest block expression on the block stack.
4411 std::string Tag = "__";
4412 Tag += FunName;
4413 Tag += "_block_impl_";
4414 Tag += utostr(Blocks.size()-1);
4415 std::string globalBuf = "static ";
4416 globalBuf += Tag; globalBuf += " ";
4417 std::string SStr;
Fangrui Song6907ce22018-07-30 19:24:48 +00004418
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004419 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004420 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4421 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004422 globalBuf += constructorExprBuf.str();
4423 globalBuf += ";\n";
4424 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004425 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004426 }
4427
Fariborz Jahanian11671902012-02-07 17:11:38 +00004428 Blocks.clear();
4429 InnerDeclRefsCount.clear();
4430 InnerDeclRefs.clear();
4431 RewrittenBlockExprs.clear();
4432}
4433
4434void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004435 SourceLocation FunLocStart =
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004436 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4437 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004438 StringRef FuncName = FD->getName();
4439
4440 SynthesizeBlockLiterals(FunLocStart, FuncName);
4441}
4442
4443static void BuildUniqueMethodName(std::string &Name,
4444 ObjCMethodDecl *MD) {
4445 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Benjamin Krameradcd0262020-01-28 20:23:46 +01004446 Name = std::string(IFace->getName());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004447 Name += "__" + MD->getSelector().getAsString();
4448 // Convert colons to underscores.
4449 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00004450 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004451 Name.replace(loc, 1, "_");
4452}
4453
4454void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004455 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4456 // SourceLocation FunLocStart = MD->getBeginLoc();
4457 SourceLocation FunLocStart = MD->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004458 std::string FuncName;
4459 BuildUniqueMethodName(FuncName, MD);
4460 SynthesizeBlockLiterals(FunLocStart, FuncName);
4461}
4462
4463void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004464 for (Stmt *SubStmt : S->children())
4465 if (SubStmt) {
4466 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004467 GetBlockDeclRefExprs(CBE->getBody());
4468 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004469 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004470 }
4471 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004472 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004473 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004474 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004475 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004476 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004477}
4478
Craig Topper5603df42013-07-05 19:34:19 +00004479void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4480 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004481 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004482 for (Stmt *SubStmt : S->children())
4483 if (SubStmt) {
4484 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004485 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4486 GetInnerBlockDeclRefExprs(CBE->getBody(),
4487 InnerBlockDeclRefs,
4488 InnerContexts);
4489 }
4490 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004491 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004492 }
4493 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004494 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004495 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004496 HasLocalVariableExternalStorage(DRE->getDecl())) {
4497 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004498 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004499 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004500 if (Var->isFunctionOrMethodVarDecl())
4501 ImportedLocalExternalDecls.insert(Var);
4502 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004503 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004504}
4505
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004506/// convertObjCTypeToCStyleType - This routine converts such objc types
4507/// as qualified objects, and blocks to their closest c/c++ types that
4508/// it can. It returns true if input type was modified.
4509bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4510 QualType oldT = T;
4511 convertBlockPointerToFunctionPointer(T);
4512 if (T->isFunctionPointerType()) {
4513 QualType PointeeTy;
4514 if (const PointerType* PT = T->getAs<PointerType>()) {
4515 PointeeTy = PT->getPointeeType();
4516 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4517 T = convertFunctionTypeOfBlocks(FT);
4518 T = Context->getPointerType(T);
4519 }
4520 }
4521 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004522
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004523 convertToUnqualifiedObjCType(T);
4524 return T != oldT;
4525}
4526
Fariborz Jahanian11671902012-02-07 17:11:38 +00004527/// convertFunctionTypeOfBlocks - This routine converts a function type
4528/// whose result type may be a block pointer or whose argument type(s)
4529/// might be block pointers to an equivalent function type replacing
4530/// all block pointers to function pointers.
4531QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4532 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4533 // FTP will be null for closures that don't take arguments.
4534 // Generate a funky cast.
4535 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004536 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004537 bool modified = convertObjCTypeToCStyleType(Res);
Fangrui Song6907ce22018-07-30 19:24:48 +00004538
Fariborz Jahanian11671902012-02-07 17:11:38 +00004539 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004540 for (auto &I : FTP->param_types()) {
4541 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004542 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004543 if (convertObjCTypeToCStyleType(t))
4544 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004545 ArgTypes.push_back(t);
4546 }
4547 }
4548 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004549 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004550 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004551 else FuncType = QualType(FT, 0);
4552 return FuncType;
4553}
4554
4555Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4556 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004557 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004558
4559 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4560 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004561 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4562 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004563 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004564 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4565 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4566 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004567 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004568 CPT = IEXPR->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004569 else if (const ConditionalOperator *CEXPR =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004570 dyn_cast<ConditionalOperator>(BlockExp)) {
4571 Expr *LHSExp = CEXPR->getLHS();
4572 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4573 Expr *RHSExp = CEXPR->getRHS();
4574 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4575 Expr *CONDExp = CEXPR->getCond();
4576 ConditionalOperator *CondExpr =
4577 new (Context) ConditionalOperator(CONDExp,
4578 SourceLocation(), cast<Expr>(LHSStmt),
4579 SourceLocation(), cast<Expr>(RHSStmt),
4580 Exp->getType(), VK_RValue, OK_Ordinary);
4581 return CondExpr;
4582 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4583 CPT = IRE->getType()->getAs<BlockPointerType>();
4584 } else if (const PseudoObjectExpr *POE
4585 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4586 CPT = POE->getType()->castAs<BlockPointerType>();
4587 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004588 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004589 }
4590 assert(CPT && "RewriteBlockClass: Bad type");
4591 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4592 assert(FT && "RewriteBlockClass: Bad type");
4593 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4594 // FTP will be null for closures that don't take arguments.
4595
4596 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4597 SourceLocation(), SourceLocation(),
4598 &Context->Idents.get("__block_impl"));
4599 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4600
4601 // Generate a funky cast.
4602 SmallVector<QualType, 8> ArgTypes;
4603
4604 // Push the block argument type.
4605 ArgTypes.push_back(PtrBlock);
4606 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004607 for (auto &I : FTP->param_types()) {
4608 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004609 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4610 if (!convertBlockPointerToFunctionPointer(t))
4611 convertToUnqualifiedObjCType(t);
4612 ArgTypes.push_back(t);
4613 }
4614 }
4615 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004616 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004617
4618 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4619
4620 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4621 CK_BitCast,
4622 const_cast<Expr*>(BlockExp));
4623 // Don't forget the parens to enforce the proper binding.
4624 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4625 BlkCast);
4626 //PE->dump();
4627
Craig Topper8ae12032014-05-07 06:21:57 +00004628 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004629 SourceLocation(),
4630 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004631 Context->VoidPtrTy, nullptr,
4632 /*BitWidth=*/nullptr, /*Mutable=*/true,
4633 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004634 MemberExpr *ME = MemberExpr::CreateImplicit(
4635 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004636
4637 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4638 CK_BitCast, ME);
4639 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004640
4641 SmallVector<Expr*, 8> BlkExprs;
4642 // Add the implicit argument.
4643 BlkExprs.push_back(BlkCast);
4644 // Add the user arguments.
4645 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4646 E = Exp->arg_end(); I != E; ++I) {
4647 BlkExprs.push_back(*I);
4648 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00004649 CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4650 VK_RValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004651 return CE;
4652}
4653
4654// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004655// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004656// For example:
4657//
4658// int main() {
4659// __block Foo *f;
4660// __block int i;
4661//
4662// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004663// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004664// i = 77;
4665// };
4666//}
John McCall113bee02012-03-10 09:33:50 +00004667Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004668 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanian11671902012-02-07 17:11:38 +00004669 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004670 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004671 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004672 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004673
4674 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004675 SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004676 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004677 Context->VoidPtrTy, nullptr,
4678 /*BitWidth=*/nullptr, /*Mutable=*/true,
4679 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004680 MemberExpr *ME = MemberExpr::CreateImplicit(
4681 *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004682
4683 StringRef Name = VD->getName();
4684 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004685 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004686 Context->VoidPtrTy, nullptr,
4687 /*BitWidth=*/nullptr, /*Mutable=*/true,
4688 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004689 ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4690 VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004691
4692 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004693 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4694 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004695 ME);
4696 ReplaceStmt(DeclRefExp, PE);
4697 return PE;
4698}
4699
Fangrui Song6907ce22018-07-30 19:24:48 +00004700// Rewrites the imported local variable V with external storage
Fariborz Jahanian11671902012-02-07 17:11:38 +00004701// (static, extern, etc.) as *V
4702//
4703Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4704 ValueDecl *VD = DRE->getDecl();
4705 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4706 if (!ImportedLocalExternalDecls.count(Var))
4707 return DRE;
4708 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4709 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00004710 DRE->getLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004711 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004712 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004713 Exp);
4714 ReplaceStmt(DRE, PE);
4715 return PE;
4716}
4717
4718void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4719 SourceLocation LocStart = CE->getLParenLoc();
4720 SourceLocation LocEnd = CE->getRParenLoc();
4721
4722 // Need to avoid trying to rewrite synthesized casts.
4723 if (LocStart.isInvalid())
4724 return;
4725 // Need to avoid trying to rewrite casts contained in macros.
4726 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4727 return;
4728
4729 const char *startBuf = SM->getCharacterData(LocStart);
4730 const char *endBuf = SM->getCharacterData(LocEnd);
4731 QualType QT = CE->getType();
4732 const Type* TypePtr = QT->getAs<Type>();
4733 if (isa<TypeOfExprType>(TypePtr)) {
4734 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4735 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4736 std::string TypeAsString = "(";
4737 RewriteBlockPointerType(TypeAsString, QT);
4738 TypeAsString += ")";
4739 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4740 return;
4741 }
4742 // advance the location to startArgList.
4743 const char *argPtr = startBuf;
4744
4745 while (*argPtr++ && (argPtr < endBuf)) {
4746 switch (*argPtr) {
4747 case '^':
4748 // Replace the '^' with '*'.
4749 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4750 ReplaceText(LocStart, 1, "*");
4751 break;
4752 }
4753 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004754}
4755
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004756void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4757 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004758 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4759 CastKind != CK_AnyPointerToBlockPointerCast)
4760 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004761
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004762 QualType QT = IC->getType();
4763 (void)convertBlockPointerToFunctionPointer(QT);
4764 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4765 std::string Str = "(";
4766 Str += TypeString;
4767 Str += ")";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004768 InsertText(IC->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004769}
4770
Fariborz Jahanian11671902012-02-07 17:11:38 +00004771void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4772 SourceLocation DeclLoc = FD->getLocation();
4773 unsigned parenCount = 0;
4774
4775 // We have 1 or more arguments that have closure pointers.
4776 const char *startBuf = SM->getCharacterData(DeclLoc);
4777 const char *startArgList = strchr(startBuf, '(');
4778
4779 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4780
4781 parenCount++;
4782 // advance the location to startArgList.
4783 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4784 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4785
4786 const char *argPtr = startArgList;
4787
4788 while (*argPtr++ && parenCount) {
4789 switch (*argPtr) {
4790 case '^':
4791 // Replace the '^' with '*'.
4792 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4793 ReplaceText(DeclLoc, 1, "*");
4794 break;
4795 case '(':
4796 parenCount++;
4797 break;
4798 case ')':
4799 parenCount--;
4800 break;
4801 }
4802 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004803}
4804
4805bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4806 const FunctionProtoType *FTP;
4807 const PointerType *PT = QT->getAs<PointerType>();
4808 if (PT) {
4809 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4810 } else {
4811 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4812 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4813 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4814 }
4815 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004816 for (const auto &I : FTP->param_types())
4817 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004818 return true;
4819 }
4820 return false;
4821}
4822
4823bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4824 const FunctionProtoType *FTP;
4825 const PointerType *PT = QT->getAs<PointerType>();
4826 if (PT) {
4827 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4828 } else {
4829 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4830 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4831 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4832 }
4833 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004834 for (const auto &I : FTP->param_types()) {
4835 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004836 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004837 if (I->isObjCObjectPointerType() &&
4838 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004839 return true;
4840 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004841
Fariborz Jahanian11671902012-02-07 17:11:38 +00004842 }
4843 return false;
4844}
4845
4846void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4847 const char *&RParen) {
4848 const char *argPtr = strchr(Name, '(');
4849 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4850
4851 LParen = argPtr; // output the start.
4852 argPtr++; // skip past the left paren.
4853 unsigned parenCount = 1;
4854
4855 while (*argPtr && parenCount) {
4856 switch (*argPtr) {
4857 case '(': parenCount++; break;
4858 case ')': parenCount--; break;
4859 default: break;
4860 }
4861 if (parenCount) argPtr++;
4862 }
4863 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4864 RParen = argPtr; // output the end
4865}
4866
4867void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4868 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4869 RewriteBlockPointerFunctionArgs(FD);
4870 return;
4871 }
4872 // Handle Variables and Typedefs.
4873 SourceLocation DeclLoc = ND->getLocation();
4874 QualType DeclT;
4875 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4876 DeclT = VD->getType();
4877 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4878 DeclT = TDD->getUnderlyingType();
4879 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4880 DeclT = FD->getType();
4881 else
4882 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4883
4884 const char *startBuf = SM->getCharacterData(DeclLoc);
4885 const char *endBuf = startBuf;
4886 // scan backward (from the decl location) for the end of the previous decl.
4887 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4888 startBuf--;
4889 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4890 std::string buf;
4891 unsigned OrigLength=0;
4892 // *startBuf != '^' if we are dealing with a pointer to function that
4893 // may take block argument types (which will be handled below).
4894 if (*startBuf == '^') {
4895 // Replace the '^' with '*', computing a negative offset.
4896 buf = '*';
4897 startBuf++;
4898 OrigLength++;
4899 }
4900 while (*startBuf != ')') {
4901 buf += *startBuf;
4902 startBuf++;
4903 OrigLength++;
4904 }
4905 buf += ')';
4906 OrigLength++;
Fangrui Song6907ce22018-07-30 19:24:48 +00004907
Fariborz Jahanian11671902012-02-07 17:11:38 +00004908 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4909 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4910 // Replace the '^' with '*' for arguments.
4911 // Replace id<P> with id/*<>*/
4912 DeclLoc = ND->getLocation();
4913 startBuf = SM->getCharacterData(DeclLoc);
4914 const char *argListBegin, *argListEnd;
4915 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4916 while (argListBegin < argListEnd) {
4917 if (*argListBegin == '^')
4918 buf += '*';
4919 else if (*argListBegin == '<') {
Fangrui Song6907ce22018-07-30 19:24:48 +00004920 buf += "/*";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004921 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004922 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004923 while (*argListBegin != '>') {
4924 buf += *argListBegin++;
4925 OrigLength++;
4926 }
4927 buf += *argListBegin;
4928 buf += "*/";
4929 }
4930 else
4931 buf += *argListBegin;
4932 argListBegin++;
4933 OrigLength++;
4934 }
4935 buf += ')';
4936 OrigLength++;
4937 }
4938 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004939}
4940
Fariborz Jahanian11671902012-02-07 17:11:38 +00004941/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4942/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4943/// struct Block_byref_id_object *src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004944/// _Block_object_assign (&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004945/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4946/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004947/// _Block_object_assign(&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004948/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4949/// [|BLOCK_FIELD_IS_WEAK]) // block
4950/// }
4951/// And:
4952/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004953/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004954/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4955/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004956/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004957/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4958/// [|BLOCK_FIELD_IS_WEAK]) // block
4959/// }
4960
4961std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4962 int flag) {
4963 std::string S;
4964 if (CopyDestroyCache.count(flag))
4965 return S;
4966 CopyDestroyCache.insert(flag);
4967 S = "static void __Block_byref_id_object_copy_";
4968 S += utostr(flag);
4969 S += "(void *dst, void *src) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004970
Fariborz Jahanian11671902012-02-07 17:11:38 +00004971 // offset into the object pointer is computed as:
4972 // void * + void* + int + int + void* + void *
Fangrui Song6907ce22018-07-30 19:24:48 +00004973 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004974 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004975 unsigned VoidPtrSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004976 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004977
Fariborz Jahanian11671902012-02-07 17:11:38 +00004978 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4979 S += " _Block_object_assign((char*)dst + ";
4980 S += utostr(offset);
4981 S += ", *(void * *) ((char*)src + ";
4982 S += utostr(offset);
4983 S += "), ";
4984 S += utostr(flag);
4985 S += ");\n}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004986
Fariborz Jahanian11671902012-02-07 17:11:38 +00004987 S += "static void __Block_byref_id_object_dispose_";
4988 S += utostr(flag);
4989 S += "(void *src) {\n";
4990 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4991 S += utostr(offset);
4992 S += "), ";
4993 S += utostr(flag);
4994 S += ");\n}\n";
4995 return S;
4996}
4997
4998/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4999/// the declaration into:
5000/// struct __Block_byref_ND {
5001/// void *__isa; // NULL for everything except __weak pointers
5002/// struct __Block_byref_ND *__forwarding;
5003/// int32_t __flags;
5004/// int32_t __size;
5005/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5006/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5007/// typex ND;
5008/// };
5009///
5010/// It then replaces declaration of ND variable with:
Fangrui Song6907ce22018-07-30 19:24:48 +00005011/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5012/// __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005013/// ND=initializer-if-any};
5014///
5015///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005016void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5017 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005018 int flag = 0;
5019 int isa = 0;
5020 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5021 if (DeclLoc.isInvalid())
5022 // If type location is missing, it is because of missing type (a warning).
5023 // Use variable's location which is good for this case.
5024 DeclLoc = ND->getLocation();
5025 const char *startBuf = SM->getCharacterData(DeclLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005026 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005027 X = SM->getExpansionLoc(X);
5028 const char *endBuf = SM->getCharacterData(X);
5029 std::string Name(ND->getNameAsString());
5030 std::string ByrefType;
5031 RewriteByRefString(ByrefType, Name, ND, true);
5032 ByrefType += " {\n";
5033 ByrefType += " void *__isa;\n";
5034 RewriteByRefString(ByrefType, Name, ND);
5035 ByrefType += " *__forwarding;\n";
5036 ByrefType += " int __flags;\n";
5037 ByrefType += " int __size;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005038 // Add void *__Block_byref_id_object_copy;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005039 // void *__Block_byref_id_object_dispose; if needed.
5040 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005041 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005042 if (HasCopyAndDispose) {
5043 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5044 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5045 }
5046
5047 QualType T = Ty;
5048 (void)convertBlockPointerToFunctionPointer(T);
5049 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00005050
Fariborz Jahanian11671902012-02-07 17:11:38 +00005051 ByrefType += " " + Name + ";\n";
5052 ByrefType += "};\n";
5053 // Insert this type in global scope. It is needed by helper function.
5054 SourceLocation FunLocStart;
5055 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005056 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005057 else {
5058 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005059 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005060 }
5061 InsertText(FunLocStart, ByrefType);
Fangrui Song6907ce22018-07-30 19:24:48 +00005062
Fariborz Jahanian11671902012-02-07 17:11:38 +00005063 if (Ty.isObjCGCWeak()) {
5064 flag |= BLOCK_FIELD_IS_WEAK;
5065 isa = 1;
5066 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005067 if (HasCopyAndDispose) {
5068 flag = BLOCK_BYREF_CALLER;
5069 QualType Ty = ND->getType();
5070 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5071 if (Ty->isBlockPointerType())
5072 flag |= BLOCK_FIELD_IS_BLOCK;
5073 else
5074 flag |= BLOCK_FIELD_IS_OBJECT;
5075 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5076 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005077 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005078 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005079
5080 // struct __Block_byref_ND ND =
5081 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005082 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005083 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005084 // FIXME. rewriter does not support __block c++ objects which
5085 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005086 if (hasInit)
5087 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5088 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5089 if (CXXDecl && CXXDecl->isDefaultConstructor())
5090 hasInit = false;
5091 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005092
Fariborz Jahanian11671902012-02-07 17:11:38 +00005093 unsigned flags = 0;
5094 if (HasCopyAndDispose)
5095 flags |= BLOCK_HAS_COPY_DISPOSE;
5096 Name = ND->getNameAsString();
5097 ByrefType.clear();
5098 RewriteByRefString(ByrefType, Name, ND);
5099 std::string ForwardingCastType("(");
5100 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005101 ByrefType += " " + Name + " = {(void*)";
5102 ByrefType += utostr(isa);
5103 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5104 ByrefType += utostr(flags);
5105 ByrefType += ", ";
5106 ByrefType += "sizeof(";
5107 RewriteByRefString(ByrefType, Name, ND);
5108 ByrefType += ")";
5109 if (HasCopyAndDispose) {
5110 ByrefType += ", __Block_byref_id_object_copy_";
5111 ByrefType += utostr(flag);
5112 ByrefType += ", __Block_byref_id_object_dispose_";
5113 ByrefType += utostr(flag);
5114 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005115
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005116 if (!firstDecl) {
5117 // In multiple __block declarations, and for all but 1st declaration,
5118 // find location of the separating comma. This would be start location
5119 // where new text is to be inserted.
5120 DeclLoc = ND->getLocation();
5121 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5122 const char *commaBuf = startDeclBuf;
5123 while (*commaBuf != ',')
5124 commaBuf--;
5125 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5126 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5127 startBuf = commaBuf;
5128 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005129
Fariborz Jahanian11671902012-02-07 17:11:38 +00005130 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005131 ByrefType += "};\n";
5132 unsigned nameSize = Name.size();
Simon Pilgrim2c518802017-03-30 14:13:19 +00005133 // for block or function pointer declaration. Name is already
Fariborz Jahanian11671902012-02-07 17:11:38 +00005134 // part of the declaration.
5135 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5136 nameSize = 1;
5137 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5138 }
5139 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005140 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005141 SourceLocation startLoc;
5142 Expr *E = ND->getInit();
5143 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5144 startLoc = ECE->getLParenLoc();
5145 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005146 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005147 startLoc = SM->getExpansionLoc(startLoc);
5148 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005149 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005150
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005151 const char separator = lastDecl ? ';' : ',';
5152 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5153 const char *separatorBuf = strchr(startInitializerBuf, separator);
Fangrui Song6907ce22018-07-30 19:24:48 +00005154 assert((*separatorBuf == separator) &&
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005155 "RewriteByRefVar: can't find ';' or ','");
5156 SourceLocation separatorLoc =
5157 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00005158
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005159 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005160 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005161}
5162
5163void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5164 // Add initializers for any closure decl refs.
5165 GetBlockDeclRefExprs(Exp->getBody());
5166 if (BlockDeclRefs.size()) {
5167 // Unique all "by copy" declarations.
5168 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005169 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005170 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5171 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5172 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5173 }
5174 }
5175 // Unique all "by ref" declarations.
5176 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005177 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005178 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5179 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5180 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5181 }
5182 }
5183 // Find any imported blocks...they will need special attention.
5184 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005185 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005186 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005187 BlockDeclRefs[i]->getType()->isBlockPointerType())
5188 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5189 }
5190}
5191
5192FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5193 IdentifierInfo *ID = &Context->Idents.get(name);
5194 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5195 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005196 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005197 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005198}
5199
5200Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005201 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005202 const BlockDecl *block = Exp->getBlockDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00005203
Fariborz Jahanian11671902012-02-07 17:11:38 +00005204 Blocks.push_back(Exp);
5205
5206 CollectBlockDeclRefInfo(Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00005207
Fariborz Jahanian11671902012-02-07 17:11:38 +00005208 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005209 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005210 if (!InnerBlockDeclRefs.empty()) {
5211 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005212 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005213 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005214 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005215 // We need to save the copied-in variables in nested
5216 // blocks because it is needed at the end for some of the API generations.
5217 // See SynthesizeBlockLiterals routine.
5218 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5219 BlockDeclRefs.push_back(Exp);
5220 BlockByCopyDeclsPtrSet.insert(VD);
5221 BlockByCopyDecls.push_back(VD);
5222 }
John McCall113bee02012-03-10 09:33:50 +00005223 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005224 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5225 BlockDeclRefs.push_back(Exp);
5226 BlockByRefDeclsPtrSet.insert(VD);
5227 BlockByRefDecls.push_back(VD);
5228 }
5229 }
5230 // Find any imported blocks...they will need special attention.
5231 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005232 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005233 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005234 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5235 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5236 }
5237 InnerDeclRefsCount.push_back(countOfInnerDecls);
Fangrui Song6907ce22018-07-30 19:24:48 +00005238
Fariborz Jahanian11671902012-02-07 17:11:38 +00005239 std::string FuncName;
5240
5241 if (CurFunctionDef)
5242 FuncName = CurFunctionDef->getNameAsString();
5243 else if (CurMethodDef)
5244 BuildUniqueMethodName(FuncName, CurMethodDef);
5245 else if (GlobalVarDecl)
5246 FuncName = std::string(GlobalVarDecl->getNameAsString());
5247
Fangrui Song6907ce22018-07-30 19:24:48 +00005248 bool GlobalBlockExpr =
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005249 block->getDeclContext()->getRedeclContext()->isFileContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005250
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005251 if (GlobalBlockExpr && !GlobalVarDecl) {
5252 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5253 GlobalBlockExpr = false;
5254 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005255
Fariborz Jahanian11671902012-02-07 17:11:38 +00005256 std::string BlockNumber = utostr(Blocks.size()-1);
5257
Fariborz Jahanian11671902012-02-07 17:11:38 +00005258 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5259
5260 // Get a pointer to the function type so we can cast appropriately.
5261 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5262 QualType FType = Context->getPointerType(BFT);
5263
5264 FunctionDecl *FD;
5265 Expr *NewRep;
5266
Benjamin Kramer60509af2013-09-09 14:48:42 +00005267 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005268 std::string Tag;
Fangrui Song6907ce22018-07-30 19:24:48 +00005269
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005270 if (GlobalBlockExpr)
5271 Tag = "__global_";
5272 else
5273 Tag = "__";
5274 Tag += FuncName + "_block_impl_" + BlockNumber;
Fangrui Song6907ce22018-07-30 19:24:48 +00005275
Fariborz Jahanian11671902012-02-07 17:11:38 +00005276 FD = SynthBlockInitFunctionDecl(Tag);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005277 DeclRefExpr *DRE = new (Context)
5278 DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005279
5280 SmallVector<Expr*, 4> InitExprs;
5281
5282 // Initialize the block function.
5283 FD = SynthBlockInitFunctionDecl(Func);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005284 DeclRefExpr *Arg = new (Context) DeclRefExpr(
5285 *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005286 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5287 CK_BitCast, Arg);
5288 InitExprs.push_back(castExpr);
5289
5290 // Initialize the block descriptor.
5291 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5292
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005293 VarDecl *NewVD = VarDecl::Create(
5294 *Context, TUDecl, SourceLocation(), SourceLocation(),
5295 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005296 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5297 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5298 VK_LValue, SourceLocation()),
5299 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5300 OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005301 InitExprs.push_back(DescRefExpr);
5302
Fariborz Jahanian11671902012-02-07 17:11:38 +00005303 // Add initializers for any closure decl refs.
5304 if (BlockDeclRefs.size()) {
5305 Expr *Exp;
5306 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005307 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005308 E = BlockByCopyDecls.end(); I != E; ++I) {
5309 if (isObjCType((*I)->getType())) {
5310 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5311 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005312 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005313 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005314 if (HasLocalVariableExternalStorage(*I)) {
5315 QualType QT = (*I)->getType();
5316 QT = Context->getPointerType(QT);
5317 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005318 OK_Ordinary, SourceLocation(),
5319 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005320 }
5321 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5322 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005323 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005324 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005325 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5326 CK_BitCast, Arg);
5327 } else {
5328 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005329 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005330 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005331 if (HasLocalVariableExternalStorage(*I)) {
5332 QualType QT = (*I)->getType();
5333 QT = Context->getPointerType(QT);
5334 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005335 OK_Ordinary, SourceLocation(),
5336 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005337 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005338
Fariborz Jahanian11671902012-02-07 17:11:38 +00005339 }
5340 InitExprs.push_back(Exp);
5341 }
5342 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005343 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005344 E = BlockByRefDecls.end(); I != E; ++I) {
5345 ValueDecl *ND = (*I);
5346 std::string Name(ND->getNameAsString());
5347 std::string RecName;
5348 RewriteByRefString(RecName, Name, ND, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005349 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
Fariborz Jahanian11671902012-02-07 17:11:38 +00005350 + sizeof("struct"));
5351 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5352 SourceLocation(), SourceLocation(),
5353 II);
5354 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5355 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00005356
Fariborz Jahanian11671902012-02-07 17:11:38 +00005357 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005358 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5359 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005360 bool isNestedCapturedVar = false;
5361 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005362 for (const auto &CI : block->captures()) {
5363 const VarDecl *variable = CI.getVariable();
5364 if (variable == ND && CI.isNested()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005365 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005366 "SynthBlockInitExpr - captured block variable is not byref");
5367 isNestedCapturedVar = true;
5368 break;
5369 }
5370 }
5371 // captured nested byref variable has its address passed. Do not take
5372 // its address again.
5373 if (!isNestedCapturedVar)
5374 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5375 Context->getPointerType(Exp->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005376 VK_RValue, OK_Ordinary, SourceLocation(),
5377 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005378 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5379 InitExprs.push_back(Exp);
5380 }
5381 }
5382 if (ImportedBlockDecls.size()) {
5383 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5384 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Fangrui Song6907ce22018-07-30 19:24:48 +00005385 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00005387 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005388 Context->IntTy, SourceLocation());
5389 InitExprs.push_back(FlagExp);
5390 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00005391 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5392 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00005393
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005394 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005395 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005396 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5397 GlobalConstructionExp = NewRep;
5398 NewRep = DRE;
5399 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005400
Fariborz Jahanian11671902012-02-07 17:11:38 +00005401 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5402 Context->getPointerType(NewRep->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005403 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005404 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5405 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005406 // Put Paren around the call.
5407 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5408 NewRep);
Fangrui Song6907ce22018-07-30 19:24:48 +00005409
Fariborz Jahanian11671902012-02-07 17:11:38 +00005410 BlockDeclRefs.clear();
5411 BlockByRefDecls.clear();
5412 BlockByRefDeclsPtrSet.clear();
5413 BlockByCopyDecls.clear();
5414 BlockByCopyDeclsPtrSet.clear();
5415 ImportedBlockDecls.clear();
5416 return NewRep;
5417}
5418
5419bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005420 if (const ObjCForCollectionStmt * CS =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005421 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5422 return CS->getElement() == DS;
5423 return false;
5424}
5425
5426//===----------------------------------------------------------------------===//
5427// Function Body / Expression rewriting
5428//===----------------------------------------------------------------------===//
5429
5430Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5431 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5432 isa<DoStmt>(S) || isa<ForStmt>(S))
5433 Stmts.push_back(S);
5434 else if (isa<ObjCForCollectionStmt>(S)) {
5435 Stmts.push_back(S);
5436 ObjCBcLabelNo.push_back(++BcLabelCount);
5437 }
5438
5439 // Pseudo-object operations and ivar references need special
5440 // treatment because we're going to recursively rewrite them.
5441 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5442 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5443 return RewritePropertyOrImplicitSetter(PseudoOp);
5444 } else {
5445 return RewritePropertyOrImplicitGetter(PseudoOp);
5446 }
5447 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5448 return RewriteObjCIvarRefExpr(IvarRefExpr);
5449 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005450 else if (isa<OpaqueValueExpr>(S))
5451 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005452
5453 SourceRange OrigStmtRange = S->getSourceRange();
5454
5455 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005456 for (Stmt *&childStmt : S->children())
5457 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005458 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5459 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005460 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005461 }
5462 }
5463
5464 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005465 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005466 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5467 InnerContexts.insert(BE->getBlockDecl());
5468 ImportedLocalExternalDecls.clear();
5469 GetInnerBlockDeclRefExprs(BE->getBody(),
5470 InnerBlockDeclRefs, InnerContexts);
5471 // Rewrite the block body in place.
5472 Stmt *SaveCurrentBody = CurrentBody;
5473 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005474 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005475 // block literal on rhs of a property-dot-sytax assignment
5476 // must be replaced by its synthesize ast so getRewrittenText
5477 // works as expected. In this case, what actually ends up on RHS
5478 // is the blockTranscribed which is the helper function for the
5479 // block literal; as in: self.c = ^() {[ace ARR];};
5480 bool saveDisableReplaceStmt = DisableReplaceStmt;
5481 DisableReplaceStmt = false;
5482 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5483 DisableReplaceStmt = saveDisableReplaceStmt;
5484 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005485 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005486 ImportedLocalExternalDecls.clear();
5487 // Now we snarf the rewritten text and stash it away for later use.
5488 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5489 RewrittenBlockExprs[BE] = Str;
5490
5491 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
Fangrui Song6907ce22018-07-30 19:24:48 +00005492
Fariborz Jahanian11671902012-02-07 17:11:38 +00005493 //blockTranscribed->dump();
5494 ReplaceStmt(S, blockTranscribed);
5495 return blockTranscribed;
5496 }
5497 // Handle specific things.
5498 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5499 return RewriteAtEncode(AtEncode);
5500
5501 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5502 return RewriteAtSelector(AtSelector);
5503
5504 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5505 return RewriteObjCStringLiteral(AtString);
Fangrui Song6907ce22018-07-30 19:24:48 +00005506
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005507 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5508 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005509
Patrick Beard0caa3942012-04-19 00:25:12 +00005510 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5511 return RewriteObjCBoxedExpr(BoxedExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005512
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005513 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5514 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005515
5516 if (ObjCDictionaryLiteral *DictionaryLitExpr =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005517 dyn_cast<ObjCDictionaryLiteral>(S))
5518 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005519
5520 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5521#if 0
5522 // Before we rewrite it, put the original message expression in a comment.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005523 SourceLocation startLoc = MessExpr->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005524 SourceLocation endLoc = MessExpr->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005525
5526 const char *startBuf = SM->getCharacterData(startLoc);
5527 const char *endBuf = SM->getCharacterData(endLoc);
5528
5529 std::string messString;
5530 messString += "// ";
5531 messString.append(startBuf, endBuf-startBuf+1);
5532 messString += "\n";
5533
5534 // FIXME: Missing definition of
5535 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005536 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005537 // Tried this, but it didn't work either...
5538 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5539#endif
5540 return RewriteMessageExpr(MessExpr);
5541 }
5542
Fangrui Song6907ce22018-07-30 19:24:48 +00005543 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005544 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5545 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5546 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005547
Fariborz Jahanian11671902012-02-07 17:11:38 +00005548 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5549 return RewriteObjCTryStmt(StmtTry);
5550
5551 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5552 return RewriteObjCSynchronizedStmt(StmtTry);
5553
5554 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5555 return RewriteObjCThrowStmt(StmtThrow);
5556
5557 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5558 return RewriteObjCProtocolExpr(ProtocolExp);
5559
5560 if (ObjCForCollectionStmt *StmtForCollection =
5561 dyn_cast<ObjCForCollectionStmt>(S))
5562 return RewriteObjCForCollectionStmt(StmtForCollection,
5563 OrigStmtRange.getEnd());
5564 if (BreakStmt *StmtBreakStmt =
5565 dyn_cast<BreakStmt>(S))
5566 return RewriteBreakStmt(StmtBreakStmt);
5567 if (ContinueStmt *StmtContinueStmt =
5568 dyn_cast<ContinueStmt>(S))
5569 return RewriteContinueStmt(StmtContinueStmt);
5570
5571 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5572 // and cast exprs.
5573 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5574 // FIXME: What we're doing here is modifying the type-specifier that
5575 // precedes the first Decl. In the future the DeclGroup should have
5576 // a separate type-specifier that we can rewrite.
5577 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5578 // the context of an ObjCForCollectionStmt. For example:
5579 // NSArray *someArray;
5580 // for (id <FooProtocol> index in someArray) ;
Fangrui Song6907ce22018-07-30 19:24:48 +00005581 // This is because RewriteObjCForCollectionStmt() does textual rewriting
Fariborz Jahanian11671902012-02-07 17:11:38 +00005582 // and it depends on the original text locations/positions.
5583 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5584 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5585
5586 // Blocks rewrite rules.
5587 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5588 DI != DE; ++DI) {
5589 Decl *SD = *DI;
5590 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5591 if (isTopLevelBlockPointerType(ND->getType()))
5592 RewriteBlockPointerDecl(ND);
5593 else if (ND->getType()->isFunctionPointerType())
5594 CheckFunctionPointerDecl(ND->getType(), ND);
5595 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5596 if (VD->hasAttr<BlocksAttr>()) {
5597 static unsigned uniqueByrefDeclCount = 0;
5598 assert(!BlockByRefDeclNo.count(ND) &&
5599 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5600 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005601 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005602 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005603 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005604 RewriteTypeOfDecl(VD);
5605 }
5606 }
5607 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5608 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5609 RewriteBlockPointerDecl(TD);
5610 else if (TD->getUnderlyingType()->isFunctionPointerType())
5611 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5612 }
5613 }
5614 }
5615
5616 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5617 RewriteObjCQualifiedInterfaceTypes(CE);
5618
5619 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5620 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5621 assert(!Stmts.empty() && "Statement stack is empty");
5622 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5623 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5624 && "Statement stack mismatch");
5625 Stmts.pop_back();
5626 }
5627 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005628 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005629 ValueDecl *VD = DRE->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005630 if (VD->hasAttr<BlocksAttr>())
5631 return RewriteBlockDeclRefExpr(DRE);
5632 if (HasLocalVariableExternalStorage(VD))
5633 return RewriteLocalVariableExternalStorage(DRE);
5634 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005635
Fariborz Jahanian11671902012-02-07 17:11:38 +00005636 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5637 if (CE->getCallee()->getType()->isBlockPointerType()) {
5638 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5639 ReplaceStmt(S, BlockCall);
5640 return BlockCall;
5641 }
5642 }
5643 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5644 RewriteCastExpr(CE);
5645 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005646 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5647 RewriteImplicitCastObjCExpr(ICE);
5648 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005649#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005650
Fariborz Jahanian11671902012-02-07 17:11:38 +00005651 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5652 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5653 ICE->getSubExpr(),
5654 SourceLocation());
5655 // Get the new text.
5656 std::string SStr;
5657 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005658 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005659 const std::string &Str = Buf.str();
5660
5661 printf("CAST = %s\n", &Str[0]);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005662 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005663 delete S;
5664 return Replacement;
5665 }
5666#endif
5667 // Return this stmt unmodified.
5668 return S;
5669}
5670
5671void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005672 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005673 if (isTopLevelBlockPointerType(FD->getType()))
5674 RewriteBlockPointerDecl(FD);
5675 if (FD->getType()->isObjCQualifiedIdType() ||
5676 FD->getType()->isObjCQualifiedInterfaceType())
5677 RewriteObjCQualifiedInterfaceTypes(FD);
5678 }
5679}
5680
5681/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5682/// main file of the input.
5683void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5684 switch (D->getKind()) {
5685 case Decl::Function: {
5686 FunctionDecl *FD = cast<FunctionDecl>(D);
5687 if (FD->isOverloadedOperator())
5688 return;
5689
5690 // Since function prototypes don't have ParmDecl's, we check the function
5691 // prototype. This enables us to rewrite function declarations and
5692 // definitions using the same code.
5693 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5694
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005695 if (!FD->isThisDeclarationADefinition())
5696 break;
5697
Fariborz Jahanian11671902012-02-07 17:11:38 +00005698 // FIXME: If this should support Obj-C++, support CXXTryStmt
5699 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5700 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005701 CurrentBody = Body;
5702 Body =
5703 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5704 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005705 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005706 if (PropParentMap) {
5707 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005708 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005709 }
5710 // This synthesizes and inserts the block "impl" struct, invoke function,
5711 // and any copy/dispose helper functions.
5712 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005713 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005714 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005715 }
5716 break;
5717 }
5718 case Decl::ObjCMethod: {
5719 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5720 if (CompoundStmt *Body = MD->getCompoundBody()) {
5721 CurMethodDef = MD;
5722 CurrentBody = Body;
5723 Body =
5724 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5725 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005726 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005727 if (PropParentMap) {
5728 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005729 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005730 }
5731 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005732 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005733 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005734 }
5735 break;
5736 }
5737 case Decl::ObjCImplementation: {
5738 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5739 ClassImplementation.push_back(CI);
5740 break;
5741 }
5742 case Decl::ObjCCategoryImpl: {
5743 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5744 CategoryImplementation.push_back(CI);
5745 break;
5746 }
5747 case Decl::Var: {
5748 VarDecl *VD = cast<VarDecl>(D);
5749 RewriteObjCQualifiedInterfaceTypes(VD);
5750 if (isTopLevelBlockPointerType(VD->getType()))
5751 RewriteBlockPointerDecl(VD);
5752 else if (VD->getType()->isFunctionPointerType()) {
5753 CheckFunctionPointerDecl(VD->getType(), VD);
5754 if (VD->getInit()) {
5755 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5756 RewriteCastExpr(CE);
5757 }
5758 }
5759 } else if (VD->getType()->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00005760 RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005761 if (RD->isCompleteDefinition())
5762 RewriteRecordBody(RD);
5763 }
5764 if (VD->getInit()) {
5765 GlobalVarDecl = VD;
5766 CurrentBody = VD->getInit();
5767 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005768 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005769 if (PropParentMap) {
5770 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005771 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005772 }
5773 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005774 GlobalVarDecl = nullptr;
5775
Fariborz Jahanian11671902012-02-07 17:11:38 +00005776 // This is needed for blocks.
5777 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5778 RewriteCastExpr(CE);
5779 }
5780 }
5781 break;
5782 }
5783 case Decl::TypeAlias:
5784 case Decl::Typedef: {
5785 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5786 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5787 RewriteBlockPointerDecl(TD);
5788 else if (TD->getUnderlyingType()->isFunctionPointerType())
5789 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005790 else
5791 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005792 }
5793 break;
5794 }
5795 case Decl::CXXRecord:
5796 case Decl::Record: {
5797 RecordDecl *RD = cast<RecordDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00005798 if (RD->isCompleteDefinition())
Fariborz Jahanian11671902012-02-07 17:11:38 +00005799 RewriteRecordBody(RD);
5800 break;
5801 }
5802 default:
5803 break;
5804 }
5805 // Nothing yet.
5806}
5807
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005808/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5809/// protocol reference symbols in the for of:
5810/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Fangrui Song6907ce22018-07-30 19:24:48 +00005811static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005812 ObjCProtocolDecl *PDecl,
5813 std::string &Result) {
5814 // Also output .objc_protorefs$B section and its meta-data.
5815 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005816 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005817 Result += "struct _protocol_t *";
5818 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5819 Result += PDecl->getNameAsString();
5820 Result += " = &";
5821 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5822 Result += ";\n";
5823}
5824
Fariborz Jahanian11671902012-02-07 17:11:38 +00005825void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5826 if (Diags.hasErrorOccurred())
5827 return;
5828
5829 RewriteInclude();
5830
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005831 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005832 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005833 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005834 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005835 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5836 HandleTopLevelSingleDecl(FDecl);
5837 }
5838
Fariborz Jahanian11671902012-02-07 17:11:38 +00005839 // Here's a great place to add any extra declarations that may be needed.
5840 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005841 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5842 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5843 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005844 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005845
5846 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005847
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005848 if (ClassImplementation.size() || CategoryImplementation.size())
5849 RewriteImplementations();
Fangrui Song6907ce22018-07-30 19:24:48 +00005850
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005851 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5852 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5853 // Write struct declaration for the class matching its ivar declarations.
5854 // Note that for modern abi, this is postponed until the end of TU
5855 // because class extensions and the implementation might declare their own
5856 // private ivars.
5857 RewriteInterfaceDecl(CDecl);
5858 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005859
Fariborz Jahanian11671902012-02-07 17:11:38 +00005860 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5861 // we are done.
5862 if (const RewriteBuffer *RewriteBuf =
5863 Rewrite.getRewriteBufferFor(MainFileID)) {
5864 //printf("Changed:\n");
5865 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5866 } else {
5867 llvm::errs() << "No changes\n";
5868 }
5869
5870 if (ClassImplementation.size() || CategoryImplementation.size() ||
5871 ProtocolExprDecls.size()) {
5872 // Rewrite Objective-c meta data*
5873 std::string ResultStr;
5874 RewriteMetaDataIntoBuffer(ResultStr);
5875 // Emit metadata.
5876 *OutFile << ResultStr;
5877 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005878 // Emit ImageInfo;
5879 {
5880 std::string ResultStr;
5881 WriteImageInfo(ResultStr);
5882 *OutFile << ResultStr;
5883 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005884 OutFile->flush();
5885}
5886
5887void RewriteModernObjC::Initialize(ASTContext &context) {
5888 InitializeCommon(context);
Fangrui Song6907ce22018-07-30 19:24:48 +00005889
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005890 Preamble += "#ifndef __OBJC2__\n";
5891 Preamble += "#define __OBJC2__\n";
5892 Preamble += "#endif\n";
5893
Fariborz Jahanian11671902012-02-07 17:11:38 +00005894 // declaring objc_selector outside the parameter list removes a silly
5895 // scope related warning...
5896 if (IsHeader)
5897 Preamble = "#pragma once\n";
5898 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005899 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5900 Preamble += "\n\tstruct objc_object *superClass; ";
5901 // Add a constructor for creating temporary objects.
5902 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5903 Preamble += ": object(o), superClass(s) {} ";
5904 Preamble += "\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005905
Fariborz Jahanian11671902012-02-07 17:11:38 +00005906 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005907 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005908 // These are currently generated.
5909 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005910 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005911 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005912 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5913 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005914 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005915 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005916 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5917 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005918 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005919
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005920 // These need be generated for performance. Currently they are not,
5921 // using API calls instead.
5922 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5923 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005925
Fariborz Jahanian11671902012-02-07 17:11:38 +00005926 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005927 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5928 Preamble += "typedef struct objc_object Protocol;\n";
5929 Preamble += "#define _REWRITER_typedef_Protocol\n";
5930 Preamble += "#endif\n";
5931 if (LangOpts.MicrosoftExt) {
5932 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5933 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005934 }
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005935 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005936 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005937
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005938 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5939 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5942 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5943
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005944 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005945 Preamble += "(const char *);\n";
5946 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5947 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005948 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005949 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005950 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005951 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005952 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005954 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005955 Preamble += "#ifdef _WIN64\n";
5956 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5957 Preamble += "#else\n";
5958 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5959 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005960 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5961 Preamble += "struct __objcFastEnumerationState {\n\t";
5962 Preamble += "unsigned long state;\n\t";
5963 Preamble += "void **itemsPtr;\n\t";
5964 Preamble += "unsigned long *mutationsPtr;\n\t";
5965 Preamble += "unsigned long extra[5];\n};\n";
5966 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5967 Preamble += "#define __FASTENUMERATIONSTATE\n";
5968 Preamble += "#endif\n";
5969 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5970 Preamble += "struct __NSConstantStringImpl {\n";
5971 Preamble += " int *isa;\n";
5972 Preamble += " int flags;\n";
5973 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005974 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005975 Preamble += " long long length;\n";
5976 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005977 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005978 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005979 Preamble += "};\n";
5980 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5981 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5982 Preamble += "#else\n";
5983 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5984 Preamble += "#endif\n";
5985 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5986 Preamble += "#endif\n";
5987 // Blocks preamble.
5988 Preamble += "#ifndef BLOCK_IMPL\n";
5989 Preamble += "#define BLOCK_IMPL\n";
5990 Preamble += "struct __block_impl {\n";
5991 Preamble += " void *isa;\n";
5992 Preamble += " int Flags;\n";
5993 Preamble += " int Reserved;\n";
5994 Preamble += " void *FuncPtr;\n";
5995 Preamble += "};\n";
5996 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5997 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5998 Preamble += "extern \"C\" __declspec(dllexport) "
5999 "void _Block_object_assign(void *, const void *, const int);\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6001 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6003 Preamble += "#else\n";
6004 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6008 Preamble += "#endif\n";
6009 Preamble += "#endif\n";
6010 if (LangOpts.MicrosoftExt) {
6011 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6012 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6013 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6014 Preamble += "#define __attribute__(X)\n";
6015 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006016 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006017 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006018 Preamble += "#endif\n";
6019 Preamble += "#ifndef __block\n";
6020 Preamble += "#define __block\n";
6021 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006022 }
6023 else {
6024 Preamble += "#define __block\n";
6025 Preamble += "#define __weak\n";
6026 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006027
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006028 // Declarations required for modern objective-c array and dictionary literals.
6029 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006030 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006031 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006032 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006033 Preamble += "\tva_list marker;\n";
6034 Preamble += "\tva_start(marker, count);\n";
6035 Preamble += "\tarr = new void *[count];\n";
6036 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6037 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6038 Preamble += "\tva_end( marker );\n";
6039 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006040 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006041 Preamble += "\tdelete[] arr;\n";
6042 Preamble += " }\n";
6043 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006044
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006045 // Declaration required for implementation of @autoreleasepool statement.
6046 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6047 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6048 Preamble += "struct __AtAutoreleasePool {\n";
6049 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6050 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6051 Preamble += " void * atautoreleasepoolobj;\n";
6052 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006053
Fariborz Jahanian11671902012-02-07 17:11:38 +00006054 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6055 // as this avoids warning in any 64bit/32bit compilation model.
6056 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6057}
6058
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00006059/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian11671902012-02-07 17:11:38 +00006060/// ivar offset.
6061void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6062 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006063 Result += "__OFFSETOFIVAR__(struct ";
6064 Result += ivar->getContainingInterface()->getNameAsString();
6065 if (LangOpts.MicrosoftExt)
6066 Result += "_IMPL";
6067 Result += ", ";
6068 if (ivar->isBitField())
6069 ObjCIvarBitfieldGroupDecl(ivar, Result);
6070 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006071 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006072 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006073}
6074
6075/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6076/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006077/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006078/// char *attributes;
6079/// }
6080
6081/// struct _prop_list_t {
6082/// uint32_t entsize; // sizeof(struct _prop_t)
6083/// uint32_t count_of_properties;
6084/// struct _prop_t prop_list[count_of_properties];
6085/// }
6086
6087/// struct _protocol_t;
6088
6089/// struct _protocol_list_t {
6090/// long protocol_count; // Note, this is 32/64 bit
6091/// struct _protocol_t * protocol_list[protocol_count];
6092/// }
6093
6094/// struct _objc_method {
6095/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006096/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006097/// char *_imp;
6098/// }
6099
6100/// struct _method_list_t {
6101/// uint32_t entsize; // sizeof(struct _objc_method)
6102/// uint32_t method_count;
6103/// struct _objc_method method_list[method_count];
6104/// }
6105
6106/// struct _protocol_t {
6107/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006108/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006109/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006110/// const struct method_list_t *instance_methods;
6111/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006112/// const struct method_list_t *optionalInstanceMethods;
6113/// const struct method_list_t *optionalClassMethods;
6114/// const struct _prop_list_t * properties;
6115/// const uint32_t size; // sizeof(struct _protocol_t)
6116/// const uint32_t flags; // = 0
6117/// const char ** extendedMethodTypes;
6118/// }
6119
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006120/// struct _ivar_t {
6121/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006122/// const char *name;
6123/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006124/// uint32_t alignment;
6125/// uint32_t size;
6126/// }
6127
6128/// struct _ivar_list_t {
6129/// uint32 entsize; // sizeof(struct _ivar_t)
6130/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006131/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006132/// }
6133
6134/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006135/// uint32_t flags;
6136/// uint32_t instanceStart;
6137/// uint32_t instanceSize;
6138/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006139/// const uint8_t *ivarLayout;
6140/// const char *name;
6141/// const struct _method_list_t *baseMethods;
6142/// const struct _protocol_list_t *baseProtocols;
6143/// const struct _ivar_list_t *ivars;
6144/// const uint8_t *weakIvarLayout;
6145/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006146/// }
6147
6148/// struct _class_t {
6149/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006150/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006151/// void *cache;
6152/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006153/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006154/// }
6155
6156/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006157/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006158/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006159/// const struct _method_list_t *instance_methods;
6160/// const struct _method_list_t *class_methods;
6161/// const struct _protocol_list_t *protocols;
6162/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006163/// }
6164
6165/// MessageRefTy - LLVM for:
6166/// struct _message_ref_t {
6167/// IMP messenger;
6168/// SEL name;
6169/// };
6170
6171/// SuperMessageRefTy - LLVM for:
6172/// struct _super_message_ref_t {
6173/// SUPER_IMP messenger;
6174/// SEL name;
6175/// };
6176
Fariborz Jahanian45489622012-03-14 18:09:23 +00006177static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006178 static bool meta_data_declared = false;
6179 if (meta_data_declared)
6180 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006181
Fariborz Jahanian11671902012-02-07 17:11:38 +00006182 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006183 Result += "\tconst char *name;\n";
6184 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006185 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006186
Fariborz Jahanian11671902012-02-07 17:11:38 +00006187 Result += "\nstruct _protocol_t;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006188
Fariborz Jahanian11671902012-02-07 17:11:38 +00006189 Result += "\nstruct _objc_method {\n";
6190 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006191 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006192 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006193 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006194
Fariborz Jahanian11671902012-02-07 17:11:38 +00006195 Result += "\nstruct _protocol_t {\n";
6196 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006197 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006198 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006199 Result += "\tconst struct method_list_t *instance_methods;\n";
6200 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006201 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6202 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6203 Result += "\tconst struct _prop_list_t * properties;\n";
6204 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6205 Result += "\tconst unsigned int flags; // = 0\n";
6206 Result += "\tconst char ** extendedMethodTypes;\n";
6207 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006208
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006209 Result += "\nstruct _ivar_t {\n";
6210 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006211 Result += "\tconst char *name;\n";
6212 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006213 Result += "\tunsigned int alignment;\n";
6214 Result += "\tunsigned int size;\n";
6215 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006216
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006217 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006218 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006219 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006220 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006221 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6222 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006223 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006224 Result += "\tconst unsigned char *ivarLayout;\n";
6225 Result += "\tconst char *name;\n";
6226 Result += "\tconst struct _method_list_t *baseMethods;\n";
6227 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6228 Result += "\tconst struct _ivar_list_t *ivars;\n";
6229 Result += "\tconst unsigned char *weakIvarLayout;\n";
6230 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006231 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006232
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006233 Result += "\nstruct _class_t {\n";
6234 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006235 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006236 Result += "\tvoid *cache;\n";
6237 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006238 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006239 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006240
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006241 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006242 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006243 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006244 Result += "\tconst struct _method_list_t *instance_methods;\n";
6245 Result += "\tconst struct _method_list_t *class_methods;\n";
6246 Result += "\tconst struct _protocol_list_t *protocols;\n";
6247 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006248 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006249
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006250 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006251 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006252 meta_data_declared = true;
6253}
6254
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006255static void Write_protocol_list_t_TypeDecl(std::string &Result,
6256 long super_protocol_count) {
6257 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6258 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6259 Result += "\tstruct _protocol_t *super_protocols[";
6260 Result += utostr(super_protocol_count); Result += "];\n";
6261 Result += "}";
6262}
6263
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006264static void Write_method_list_t_TypeDecl(std::string &Result,
6265 unsigned int method_count) {
6266 Result += "struct /*_method_list_t*/"; Result += " {\n";
6267 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6268 Result += "\tunsigned int method_count;\n";
6269 Result += "\tstruct _objc_method method_list[";
6270 Result += utostr(method_count); Result += "];\n";
6271 Result += "}";
6272}
6273
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006274static void Write__prop_list_t_TypeDecl(std::string &Result,
6275 unsigned int property_count) {
6276 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6277 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6278 Result += "\tunsigned int count_of_properties;\n";
6279 Result += "\tstruct _prop_t prop_list[";
6280 Result += utostr(property_count); Result += "];\n";
6281 Result += "}";
6282}
6283
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006284static void Write__ivar_list_t_TypeDecl(std::string &Result,
6285 unsigned int ivar_count) {
6286 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6287 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6288 Result += "\tunsigned int count;\n";
6289 Result += "\tstruct _ivar_t ivar_list[";
6290 Result += utostr(ivar_count); Result += "];\n";
6291 Result += "}";
6292}
6293
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006294static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6295 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6296 StringRef VarName,
6297 StringRef ProtocolName) {
6298 if (SuperProtocols.size() > 0) {
6299 Result += "\nstatic ";
6300 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6301 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006302 Result += ProtocolName;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006303 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6304 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6305 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6306 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00006307 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006308 Result += SuperPD->getNameAsString();
6309 if (i == e-1)
6310 Result += "\n};\n";
6311 else
6312 Result += ",\n";
6313 }
6314 }
6315}
6316
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006317static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6318 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006319 ArrayRef<ObjCMethodDecl *> Methods,
6320 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006321 StringRef TopLevelDeclName,
6322 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006323 if (Methods.size() > 0) {
6324 Result += "\nstatic ";
6325 Write_method_list_t_TypeDecl(Result, Methods.size());
6326 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006327 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006328 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6329 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6330 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6331 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6332 ObjCMethodDecl *MD = Methods[i];
6333 if (i == 0)
6334 Result += "\t{{(struct objc_selector *)\"";
6335 else
6336 Result += "\t{(struct objc_selector *)\"";
6337 Result += (MD)->getSelector().getAsString(); Result += "\"";
6338 Result += ", ";
John McCall843dfcc2016-11-29 21:57:00 +00006339 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006340 Result += "\""; Result += MethodTypeString; Result += "\"";
6341 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006342 if (!MethodImpl)
6343 Result += "0";
6344 else {
6345 Result += "(void *)";
6346 Result += RewriteObj.MethodInternalNames[MD];
6347 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006348 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006349 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006350 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006351 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006352 }
6353 Result += "};\n";
6354 }
6355}
6356
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006357static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006358 ASTContext *Context, std::string &Result,
6359 ArrayRef<ObjCPropertyDecl *> Properties,
6360 const Decl *Container,
6361 StringRef VarName,
6362 StringRef ProtocolName) {
6363 if (Properties.size() > 0) {
6364 Result += "\nstatic ";
6365 Write__prop_list_t_TypeDecl(Result, Properties.size());
6366 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006367 Result += ProtocolName;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006368 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6369 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6370 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6371 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6372 ObjCPropertyDecl *PropDecl = Properties[i];
6373 if (i == 0)
6374 Result += "\t{{\"";
6375 else
6376 Result += "\t{\"";
6377 Result += PropDecl->getName(); Result += "\",";
John McCall843dfcc2016-11-29 21:57:00 +00006378 std::string PropertyTypeString =
6379 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6380 std::string QuotePropertyTypeString;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006381 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6382 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6383 if (i == e-1)
6384 Result += "}}\n";
6385 else
6386 Result += "},\n";
6387 }
6388 Result += "};\n";
6389 }
6390}
6391
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006392// Metadata flags
6393enum MetaDataDlags {
6394 CLS = 0x0,
6395 CLS_META = 0x1,
6396 CLS_ROOT = 0x2,
6397 OBJC2_CLS_HIDDEN = 0x10,
6398 CLS_EXCEPTION = 0x20,
Fangrui Song6907ce22018-07-30 19:24:48 +00006399
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006400 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6401 CLS_HAS_IVAR_RELEASER = 0x40,
6402 /// class was compiled with -fobjc-arr
6403 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6404};
6405
Fangrui Song6907ce22018-07-30 19:24:48 +00006406static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6407 unsigned int flags,
6408 const std::string &InstanceStart,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006409 const std::string &InstanceSize,
6410 ArrayRef<ObjCMethodDecl *>baseMethods,
6411 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6412 ArrayRef<ObjCIvarDecl *>ivars,
6413 ArrayRef<ObjCPropertyDecl *>Properties,
6414 StringRef VarName,
6415 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006416 Result += "\nstatic struct _class_ro_t ";
6417 Result += VarName; Result += ClassName;
6418 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006419 Result += "\t";
6420 Result += llvm::utostr(flags); Result += ", ";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006421 Result += InstanceStart; Result += ", ";
6422 Result += InstanceSize; Result += ", \n";
6423 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006424 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6425 if (Triple.getArch() == llvm::Triple::x86_64)
6426 // uint32_t const reserved; // only when building for 64bit targets
6427 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006428 // const uint8_t * const ivarLayout;
6429 Result += "0, \n\t";
6430 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006431 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006432 if (baseMethods.size() > 0) {
6433 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006434 if (metaclass)
6435 Result += "_OBJC_$_CLASS_METHODS_";
6436 else
6437 Result += "_OBJC_$_INSTANCE_METHODS_";
6438 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006439 Result += ",\n\t";
6440 }
6441 else
6442 Result += "0, \n\t";
6443
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006444 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006445 Result += "(const struct _objc_protocol_list *)&";
6446 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6447 Result += ",\n\t";
6448 }
6449 else
6450 Result += "0, \n\t";
6451
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006452 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006453 Result += "(const struct _ivar_list_t *)&";
6454 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6455 Result += ",\n\t";
6456 }
6457 else
6458 Result += "0, \n\t";
6459
6460 // weakIvarLayout
6461 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006462 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006463 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006464 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006465 Result += ",\n";
6466 }
6467 else
6468 Result += "0, \n";
6469
6470 Result += "};\n";
6471}
6472
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006473static void Write_class_t(ASTContext *Context, std::string &Result,
6474 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006475 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6476 bool rootClass = (!CDecl->getSuperClass());
6477 const ObjCInterfaceDecl *RootClass = CDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +00006478
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006479 if (!rootClass) {
6480 // Find the Root class
6481 RootClass = CDecl->getSuperClass();
6482 while (RootClass->getSuperClass()) {
6483 RootClass = RootClass->getSuperClass();
6484 }
6485 }
6486
6487 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006488 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006489 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006490 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006491 if (CDecl->getImplementation())
6492 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006493 else
6494 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006495
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006496 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006497 Result += CDecl->getNameAsString();
6498 Result += ";\n";
6499 }
6500 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006501 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006502 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006503 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006504 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006505 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006506 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006507 else
6508 Result += "__declspec(dllimport) ";
6509
Fangrui Song6907ce22018-07-30 19:24:48 +00006510 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006511 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006512 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006513 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006514
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006515 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006516 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006517 if (RootClass->getImplementation())
6518 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006519 else
6520 Result += "__declspec(dllimport) ";
6521
Fangrui Song6907ce22018-07-30 19:24:48 +00006522 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006523 Result += VarName;
6524 Result += RootClass->getNameAsString();
6525 Result += ";\n";
6526 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006527 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006528
6529 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006530 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006531 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6532 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006533 if (metaclass) {
6534 if (!rootClass) {
6535 Result += "0, // &"; Result += VarName;
6536 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006537 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006538 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006539 Result += CDecl->getSuperClass()->getNameAsString();
6540 Result += ",\n\t";
6541 }
6542 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006543 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006544 Result += CDecl->getNameAsString();
6545 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006546 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006547 Result += ",\n\t";
6548 }
6549 }
6550 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006551 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006552 Result += CDecl->getNameAsString();
6553 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006554 if (!rootClass) {
6555 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006556 Result += CDecl->getSuperClass()->getNameAsString();
6557 Result += ",\n\t";
6558 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006559 else
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006560 Result += "0,\n\t";
6561 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006562 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6563 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6564 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006565 Result += "&_OBJC_METACLASS_RO_$_";
6566 else
6567 Result += "&_OBJC_CLASS_RO_$_";
6568 Result += CDecl->getNameAsString();
6569 Result += ",\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006570
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006571 // Add static function to initialize some of the meta-data fields.
6572 // avoid doing it twice.
6573 if (metaclass)
6574 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006575
6576 const ObjCInterfaceDecl *SuperClass =
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006577 rootClass ? CDecl : CDecl->getSuperClass();
Fangrui Song6907ce22018-07-30 19:24:48 +00006578
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006579 Result += "static void OBJC_CLASS_SETUP_$_";
6580 Result += CDecl->getNameAsString();
6581 Result += "(void ) {\n";
6582 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6583 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006584 Result += RootClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006585
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006586 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006587 Result += ".superclass = ";
6588 if (rootClass)
6589 Result += "&OBJC_CLASS_$_";
6590 else
6591 Result += "&OBJC_METACLASS_$_";
6592
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006593 Result += SuperClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006594
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006595 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6596 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006597
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006598 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6599 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6600 Result += CDecl->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006601
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006602 if (!rootClass) {
6603 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6604 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6605 Result += SuperClass->getNameAsString(); Result += ";\n";
6606 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006607
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006608 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6609 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6610 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006611}
6612
Fangrui Song6907ce22018-07-30 19:24:48 +00006613static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006614 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006615 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006616 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006617 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6618 ArrayRef<ObjCMethodDecl *> ClassMethods,
6619 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6620 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006621 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006622 StringRef ClassName = ClassDecl->getName();
Fangrui Song6907ce22018-07-30 19:24:48 +00006623 // must declare an extern class object in case this class is not implemented
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006624 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006625 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006626 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006627 if (ClassDecl->getImplementation())
6628 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006629 else
6630 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006631
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006632 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006633 Result += "OBJC_CLASS_$_"; Result += ClassName;
6634 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006635
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006636 Result += "\nstatic struct _category_t ";
6637 Result += "_OBJC_$_CATEGORY_";
6638 Result += ClassName; Result += "_$_"; Result += CatName;
6639 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6640 Result += "{\n";
6641 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006642 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006643 Result += ",\n";
6644 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006645 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006646 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6647 Result += ClassName; Result += "_$_"; Result += CatName;
6648 Result += ",\n";
6649 }
6650 else
6651 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006652
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006653 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006654 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006655 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6656 Result += ClassName; Result += "_$_"; Result += CatName;
6657 Result += ",\n";
6658 }
6659 else
6660 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006661
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006662 if (RefedProtocols.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006663 Result += "\t(const struct _protocol_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006664 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6665 Result += ClassName; Result += "_$_"; Result += CatName;
6666 Result += ",\n";
6667 }
6668 else
6669 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006670
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006671 if (ClassProperties.size() > 0) {
6672 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6673 Result += ClassName; Result += "_$_"; Result += CatName;
6674 Result += ",\n";
6675 }
6676 else
6677 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006678
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006679 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006680
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006681 // Add static function to initialize the class pointer in the category structure.
6682 Result += "static void OBJC_CATEGORY_SETUP_$_";
6683 Result += ClassDecl->getNameAsString();
6684 Result += "_$_";
6685 Result += CatName;
6686 Result += "(void ) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006687 Result += "\t_OBJC_$_CATEGORY_";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006688 Result += ClassDecl->getNameAsString();
6689 Result += "_$_";
6690 Result += CatName;
6691 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6692 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006693}
6694
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006695static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6696 ASTContext *Context, std::string &Result,
6697 ArrayRef<ObjCMethodDecl *> Methods,
6698 StringRef VarName,
6699 StringRef ProtocolName) {
6700 if (Methods.size() == 0)
6701 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006702
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006703 Result += "\nstatic const char *";
6704 Result += VarName; Result += ProtocolName;
6705 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6706 Result += "{\n";
6707 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6708 ObjCMethodDecl *MD = Methods[i];
John McCall843dfcc2016-11-29 21:57:00 +00006709 std::string MethodTypeString =
6710 Context->getObjCEncodingForMethodDecl(MD, true);
6711 std::string QuoteMethodTypeString;
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006712 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6713 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6714 if (i == e-1)
6715 Result += "\n};\n";
6716 else {
6717 Result += ",\n";
6718 }
6719 }
6720}
6721
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006722static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6723 ASTContext *Context,
Fangrui Song6907ce22018-07-30 19:24:48 +00006724 std::string &Result,
6725 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006726 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006727 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6728 // this is what happens:
6729 /**
6730 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6731 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6732 Class->getVisibility() == HiddenVisibility)
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006733 Visibility should be: HiddenVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006734 else
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006735 Visibility should be: DefaultVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006736 */
Fangrui Song6907ce22018-07-30 19:24:48 +00006737
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006738 Result += "\n";
6739 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6740 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006741 if (Context->getLangOpts().MicrosoftExt)
6742 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006743
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006744 if (!Context->getLangOpts().MicrosoftExt ||
6745 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006746 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fangrui Song6907ce22018-07-30 19:24:48 +00006747 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006748 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006749 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006750 if (Ivars[i]->isBitField())
6751 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6752 else
6753 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006754 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6755 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006756 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6757 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006758 if (Ivars[i]->isBitField()) {
6759 // skip over rest of the ivar bitfields.
6760 SKIP_BITFIELDS(i , e, Ivars);
6761 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006762 }
6763}
6764
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006765static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6766 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006767 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006768 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006769 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006770 if (OriginalIvars.size() > 0) {
6771 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6772 SmallVector<ObjCIvarDecl *, 8> Ivars;
6773 // strip off all but the first ivar bitfield from each group of ivars.
6774 // Such ivars in the ivar list table will be replaced by their grouping struct
6775 // 'ivar'.
6776 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6777 if (OriginalIvars[i]->isBitField()) {
6778 Ivars.push_back(OriginalIvars[i]);
6779 // skip over rest of the ivar bitfields.
6780 SKIP_BITFIELDS(i , e, OriginalIvars);
6781 }
6782 else
6783 Ivars.push_back(OriginalIvars[i]);
6784 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006785
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006786 Result += "\nstatic ";
6787 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6788 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006789 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006790 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6791 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6792 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6793 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6794 ObjCIvarDecl *IvarDecl = Ivars[i];
6795 if (i == 0)
6796 Result += "\t{{";
6797 else
6798 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006799 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006800 if (Ivars[i]->isBitField())
6801 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6802 else
6803 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006804 Result += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006805
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006806 Result += "\"";
6807 if (Ivars[i]->isBitField())
6808 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6809 else
6810 Result += IvarDecl->getName();
6811 Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006812
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006813 QualType IVQT = IvarDecl->getType();
6814 if (IvarDecl->isBitField())
6815 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00006816
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006817 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006818 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006819 IvarDecl);
6820 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6821 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006822
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006823 // FIXME. this alignment represents the host alignment and need be changed to
6824 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006825 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006826 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006827 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006828 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006829 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006830 if (i == e-1)
6831 Result += "}}\n";
6832 else
6833 Result += "},\n";
6834 }
6835 Result += "};\n";
6836 }
6837}
6838
Fariborz Jahanian11671902012-02-07 17:11:38 +00006839/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fangrui Song6907ce22018-07-30 19:24:48 +00006840void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006841 std::string &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006842
Fariborz Jahanian11671902012-02-07 17:11:38 +00006843 // Do not synthesize the protocol more than once.
6844 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6845 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006846 WriteModernMetadataDeclarations(Context, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006847
Fariborz Jahanian11671902012-02-07 17:11:38 +00006848 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6849 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006850 // Must write out all protocol definitions in current qualifier list,
6851 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006852 for (auto *I : PDecl->protocols())
6853 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006854
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006855 // Construct method lists.
6856 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6857 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006858 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006859 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6860 OptInstanceMethods.push_back(MD);
6861 } else {
6862 InstanceMethods.push_back(MD);
6863 }
6864 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006865
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006866 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006867 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6868 OptClassMethods.push_back(MD);
6869 } else {
6870 ClassMethods.push_back(MD);
6871 }
6872 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006873 std::vector<ObjCMethodDecl *> AllMethods;
6874 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6875 AllMethods.push_back(InstanceMethods[i]);
6876 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6877 AllMethods.push_back(ClassMethods[i]);
6878 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6879 AllMethods.push_back(OptInstanceMethods[i]);
6880 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6881 AllMethods.push_back(OptClassMethods[i]);
6882
6883 Write__extendedMethodTypes_initializer(*this, Context, Result,
6884 AllMethods,
6885 "_OBJC_PROTOCOL_METHOD_TYPES_",
6886 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006887 // Protocol's super protocol list
Fangrui Song6907ce22018-07-30 19:24:48 +00006888 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006889 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6890 "_OBJC_PROTOCOL_REFS_",
6891 PDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00006892
6893 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006894 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006895 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006896
6897 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006898 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006899 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006900
Fangrui Song6907ce22018-07-30 19:24:48 +00006901 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006902 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006903 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006904
6905 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006906 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006907 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006908
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006909 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006910 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6911 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006912 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006913 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006914 "_OBJC_PROTOCOL_PROPERTIES_",
6915 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006916
Fariborz Jahanian48985802012-02-08 00:50:52 +00006917 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006918 Result += "\n";
6919 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006920 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006921 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006922 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006923 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006924 Result += "\t0,\n"; // id is; is null
6925 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006926 if (SuperProtocols.size() > 0) {
6927 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6928 Result += PDecl->getNameAsString(); Result += ",\n";
6929 }
6930 else
6931 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006932 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006933 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006934 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006935 }
6936 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006937 Result += "\t0,\n";
6938
6939 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006940 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006941 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006942 }
6943 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006944 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006945
Fariborz Jahanian48985802012-02-08 00:50:52 +00006946 if (OptInstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006947 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006948 Result += PDecl->getNameAsString(); Result += ",\n";
6949 }
6950 else
6951 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006952
Fariborz Jahanian48985802012-02-08 00:50:52 +00006953 if (OptClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006954 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006955 Result += PDecl->getNameAsString(); Result += ",\n";
6956 }
6957 else
6958 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006959
Fariborz Jahanian48985802012-02-08 00:50:52 +00006960 if (ProtocolProperties.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006961 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006962 Result += PDecl->getNameAsString(); Result += ",\n";
6963 }
6964 else
6965 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006966
Fariborz Jahanian48985802012-02-08 00:50:52 +00006967 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6968 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006969
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006970 if (AllMethods.size() > 0) {
6971 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6972 Result += PDecl->getNameAsString();
6973 Result += "\n};\n";
6974 }
6975 else
6976 Result += "\t0\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006977
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006978 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006979 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006980 Result += "struct _protocol_t *";
6981 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6982 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6983 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006984
Fariborz Jahanian11671902012-02-07 17:11:38 +00006985 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00006986 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00006987 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00006988}
6989
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006990/// hasObjCExceptionAttribute - Return true if this class or any super
6991/// class has the __objc_exception__ attribute.
6992/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6993static bool hasObjCExceptionAttribute(ASTContext &Context,
6994 const ObjCInterfaceDecl *OID) {
6995 if (OID->hasAttr<ObjCExceptionAttr>())
6996 return true;
6997 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6998 return hasObjCExceptionAttribute(Context, Super);
6999 return false;
7000}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007001
Fariborz Jahanian11671902012-02-07 17:11:38 +00007002void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7003 std::string &Result) {
7004 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00007005
Fariborz Jahanian11671902012-02-07 17:11:38 +00007006 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007007 if (CDecl->isImplicitInterfaceDecl())
Fangrui Song6907ce22018-07-30 19:24:48 +00007008 assert(false &&
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007009 "Legacy implicit interface rewriting not supported in moder abi");
Fangrui Song6907ce22018-07-30 19:24:48 +00007010
Fariborz Jahanian45489622012-03-14 18:09:23 +00007011 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007012 SmallVector<ObjCIvarDecl *, 8> IVars;
Fangrui Song6907ce22018-07-30 19:24:48 +00007013
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007014 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7015 IVD; IVD = IVD->getNextIvar()) {
7016 // Ignore unnamed bit-fields.
7017 if (!IVD->getDeclName())
7018 continue;
7019 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007020 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007021
7022 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007023 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007024 CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00007025
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007026 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007027 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007028
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007029 // If any of our property implementations have associated getters or
7030 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007031 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007032 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007033 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007034 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007035 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007036 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007037 if (!PD)
7038 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007039 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007040 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007041 InstanceMethods.push_back(Getter);
7042 if (PD->isReadOnly())
7043 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007044 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007045 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007046 InstanceMethods.push_back(Setter);
7047 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007048
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007049 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7050 "_OBJC_$_INSTANCE_METHODS_",
7051 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007052
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007053 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007054
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007055 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7056 "_OBJC_$_CLASS_METHODS_",
7057 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007058
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007059 // Protocols referenced in class declaration?
7060 // Protocol's super protocol list
7061 std::vector<ObjCProtocolDecl *> RefedProtocols;
7062 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7063 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7064 E = Protocols.end();
7065 I != E; ++I) {
7066 RefedProtocols.push_back(*I);
7067 // Must write out all protocol definitions in current qualifier list,
7068 // and in their nested qualifiers before writing out current definition.
7069 RewriteObjCProtocolMetaData(*I, Result);
7070 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007071
7072 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007073 RefedProtocols,
7074 "_OBJC_CLASS_PROTOCOLS_$_",
7075 IDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007076
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007077 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007078 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7079 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007080 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007081 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007082 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007083 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007084
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007085 // Data for initializing _class_ro_t metaclass meta-data
7086 uint32_t flags = CLS_META;
7087 std::string InstanceSize;
7088 std::string InstanceStart;
Fangrui Song6907ce22018-07-30 19:24:48 +00007089
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007090 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7091 if (classIsHidden)
7092 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007093
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007094 if (!CDecl->getSuperClass())
7095 // class is root
7096 flags |= CLS_ROOT;
7097 InstanceSize = "sizeof(struct _class_t)";
7098 InstanceStart = InstanceSize;
Fangrui Song6907ce22018-07-30 19:24:48 +00007099 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007100 InstanceStart, InstanceSize,
7101 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007102 nullptr,
7103 nullptr,
7104 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007105 "_OBJC_METACLASS_RO_$_",
7106 CDecl->getNameAsString());
7107
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007108 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007109 flags = CLS;
7110 if (classIsHidden)
7111 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007112
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007113 if (hasObjCExceptionAttribute(*Context, CDecl))
7114 flags |= CLS_EXCEPTION;
7115
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007116 if (!CDecl->getSuperClass())
7117 // class is root
7118 flags |= CLS_ROOT;
Fangrui Song6907ce22018-07-30 19:24:48 +00007119
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007120 InstanceSize.clear();
7121 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007122 if (!ObjCSynthesizedStructs.count(CDecl)) {
7123 InstanceSize = "0";
7124 InstanceStart = "0";
7125 }
7126 else {
7127 InstanceSize = "sizeof(struct ";
7128 InstanceSize += CDecl->getNameAsString();
7129 InstanceSize += "_IMPL)";
Fangrui Song6907ce22018-07-30 19:24:48 +00007130
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007131 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7132 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007133 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007134 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007135 else
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007136 InstanceStart = InstanceSize;
7137 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007138 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007139 InstanceStart, InstanceSize,
7140 InstanceMethods,
7141 RefedProtocols,
7142 IVars,
7143 ClassProperties,
7144 "_OBJC_CLASS_RO_$_",
7145 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007146
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007147 Write_class_t(Context, Result,
7148 "OBJC_METACLASS_$_",
7149 CDecl, /*metaclass*/true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007150
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007151 Write_class_t(Context, Result,
7152 "OBJC_CLASS_$_",
7153 CDecl, /*metaclass*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00007154
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007155 if (ImplementationIsNonLazy(IDecl))
7156 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007157}
7158
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007159void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7160 int ClsDefCount = ClassImplementation.size();
7161 if (!ClsDefCount)
7162 return;
7163 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7164 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7165 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7166 for (int i = 0; i < ClsDefCount; i++) {
7167 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7168 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7169 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7170 Result += CDecl->getName(); Result += ",\n";
7171 }
7172 Result += "};\n";
7173}
7174
Fariborz Jahanian11671902012-02-07 17:11:38 +00007175void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7176 int ClsDefCount = ClassImplementation.size();
7177 int CatDefCount = CategoryImplementation.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00007178
Fariborz Jahanian11671902012-02-07 17:11:38 +00007179 // For each implemented class, write out all its meta data.
7180 for (int i = 0; i < ClsDefCount; i++)
7181 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007182
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007183 RewriteClassSetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007184
Fariborz Jahanian11671902012-02-07 17:11:38 +00007185 // For each implemented category, write out all its meta data.
7186 for (int i = 0; i < CatDefCount; i++)
7187 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007188
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007189 RewriteCategorySetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007190
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007191 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007192 if (LangOpts.MicrosoftExt)
7193 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007194 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7195 Result += llvm::utostr(ClsDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007196 Result +=
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007197 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7198 "regular,no_dead_strip\")))= {\n";
7199 for (int i = 0; i < ClsDefCount; i++) {
7200 Result += "\t&OBJC_CLASS_$_";
7201 Result += ClassImplementation[i]->getNameAsString();
7202 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007203 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007204 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007205
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007206 if (!DefinedNonLazyClasses.empty()) {
7207 if (LangOpts.MicrosoftExt)
7208 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7209 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7210 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7211 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7212 Result += ",\n";
7213 }
7214 Result += "};\n";
7215 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007216 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007217
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007218 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007219 if (LangOpts.MicrosoftExt)
7220 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007221 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7222 Result += llvm::utostr(CatDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007223 Result +=
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007224 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7225 "regular,no_dead_strip\")))= {\n";
7226 for (int i = 0; i < CatDefCount; i++) {
7227 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007228 Result +=
7229 CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007230 Result += "_$_";
7231 Result += CategoryImplementation[i]->getNameAsString();
7232 Result += ",\n";
7233 }
7234 Result += "};\n";
7235 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007236
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007237 if (!DefinedNonLazyCategories.empty()) {
7238 if (LangOpts.MicrosoftExt)
7239 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7240 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7241 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7242 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007243 Result +=
7244 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007245 Result += "_$_";
7246 Result += DefinedNonLazyCategories[i]->getNameAsString();
7247 Result += ",\n";
7248 }
7249 Result += "};\n";
7250 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007251}
7252
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007253void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7254 if (LangOpts.MicrosoftExt)
7255 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007256
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007257 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7258 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007259 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007260}
7261
Fariborz Jahanian11671902012-02-07 17:11:38 +00007262/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7263/// implementation.
7264void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7265 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007266 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007267 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7268 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007269 ObjCCategoryDecl *CDecl
7270 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fangrui Song6907ce22018-07-30 19:24:48 +00007271
Fariborz Jahanian11671902012-02-07 17:11:38 +00007272 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007273 FullCategoryName += "_$_";
7274 FullCategoryName += CDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00007275
Fariborz Jahanian11671902012-02-07 17:11:38 +00007276 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007277 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007278
Fariborz Jahanian11671902012-02-07 17:11:38 +00007279 // If any of our property implementations have associated getters or
7280 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007281 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007282 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007283 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007284 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007285 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007286 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007287 if (!PD)
7288 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007289 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007290 InstanceMethods.push_back(Getter);
7291 if (PD->isReadOnly())
7292 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007293 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007294 InstanceMethods.push_back(Setter);
7295 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007296
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007297 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7298 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7299 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007300
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007301 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007302
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007303 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7304 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7305 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007306
Fariborz Jahanian11671902012-02-07 17:11:38 +00007307 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007308 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007309 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7310 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007311 // Must write out all protocol definitions in current qualifier list,
7312 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007313 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007314
7315 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007316 RefedProtocols,
7317 "_OBJC_CATEGORY_PROTOCOLS_$_",
7318 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007319
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007320 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007321 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7322 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007323 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007324 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007325 "_OBJC_$_PROP_LIST_",
7326 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007327
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007328 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007329 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007330 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007331 InstanceMethods,
7332 ClassMethods,
7333 RefedProtocols,
7334 ClassProperties);
Fangrui Song6907ce22018-07-30 19:24:48 +00007335
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007336 // Determine if this category is also "non-lazy".
7337 if (ImplementationIsNonLazy(IDecl))
7338 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007339}
7340
7341void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7342 int CatDefCount = CategoryImplementation.size();
7343 if (!CatDefCount)
7344 return;
7345 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7346 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7347 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7348 for (int i = 0; i < CatDefCount; i++) {
7349 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7350 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7351 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7352 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7353 Result += ClassDecl->getName();
7354 Result += "_$_";
7355 Result += CatDecl->getName();
7356 Result += ",\n";
7357 }
7358 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007359}
7360
7361// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7362/// class methods.
7363template<typename MethodIterator>
7364void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7365 MethodIterator MethodEnd,
7366 bool IsInstanceMethod,
7367 StringRef prefix,
7368 StringRef ClassName,
7369 std::string &Result) {
7370 if (MethodBegin == MethodEnd) return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007371
Fariborz Jahanian11671902012-02-07 17:11:38 +00007372 if (!objc_impl_method) {
7373 /* struct _objc_method {
7374 SEL _cmd;
7375 char *method_types;
7376 void *_imp;
7377 }
7378 */
7379 Result += "\nstruct _objc_method {\n";
7380 Result += "\tSEL _cmd;\n";
7381 Result += "\tchar *method_types;\n";
7382 Result += "\tvoid *_imp;\n";
7383 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007384
Fariborz Jahanian11671902012-02-07 17:11:38 +00007385 objc_impl_method = true;
7386 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007387
Fariborz Jahanian11671902012-02-07 17:11:38 +00007388 // Build _objc_method_list for class's methods if needed
Fangrui Song6907ce22018-07-30 19:24:48 +00007389
Fariborz Jahanian11671902012-02-07 17:11:38 +00007390 /* struct {
7391 struct _objc_method_list *next_method;
7392 int method_count;
7393 struct _objc_method method_list[];
7394 }
7395 */
7396 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007397 Result += "\n";
7398 if (LangOpts.MicrosoftExt) {
7399 if (IsInstanceMethod)
7400 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7401 else
7402 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7403 }
7404 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007405 Result += "\tstruct _objc_method_list *next_method;\n";
7406 Result += "\tint method_count;\n";
7407 Result += "\tstruct _objc_method method_list[";
7408 Result += utostr(NumMethods);
7409 Result += "];\n} _OBJC_";
7410 Result += prefix;
7411 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7412 Result += "_METHODS_";
7413 Result += ClassName;
7414 Result += " __attribute__ ((used, section (\"__OBJC, __";
7415 Result += IsInstanceMethod ? "inst" : "cls";
7416 Result += "_meth\")))= ";
7417 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007418
Fariborz Jahanian11671902012-02-07 17:11:38 +00007419 Result += "\t,{{(SEL)\"";
7420 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7421 std::string MethodTypeString;
7422 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7423 Result += "\", \"";
7424 Result += MethodTypeString;
7425 Result += "\", (void *)";
7426 Result += MethodInternalNames[*MethodBegin];
7427 Result += "}\n";
7428 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7429 Result += "\t ,{(SEL)\"";
7430 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7431 std::string MethodTypeString;
7432 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7433 Result += "\", \"";
7434 Result += MethodTypeString;
7435 Result += "\", (void *)";
7436 Result += MethodInternalNames[*MethodBegin];
7437 Result += "}\n";
7438 }
7439 Result += "\t }\n};\n";
7440}
7441
7442Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7443 SourceRange OldRange = IV->getSourceRange();
7444 Expr *BaseExpr = IV->getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00007445
Fariborz Jahanian11671902012-02-07 17:11:38 +00007446 // Rewrite the base, but without actually doing replaces.
7447 {
7448 DisableReplaceStmtScope S(*this);
7449 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7450 IV->setBase(BaseExpr);
7451 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007452
Fariborz Jahanian11671902012-02-07 17:11:38 +00007453 ObjCIvarDecl *D = IV->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00007454
Fariborz Jahanian11671902012-02-07 17:11:38 +00007455 Expr *Replacement = IV;
Fangrui Song6907ce22018-07-30 19:24:48 +00007456
Fariborz Jahanian11671902012-02-07 17:11:38 +00007457 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7458 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007459 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007460 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7461 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007462 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007463 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7464 clsDeclared);
7465 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Fangrui Song6907ce22018-07-30 19:24:48 +00007466
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007467 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007468 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007469 if (D->isBitField())
7470 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7471 else
7472 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007473
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007474 ReferencedIvars[clsDeclared].insert(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00007475
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007476 // cast offset to "char *".
Fangrui Song6907ce22018-07-30 19:24:48 +00007477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007478 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007479 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007480 BaseExpr);
7481 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7482 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007483 Context->UnsignedLongTy, nullptr,
7484 SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00007485 DeclRefExpr *DRE = new (Context)
7486 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7487 VK_LValue, SourceLocation());
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07007488 BinaryOperator *addExpr = BinaryOperator::Create(
7489 *Context, castExpr, DRE, BO_Add,
7490 Context->getPointerType(Context->CharTy), VK_RValue, OK_Ordinary,
7491 SourceLocation(), FPOptions(Context->getLangOpts()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00007492 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007493 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7494 SourceLocation(),
7495 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007496 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007497 if (D->isBitField())
7498 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007499
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007500 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00007501 RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007502 RD = RD->getDefinition();
7503 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007504 // decltype(((Foo_IMPL*)0)->bar) *
Simon Pilgrim7bfc3bf2020-03-12 16:49:35 +00007505 auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007506 // ivar in class extensions requires special treatment.
7507 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7508 CDecl = CatDecl->getClassInterface();
Benjamin Krameradcd0262020-01-28 20:23:46 +01007509 std::string RecName = std::string(CDecl->getName());
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007510 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007511 RecordDecl *RD = RecordDecl::Create(
7512 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7513 &Context->Idents.get(RecName));
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007514 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00007515 unsigned UnsignedIntSize =
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007516 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7517 Expr *Zero = IntegerLiteral::Create(*Context,
7518 llvm::APInt(UnsignedIntSize, 0),
7519 Context->UnsignedIntTy, SourceLocation());
7520 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7521 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7522 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007523 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007524 SourceLocation(),
7525 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007526 IvarT, nullptr,
7527 /*BitWidth=*/nullptr,
7528 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00007529 MemberExpr *ME = MemberExpr::CreateImplicit(
7530 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007531 IvarT = Context->getDecltypeType(ME, ME->getType());
7532 }
7533 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007534 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007535 QualType castT = Context->getPointerType(IvarT);
Fangrui Song6907ce22018-07-30 19:24:48 +00007536
7537 castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007538 castT,
7539 CK_BitCast,
7540 PE);
Fangrui Song6907ce22018-07-30 19:24:48 +00007541
7542
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007543 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007544 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00007545 SourceLocation(), false);
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007546 PE = new (Context) ParenExpr(OldRange.getBegin(),
7547 OldRange.getEnd(),
7548 Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00007549
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007550 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007551 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007552 SourceLocation(),
7553 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007554 D->getType(), nullptr,
7555 /*BitWidth=*/D->getBitWidth(),
7556 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00007557 MemberExpr *ME =
7558 MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7559 FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007560 Replacement = ME;
7561
7562 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007563 else
7564 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007565 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007566
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007567 ReplaceStmtWithRange(IV, Replacement, OldRange);
Fangrui Song6907ce22018-07-30 19:24:48 +00007568 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007569}
Alp Toker0621cb22014-07-16 16:48:33 +00007570
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007571#endif // CLANG_ENABLE_OBJC_REWRITER