blob: 8c41e71ef0187b31c3d59fb8f5d1e334b3245045 [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,
Serge Pavlovde044f72020-09-12 17:05:26 +0700589 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 =
Serge Pavlovde044f72020-09-12 17:05:26 +07002108 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2109 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>();
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002112 CallExpr *Exp =
2113 CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2114 VK_RValue, EndLoc, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002115 return Exp;
2116}
2117
2118static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2119 const char *&startRef, const char *&endRef) {
2120 while (startBuf < endBuf) {
2121 if (*startBuf == '<')
2122 startRef = startBuf; // mark the start.
2123 if (*startBuf == '>') {
2124 if (startRef && *startRef == '<') {
2125 endRef = startBuf; // mark the end.
2126 return true;
2127 }
2128 return false;
2129 }
2130 startBuf++;
2131 }
2132 return false;
2133}
2134
2135static void scanToNextArgument(const char *&argRef) {
2136 int angle = 0;
2137 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2138 if (*argRef == '<')
2139 angle++;
2140 else if (*argRef == '>')
2141 angle--;
2142 argRef++;
2143 }
2144 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2145}
2146
2147bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2148 if (T->isObjCQualifiedIdType())
2149 return true;
2150 if (const PointerType *PT = T->getAs<PointerType>()) {
2151 if (PT->getPointeeType()->isObjCQualifiedIdType())
2152 return true;
2153 }
2154 if (T->isObjCObjectPointerType()) {
2155 T = T->getPointeeType();
2156 return T->isObjCQualifiedInterfaceType();
2157 }
2158 if (T->isArrayType()) {
2159 QualType ElemTy = Context->getBaseElementType(T);
2160 return needToScanForQualifiers(ElemTy);
2161 }
2162 return false;
2163}
2164
2165void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2166 QualType Type = E->getType();
2167 if (needToScanForQualifiers(Type)) {
2168 SourceLocation Loc, EndLoc;
2169
2170 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2171 Loc = ECE->getLParenLoc();
2172 EndLoc = ECE->getRParenLoc();
2173 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002174 Loc = E->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002175 EndLoc = E->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002176 }
2177 // This will defend against trying to rewrite synthesized expressions.
2178 if (Loc.isInvalid() || EndLoc.isInvalid())
2179 return;
2180
2181 const char *startBuf = SM->getCharacterData(Loc);
2182 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002183 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002184 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2185 // Get the locations of the startRef, endRef.
2186 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2187 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2188 // Comment out the protocol references.
2189 InsertText(LessLoc, "/*");
2190 InsertText(GreaterLoc, "*/");
2191 }
2192 }
2193}
2194
2195void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2196 SourceLocation Loc;
2197 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002198 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002199 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2200 Loc = VD->getLocation();
2201 Type = VD->getType();
2202 }
2203 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2204 Loc = FD->getLocation();
2205 // Check for ObjC 'id' and class types that have been adorned with protocol
2206 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2207 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2208 assert(funcType && "missing function type");
2209 proto = dyn_cast<FunctionProtoType>(funcType);
2210 if (!proto)
2211 return;
Alp Toker314cc812014-01-25 16:55:45 +00002212 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002213 }
2214 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2215 Loc = FD->getLocation();
2216 Type = FD->getType();
2217 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002218 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2219 Loc = TD->getLocation();
2220 Type = TD->getUnderlyingType();
2221 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002222 else
2223 return;
2224
2225 if (needToScanForQualifiers(Type)) {
2226 // Since types are unique, we need to scan the buffer.
2227
2228 const char *endBuf = SM->getCharacterData(Loc);
2229 const char *startBuf = endBuf;
2230 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2231 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002232 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002233 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2234 // Get the locations of the startRef, endRef.
2235 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2236 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2237 // Comment out the protocol references.
2238 InsertText(LessLoc, "/*");
2239 InsertText(GreaterLoc, "*/");
2240 }
2241 }
2242 if (!proto)
2243 return; // most likely, was a variable
2244 // Now check arguments.
2245 const char *startBuf = SM->getCharacterData(Loc);
2246 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002247 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2248 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002249 // Since types are unique, we need to scan the buffer.
2250
2251 const char *endBuf = startBuf;
2252 // scan forward (from the decl location) for argument types.
2253 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002254 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
2257 SourceLocation LessLoc =
2258 Loc.getLocWithOffset(startRef-startFuncBuf);
2259 SourceLocation GreaterLoc =
2260 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2261 // Comment out the protocol references.
2262 InsertText(LessLoc, "/*");
2263 InsertText(GreaterLoc, "*/");
2264 }
2265 startBuf = ++endBuf;
2266 }
2267 else {
2268 // If the function name is derived from a macro expansion, then the
2269 // argument buffer will not follow the name. Need to speak with Chris.
2270 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2271 startBuf++; // scan forward (from the decl location) for argument types.
2272 startBuf++;
2273 }
2274 }
2275}
2276
2277void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2278 QualType QT = ND->getType();
2279 const Type* TypePtr = QT->getAs<Type>();
2280 if (!isa<TypeOfExprType>(TypePtr))
2281 return;
2282 while (isa<TypeOfExprType>(TypePtr)) {
2283 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2284 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2285 TypePtr = QT->getAs<Type>();
2286 }
2287 // FIXME. This will not work for multiple declarators; as in:
2288 // __typeof__(a) b,c,d;
2289 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2290 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2291 const char *startBuf = SM->getCharacterData(DeclLoc);
2292 if (ND->getInit()) {
2293 std::string Name(ND->getNameAsString());
2294 TypeAsString += " " + Name + " = ";
2295 Expr *E = ND->getInit();
2296 SourceLocation startLoc;
2297 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2298 startLoc = ECE->getLParenLoc();
2299 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002300 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002301 startLoc = SM->getExpansionLoc(startLoc);
2302 const char *endBuf = SM->getCharacterData(startLoc);
2303 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2304 }
2305 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002306 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002307 X = SM->getExpansionLoc(X);
2308 const char *endBuf = SM->getCharacterData(X);
2309 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2310 }
2311}
2312
2313// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2314void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2315 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2316 SmallVector<QualType, 16> ArgTys;
2317 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2318 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002319 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002320 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002321 SourceLocation(),
2322 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002323 SelGetUidIdent, getFuncType,
2324 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002325}
2326
2327void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2328 // declared in <objc/objc.h>
2329 if (FD->getIdentifier() &&
2330 FD->getName() == "sel_registerName") {
2331 SelGetUidFunctionDecl = FD;
2332 return;
2333 }
2334 RewriteObjCQualifiedInterfaceTypes(FD);
2335}
2336
2337void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2338 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2339 const char *argPtr = TypeString.c_str();
2340 if (!strchr(argPtr, '^')) {
2341 Str += TypeString;
2342 return;
2343 }
2344 while (*argPtr) {
2345 Str += (*argPtr == '^' ? '*' : *argPtr);
2346 argPtr++;
2347 }
2348}
2349
2350// FIXME. Consolidate this routine with RewriteBlockPointerType.
2351void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2352 ValueDecl *VD) {
2353 QualType Type = VD->getType();
2354 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2355 const char *argPtr = TypeString.c_str();
2356 int paren = 0;
2357 while (*argPtr) {
2358 switch (*argPtr) {
2359 case '(':
2360 Str += *argPtr;
2361 paren++;
2362 break;
2363 case ')':
2364 Str += *argPtr;
2365 paren--;
2366 break;
2367 case '^':
2368 Str += '*';
2369 if (paren == 1)
2370 Str += VD->getNameAsString();
2371 break;
2372 default:
2373 Str += *argPtr;
2374 break;
2375 }
2376 argPtr++;
2377 }
2378}
2379
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002380void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2381 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2382 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2383 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2384 if (!proto)
2385 return;
Alp Toker314cc812014-01-25 16:55:45 +00002386 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002387 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2388 FdStr += " ";
2389 FdStr += FD->getName();
2390 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002391 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002392 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002393 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002394 RewriteBlockPointerType(FdStr, ArgType);
2395 if (i+1 < numArgs)
2396 FdStr += ", ";
2397 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002398 if (FD->isVariadic()) {
2399 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2400 }
2401 else
2402 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002403 InsertText(FunLocStart, FdStr);
2404}
2405
Benjamin Kramer60509af2013-09-09 14:48:42 +00002406// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2407void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2408 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002409 return;
2410 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2411 SmallVector<QualType, 16> ArgTys;
2412 QualType argT = Context->getObjCIdType();
2413 assert(!argT.isNull() && "Can't find 'id' type");
2414 ArgTys.push_back(argT);
2415 ArgTys.push_back(argT);
2416 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002417 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002418 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002419 SourceLocation(),
2420 SourceLocation(),
2421 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002422 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002423}
2424
2425// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2426void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2427 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2428 SmallVector<QualType, 16> ArgTys;
2429 QualType argT = Context->getObjCIdType();
2430 assert(!argT.isNull() && "Can't find 'id' type");
2431 ArgTys.push_back(argT);
2432 argT = Context->getObjCSelType();
2433 assert(!argT.isNull() && "Can't find 'SEL' type");
2434 ArgTys.push_back(argT);
2435 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002436 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002437 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002438 SourceLocation(),
2439 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002440 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002441 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002442}
2443
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002444// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002445void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2446 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002447 SmallVector<QualType, 2> ArgTys;
2448 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002449 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002450 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002451 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002452 SourceLocation(),
2453 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002454 msgSendIdent, msgSendType,
2455 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002456}
2457
2458// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2459void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2460 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2461 SmallVector<QualType, 16> ArgTys;
2462 QualType argT = Context->getObjCIdType();
2463 assert(!argT.isNull() && "Can't find 'id' type");
2464 ArgTys.push_back(argT);
2465 argT = Context->getObjCSelType();
2466 assert(!argT.isNull() && "Can't find 'SEL' type");
2467 ArgTys.push_back(argT);
2468 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002469 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002470 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002471 SourceLocation(),
2472 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002473 msgSendIdent, msgSendType,
2474 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002475}
2476
2477// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002478// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002479void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2480 IdentifierInfo *msgSendIdent =
2481 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002482 SmallVector<QualType, 2> ArgTys;
2483 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002484 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002485 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002486 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2487 SourceLocation(),
2488 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002489 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002490 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002491 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002492}
2493
2494// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2495void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2496 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2497 SmallVector<QualType, 16> ArgTys;
2498 QualType argT = Context->getObjCIdType();
2499 assert(!argT.isNull() && "Can't find 'id' type");
2500 ArgTys.push_back(argT);
2501 argT = Context->getObjCSelType();
2502 assert(!argT.isNull() && "Can't find 'SEL' type");
2503 ArgTys.push_back(argT);
2504 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002505 ArgTys, /*variadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002506 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002507 SourceLocation(),
2508 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002509 msgSendIdent, msgSendType,
2510 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002511}
2512
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002513// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002514void RewriteModernObjC::SynthGetClassFunctionDecl() {
2515 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2516 SmallVector<QualType, 16> ArgTys;
2517 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002518 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002519 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002520 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002521 SourceLocation(),
2522 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002523 getClassIdent, getClassType,
2524 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002525}
2526
2527// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2528void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
Fangrui Song6907ce22018-07-30 19:24:48 +00002529 IdentifierInfo *getSuperClassIdent =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002530 &Context->Idents.get("class_getSuperclass");
2531 SmallVector<QualType, 16> ArgTys;
2532 ArgTys.push_back(Context->getObjCClassType());
2533 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002534 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002535 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2536 SourceLocation(),
2537 SourceLocation(),
2538 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002539 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002540 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002541}
2542
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002543// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002544void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2545 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2546 SmallVector<QualType, 16> ArgTys;
2547 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002548 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002549 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002550 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002551 SourceLocation(),
2552 SourceLocation(),
2553 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002554 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555}
2556
2557Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002558 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002559 QualType strType = getConstantStringStructType();
2560
2561 std::string S = "__NSConstantStringImpl_";
2562
2563 std::string tmpName = InFileName;
2564 unsigned i;
2565 for (i=0; i < tmpName.length(); i++) {
2566 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002567 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002568 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002569 tmpName[i] = '_';
2570 }
2571 S += tmpName;
2572 S += "_";
2573 S += utostr(NumObjCStringLiterals++);
2574
2575 Preamble += "static __NSConstantStringImpl " + S;
2576 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2577 Preamble += "0x000007c8,"; // utf8_str
2578 // The pretty printer for StringLiteral handles escape characters properly.
2579 std::string prettyBufS;
2580 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002581 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002582 Preamble += prettyBuf.str();
2583 Preamble += ",";
2584 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2585
2586 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2587 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002588 strType, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002589 DeclRefExpr *DRE = new (Context)
2590 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
Melanie Blowerf5360d42020-05-01 10:32:06 -07002591 Expr *Unop = UnaryOperator::Create(
2592 const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2593 Context->getPointerType(DRE->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07002594 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002595 // cast to NSConstantString *
2596 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2597 CK_CPointerToObjCPointerCast, Unop);
2598 ReplaceStmt(Exp, cast);
2599 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2600 return cast;
2601}
2602
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002603Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2604 unsigned IntSize =
2605 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00002606
2607 Expr *FlagExp = IntegerLiteral::Create(*Context,
2608 llvm::APInt(IntSize, Exp->getValue()),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002609 Context->IntTy, Exp->getLocation());
2610 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2611 CK_BitCast, FlagExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002612 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002613 cast);
2614 ReplaceStmt(Exp, PE);
2615 return PE;
2616}
2617
Patrick Beard0caa3942012-04-19 00:25:12 +00002618Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002619 // synthesize declaration of helper functions needed in this routine.
2620 if (!SelGetUidFunctionDecl)
2621 SynthSelGetUidFunctionDecl();
2622 // use objc_msgSend() for all.
2623 if (!MsgSendFunctionDecl)
2624 SynthMsgSendFunctionDecl();
2625 if (!GetClassFunctionDecl)
2626 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002627
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002628 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002629 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002630 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002631
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002632 // Synthesize a call to objc_msgSend().
2633 SmallVector<Expr*, 4> MsgExprs;
2634 SmallVector<Expr*, 4> ClsExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002635
Patrick Beard0caa3942012-04-19 00:25:12 +00002636 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2637 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2638 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002639
Patrick Beard0caa3942012-04-19 00:25:12 +00002640 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002641 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002642 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002643 StartLoc, EndLoc);
2644 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002645
Patrick Beard0caa3942012-04-19 00:25:12 +00002646 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002647 // it will be the 2nd argument.
2648 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002649 SelExprs.push_back(
2650 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002651 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002652 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002653 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002654
Patrick Beard0caa3942012-04-19 00:25:12 +00002655 // User provided sub-expression is the 3rd, and last, argument.
2656 Expr *subExpr = Exp->getSubExpr();
2657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002658 QualType type = ICE->getType();
2659 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2660 CastKind CK = CK_BitCast;
2661 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2662 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002663 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002664 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002665 MsgExprs.push_back(subExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00002666
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002667 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002668 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002669 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002670 for (const auto PI : BoxingMethod->parameters())
2671 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002672
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002673 QualType returnType = Exp->getType();
2674 // Get the type, we will need to reference it in a couple spots.
2675 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002676
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002677 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002678 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2679 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002680
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002681 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2682 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002683
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002684 // Now do the "normal" pointer to function cast.
2685 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002686 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002687 castType = Context->getPointerType(castType);
2688 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2689 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002690
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002691 // Don't forget the parens to enforce the proper binding.
2692 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002693
Simon Pilgrim7bfc3bf2020-03-12 16:49:35 +00002694 auto *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002695 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002696 VK_RValue, EndLoc, FPOptionsOverride());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002697 ReplaceStmt(Exp, CE);
2698 return CE;
2699}
2700
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002701Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2702 // synthesize declaration of helper functions needed in this routine.
2703 if (!SelGetUidFunctionDecl)
2704 SynthSelGetUidFunctionDecl();
2705 // use objc_msgSend() for all.
2706 if (!MsgSendFunctionDecl)
2707 SynthMsgSendFunctionDecl();
2708 if (!GetClassFunctionDecl)
2709 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002710
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002711 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002712 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002713 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002714
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002715 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002716 QualType IntQT = Context->IntTy;
2717 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002718 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002719 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002720 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002721 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2722 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002723
2724 SmallVector<Expr*, 16> InitExprs;
2725 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002726 unsigned UnsignedIntSize =
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002727 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2728 Expr *count = IntegerLiteral::Create(*Context,
2729 llvm::APInt(UnsignedIntSize, NumElements),
2730 Context->UnsignedIntTy, SourceLocation());
2731 InitExprs.push_back(count);
2732 for (unsigned i = 0; i < NumElements; i++)
2733 InitExprs.push_back(Exp->getElement(i));
Fangrui Song6907ce22018-07-30 19:24:48 +00002734 Expr *NSArrayCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002735 CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002736 SourceLocation(), FPOptionsOverride());
Craig Topper8ae12032014-05-07 06:21:57 +00002737
2738 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002739 SourceLocation(),
2740 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002741 Context->getPointerType(Context->VoidPtrTy),
2742 nullptr, /*BitWidth=*/nullptr,
2743 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00002744 MemberExpr *ArrayLiteralME =
2745 MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2746 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002747 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002748 CStyleCastExpr * ArrayLiteralObjects =
2749 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002750 Context->getPointerType(ConstIdT),
2751 CK_BitCast,
2752 ArrayLiteralME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002753
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002754 // Synthesize a call to objc_msgSend().
2755 SmallVector<Expr*, 32> MsgExprs;
2756 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002757 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002758
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002759 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002760 ObjCInterfaceDecl *Class =
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002761 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002762
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002763 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002764 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002765 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002766 StartLoc, EndLoc);
2767 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002768
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002769 // Create a call to sel_registerName("arrayWithObjects:count:").
2770 // it will be the 2nd argument.
2771 SmallVector<Expr*, 4> SelExprs;
2772 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002773 SelExprs.push_back(
2774 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002775 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002776 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002777 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002778
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002779 // (const id [])objects
2780 MsgExprs.push_back(ArrayLiteralObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002781
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002782 // (NSUInteger)cnt
2783 Expr *cnt = IntegerLiteral::Create(*Context,
2784 llvm::APInt(UnsignedIntSize, NumElements),
2785 Context->UnsignedIntTy, SourceLocation());
2786 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002787
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002788 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002789 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002790 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002791 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002792 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002793
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002794 QualType returnType = Exp->getType();
2795 // Get the type, we will need to reference it in a couple spots.
2796 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002797
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002798 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002799 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2800 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002801
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002802 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2803 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002804
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002805 // Now do the "normal" pointer to function cast.
2806 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002807 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002808 castType = Context->getPointerType(castType);
2809 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2810 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002811
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002812 // Don't forget the parens to enforce the proper binding.
2813 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002814
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002815 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002816 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002817 VK_RValue, EndLoc, FPOptionsOverride());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002818 ReplaceStmt(Exp, CE);
2819 return CE;
2820}
2821
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002822Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2823 // synthesize declaration of helper functions needed in this routine.
2824 if (!SelGetUidFunctionDecl)
2825 SynthSelGetUidFunctionDecl();
2826 // use objc_msgSend() for all.
2827 if (!MsgSendFunctionDecl)
2828 SynthMsgSendFunctionDecl();
2829 if (!GetClassFunctionDecl)
2830 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002831
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002832 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002833 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002834 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002835
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002836 // Build the expression: __NSContainer_literal(int, ...).arr
2837 QualType IntQT = Context->IntTy;
2838 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002839 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002840 std::string NSDictFName("__NSContainer_literal");
2841 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002842 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2843 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002844
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002845 SmallVector<Expr*, 16> KeyExprs;
2846 SmallVector<Expr*, 16> ValueExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002847
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002848 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002849 unsigned UnsignedIntSize =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002850 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2851 Expr *count = IntegerLiteral::Create(*Context,
2852 llvm::APInt(UnsignedIntSize, NumElements),
2853 Context->UnsignedIntTy, SourceLocation());
2854 KeyExprs.push_back(count);
2855 ValueExprs.push_back(count);
2856 for (unsigned i = 0; i < NumElements; i++) {
2857 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2858 KeyExprs.push_back(Element.Key);
2859 ValueExprs.push_back(Element.Value);
2860 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002861
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002862 // (const id [])objects
Fangrui Song6907ce22018-07-30 19:24:48 +00002863 Expr *NSValueCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002864 CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002865 SourceLocation(), FPOptionsOverride());
Craig Topper8ae12032014-05-07 06:21:57 +00002866
2867 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002868 SourceLocation(),
2869 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002870 Context->getPointerType(Context->VoidPtrTy),
2871 nullptr, /*BitWidth=*/nullptr,
2872 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00002873 MemberExpr *DictLiteralValueME =
2874 MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2875 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002876 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002877 CStyleCastExpr * DictValueObjects =
2878 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002879 Context->getPointerType(ConstIdT),
2880 CK_BitCast,
2881 DictLiteralValueME);
2882 // (const id <NSCopying> [])keys
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002883 Expr *NSKeyCallExpr =
2884 CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue,
2885 SourceLocation(), FPOptionsOverride());
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002886
Richard Smithdcf17de2019-06-06 23:24:15 +00002887 MemberExpr *DictLiteralKeyME =
2888 MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2889 ARRFD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002890
Fangrui Song6907ce22018-07-30 19:24:48 +00002891 CStyleCastExpr * DictKeyObjects =
2892 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002893 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002894 CK_BitCast,
2895 DictLiteralKeyME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002896
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002897 // Synthesize a call to objc_msgSend().
2898 SmallVector<Expr*, 32> MsgExprs;
2899 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002900 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002901
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002902 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002903 ObjCInterfaceDecl *Class =
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002904 expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002905
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002906 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002907 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002908 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002909 StartLoc, EndLoc);
2910 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002911
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002912 // Create a call to sel_registerName("arrayWithObjects:count:").
2913 // it will be the 2nd argument.
2914 SmallVector<Expr*, 4> SelExprs;
2915 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002916 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002917 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002918 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002919 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002920
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 // (const id [])objects
2922 MsgExprs.push_back(DictValueObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002923
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002924 // (const id <NSCopying> [])keys
2925 MsgExprs.push_back(DictKeyObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002926
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002927 // (NSUInteger)cnt
2928 Expr *cnt = IntegerLiteral::Create(*Context,
2929 llvm::APInt(UnsignedIntSize, NumElements),
2930 Context->UnsignedIntTy, SourceLocation());
2931 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002932
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002933 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002934 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002935 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002936 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002937 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002938 if (const PointerType* PT = T->getAs<PointerType>()) {
2939 QualType PointeeTy = PT->getPointeeType();
2940 convertToUnqualifiedObjCType(PointeeTy);
2941 T = Context->getPointerType(PointeeTy);
2942 }
2943 ArgTypes.push_back(T);
2944 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002945
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002946 QualType returnType = Exp->getType();
2947 // Get the type, we will need to reference it in a couple spots.
2948 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002949
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002950 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002951 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2952 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002953
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002954 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2955 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002956
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002957 // Now do the "normal" pointer to function cast.
2958 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002959 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002960 castType = Context->getPointerType(castType);
2961 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2962 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002963
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 // Don't forget the parens to enforce the proper binding.
2965 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002966
Simon Pilgrim8dc170092019-10-07 13:58:15 +00002967 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002968 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
Serge Pavlov70e7aa42020-07-24 12:04:19 +07002969 VK_RValue, EndLoc, FPOptionsOverride());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002970 ReplaceStmt(Exp, CE);
2971 return CE;
2972}
2973
Fangrui Song6907ce22018-07-30 19:24:48 +00002974// struct __rw_objc_super {
2975// struct objc_object *object; struct objc_object *superClass;
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002976// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002977QualType RewriteModernObjC::getSuperStructType() {
2978 if (!SuperStructDecl) {
2979 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2980 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002981 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002982 QualType FieldTypes[2];
2983
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002984 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002985 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002986 // struct objc_object *superClass;
2987 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002988
2989 // Create fields
2990 for (unsigned i = 0; i < 2; ++i) {
2991 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2992 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002993 SourceLocation(), nullptr,
2994 FieldTypes[i], nullptr,
2995 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002996 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002997 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002998 }
2999
3000 SuperStructDecl->completeDefinition();
3001 }
3002 return Context->getTagDeclType(SuperStructDecl);
3003}
3004
3005QualType RewriteModernObjC::getConstantStringStructType() {
3006 if (!ConstantStringDecl) {
3007 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3008 SourceLocation(), SourceLocation(),
3009 &Context->Idents.get("__NSConstantStringImpl"));
3010 QualType FieldTypes[4];
3011
3012 // struct objc_object *receiver;
3013 FieldTypes[0] = Context->getObjCIdType();
3014 // int flags;
3015 FieldTypes[1] = Context->IntTy;
3016 // char *str;
3017 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3018 // long length;
3019 FieldTypes[3] = Context->LongTy;
3020
3021 // Create fields
3022 for (unsigned i = 0; i < 4; ++i) {
3023 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3024 ConstantStringDecl,
3025 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003026 SourceLocation(), nullptr,
3027 FieldTypes[i], nullptr,
3028 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003029 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003030 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003031 }
3032
3033 ConstantStringDecl->completeDefinition();
3034 }
3035 return Context->getTagDeclType(ConstantStringDecl);
3036}
3037
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003038/// getFunctionSourceLocation - returns start location of a function
3039/// definition. Complication arises when function has declared as
3040/// extern "C" or extern "C" {...}
3041static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3042 FunctionDecl *FD) {
3043 if (FD->isExternC() && !FD->isMain()) {
3044 const DeclContext *DC = FD->getDeclContext();
3045 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3046 // if it is extern "C" {...}, return function decl's own location.
3047 if (!LSD->getRBraceLoc().isValid())
3048 return LSD->getExternLoc();
3049 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003050 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003051 R.RewriteBlockLiteralFunctionDecl(FD);
3052 return FD->getTypeSpecStartLoc();
3053}
3054
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003055void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003056
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003057 SourceLocation Location = D->getLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003058
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003059 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003060 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003061 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3062 LineString += utostr(PLoc.getLine());
3063 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003064 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003065 if (isa<ObjCMethodDecl>(D))
3066 LineString += "\"";
3067 else LineString += "\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003068
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003069 Location = D->getBeginLoc();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3071 if (FD->isExternC() && !FD->isMain()) {
3072 const DeclContext *DC = FD->getDeclContext();
3073 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3074 // if it is extern "C" {...}, return function decl's own location.
3075 if (!LSD->getRBraceLoc().isValid())
3076 Location = LSD->getExternLoc();
3077 }
3078 }
3079 InsertText(Location, LineString);
3080 }
3081}
3082
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003083/// SynthMsgSendStretCallExpr - This routine translates message expression
3084/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3085/// nil check on receiver must be performed before calling objc_msgSend_stret.
3086/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3087/// msgSendType - function type of objc_msgSend_stret(...)
3088/// returnType - Result type of the method being synthesized.
3089/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003090/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003091/// starting with receiver.
3092/// Method - Method being rewritten.
3093Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +00003094 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003095 SmallVectorImpl<QualType> &ArgTypes,
3096 SmallVectorImpl<Expr*> &MsgExprs,
3097 ObjCMethodDecl *Method) {
3098 // Now do the "normal" pointer to function cast.
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003099 QualType FuncType = getSimpleFunctionType(
3100 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3101 QualType castType = Context->getPointerType(FuncType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003102
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003103 // build type for containing the objc_msgSend_stret object.
3104 static unsigned stretCount=0;
3105 std::string name = "__Stret"; name += utostr(stretCount);
Fangrui Song6907ce22018-07-30 19:24:48 +00003106 std::string str =
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003107 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003108 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003109 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003110 str += " {\n\t";
3111 str += name;
3112 str += "(id receiver, SEL sel";
3113 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003114 std::string ArgName = "arg"; ArgName += utostr(i);
3115 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3116 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003117 }
3118 // could be vararg.
3119 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003120 std::string ArgName = "arg"; ArgName += utostr(i);
3121 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3122 Context->getPrintingPolicy());
3123 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003124 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003125
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003126 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003127 str += "\t unsigned size = sizeof(";
3128 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003129
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003130 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003131
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003132 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3133 str += ")(void *)objc_msgSend)(receiver, sel";
3134 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3135 str += ", arg"; str += utostr(i);
3136 }
3137 // could be vararg.
3138 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3139 str += ", arg"; str += utostr(i);
3140 }
3141 str+= ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003142
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003143 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003144 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3145 str += "\t else\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003146
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003147 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3148 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3149 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3150 str += ", arg"; str += utostr(i);
3151 }
3152 // could be vararg.
3153 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3154 str += ", arg"; str += utostr(i);
3155 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003156 str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003157
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003158 str += "\t}\n";
3159 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3160 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003161 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003162 SourceLocation FunLocStart;
3163 if (CurFunctionDef)
3164 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3165 else {
3166 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003167 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003168 }
3169
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003170 InsertText(FunLocStart, str);
3171 ++stretCount;
Fangrui Song6907ce22018-07-30 19:24:48 +00003172
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003173 // AST for __Stretn(receiver, args).s;
3174 IdentifierInfo *ID = &Context->Idents.get(name);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003175 FunctionDecl *FD =
3176 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3177 ID, FuncType, nullptr, SC_Extern, false, false);
Bruno Riccic5885cf2018-12-21 15:20:32 +00003178 DeclRefExpr *DRE = new (Context)
3179 DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
Serge Pavlov70e7aa42020-07-24 12:04:19 +07003180 CallExpr *STCE =
3181 CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue,
3182 SourceLocation(), FPOptionsOverride());
Craig Topper8ae12032014-05-07 06:21:57 +00003183
3184 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003185 SourceLocation(),
3186 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003187 returnType, nullptr,
3188 /*BitWidth=*/nullptr,
3189 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00003190 MemberExpr *ME = MemberExpr::CreateImplicit(
3191 *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003192
3193 return ME;
3194}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003195
Fariborz Jahanian11671902012-02-07 17:11:38 +00003196Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3197 SourceLocation StartLoc,
3198 SourceLocation EndLoc) {
3199 if (!SelGetUidFunctionDecl)
3200 SynthSelGetUidFunctionDecl();
3201 if (!MsgSendFunctionDecl)
3202 SynthMsgSendFunctionDecl();
3203 if (!MsgSendSuperFunctionDecl)
3204 SynthMsgSendSuperFunctionDecl();
3205 if (!MsgSendStretFunctionDecl)
3206 SynthMsgSendStretFunctionDecl();
3207 if (!MsgSendSuperStretFunctionDecl)
3208 SynthMsgSendSuperStretFunctionDecl();
3209 if (!MsgSendFpretFunctionDecl)
3210 SynthMsgSendFpretFunctionDecl();
3211 if (!GetClassFunctionDecl)
3212 SynthGetClassFunctionDecl();
3213 if (!GetSuperClassFunctionDecl)
3214 SynthGetSuperClassFunctionDecl();
3215 if (!GetMetaClassFunctionDecl)
3216 SynthGetMetaClassFunctionDecl();
3217
3218 // default to objc_msgSend().
3219 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3220 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003221 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003222 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003223 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003224 if (resultType->isRecordType())
3225 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3226 else if (resultType->isRealFloatingType())
3227 MsgSendFlavor = MsgSendFpretFunctionDecl;
3228 }
3229
3230 // Synthesize a call to objc_msgSend().
3231 SmallVector<Expr*, 8> MsgExprs;
3232 switch (Exp->getReceiverKind()) {
3233 case ObjCMessageExpr::SuperClass: {
3234 MsgSendFlavor = MsgSendSuperFunctionDecl;
3235 if (MsgSendStretFlavor)
3236 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3237 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3238
3239 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3240
3241 SmallVector<Expr*, 4> InitExprs;
3242
3243 // set the receiver to self, the first argument to all methods.
3244 InitExprs.push_back(
3245 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3246 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003247 new (Context) DeclRefExpr(*Context,
3248 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003249 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003250 Context->getObjCIdType(),
3251 VK_RValue,
3252 SourceLocation()))
3253 ); // set the 'receiver'.
3254
3255 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3256 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003257 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003258 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003259 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003260 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003261 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003262 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003263 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003264 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003265
Fariborz Jahanian11671902012-02-07 17:11:38 +00003266 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3267 // To turn off a warning, type-cast to 'id'
3268 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3269 NoTypeInfoCStyleCastExpr(Context,
3270 Context->getObjCIdType(),
3271 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003272 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003273 QualType superType = getSuperStructType();
3274 Expr *SuperRep;
3275
3276 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003277 SynthSuperConstructorFunctionDecl();
3278 // Simulate a constructor call...
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003279 DeclRefExpr *DRE = new (Context)
3280 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3281 VK_LValue, SourceLocation());
Serge Pavlov70e7aa42020-07-24 12:04:19 +07003282 SuperRep =
3283 CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3284 SourceLocation(), FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003285 // The code for super is a little tricky to prevent collision with
3286 // the structure definition in the header. The rewriter has it's own
3287 // internal definition (__rw_objc_super) that is uses. This is why
3288 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003289 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003290 //
Melanie Blowerf5360d42020-05-01 10:32:06 -07003291 SuperRep = UnaryOperator::Create(
3292 const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3293 Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003294 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003295 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3296 Context->getPointerType(superType),
3297 CK_BitCast, SuperRep);
3298 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003299 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003300 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003301 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003302 SourceLocation());
3303 TypeSourceInfo *superTInfo
3304 = Context->getTrivialTypeSourceInfo(superType);
3305 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3306 superType, VK_LValue,
3307 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003308 // struct __rw_objc_super *
Melanie Blowerf5360d42020-05-01 10:32:06 -07003309 SuperRep = UnaryOperator::Create(
3310 const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3311 Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003312 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003313 }
3314 MsgExprs.push_back(SuperRep);
3315 break;
3316 }
3317
3318 case ObjCMessageExpr::Class: {
3319 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003320 ObjCInterfaceDecl *Class
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003321 = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003322 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003323 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003324 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003325 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003326 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3327 Context->getObjCIdType(),
3328 CK_BitCast, Cls);
3329 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003330 break;
3331 }
3332
3333 case ObjCMessageExpr::SuperInstance:{
3334 MsgSendFlavor = MsgSendSuperFunctionDecl;
3335 if (MsgSendStretFlavor)
3336 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3337 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3338 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3339 SmallVector<Expr*, 4> InitExprs;
3340
3341 InitExprs.push_back(
3342 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3343 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003344 new (Context) DeclRefExpr(*Context,
3345 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003346 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003347 Context->getObjCIdType(),
3348 VK_RValue, SourceLocation()))
3349 ); // set the 'receiver'.
Fangrui Song6907ce22018-07-30 19:24:48 +00003350
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3352 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003353 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003354 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003355 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003356 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003357 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003358 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003359 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003360 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003361
Fariborz Jahanian11671902012-02-07 17:11:38 +00003362 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3363 // To turn off a warning, type-cast to 'id'
3364 InitExprs.push_back(
3365 // set 'super class', using class_getSuperclass().
3366 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3367 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003368 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003369 QualType superType = getSuperStructType();
3370 Expr *SuperRep;
3371
3372 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003373 SynthSuperConstructorFunctionDecl();
3374 // Simulate a constructor call...
Bruno Riccic5885cf2018-12-21 15:20:32 +00003375 DeclRefExpr *DRE = new (Context)
3376 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3377 VK_LValue, SourceLocation());
Serge Pavlov70e7aa42020-07-24 12:04:19 +07003378 SuperRep =
3379 CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3380 SourceLocation(), FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003381 // The code for super is a little tricky to prevent collision with
3382 // the structure definition in the header. The rewriter has it's own
3383 // internal definition (__rw_objc_super) that is uses. This is why
3384 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003385 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003386 //
Melanie Blowerf5360d42020-05-01 10:32:06 -07003387 SuperRep = UnaryOperator::Create(
3388 const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3389 Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003390 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3392 Context->getPointerType(superType),
3393 CK_BitCast, SuperRep);
3394 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003395 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003396 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003397 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003398 SourceLocation());
3399 TypeSourceInfo *superTInfo
3400 = Context->getTrivialTypeSourceInfo(superType);
3401 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3402 superType, VK_RValue, ILE,
3403 false);
3404 }
3405 MsgExprs.push_back(SuperRep);
3406 break;
3407 }
3408
3409 case ObjCMessageExpr::Instance: {
3410 // Remove all type-casts because it may contain objc-style types; e.g.
3411 // Foo<Proto> *.
3412 Expr *recExpr = Exp->getInstanceReceiver();
3413 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3414 recExpr = CE->getSubExpr();
3415 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3416 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3417 ? CK_BlockPointerToObjCPointerCast
3418 : CK_CPointerToObjCPointerCast;
3419
3420 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3421 CK, recExpr);
3422 MsgExprs.push_back(recExpr);
3423 break;
3424 }
3425 }
3426
3427 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3428 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003429 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003430 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003431 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003432 MsgExprs.push_back(SelExp);
3433
3434 // Now push any user supplied arguments.
3435 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3436 Expr *userExpr = Exp->getArg(i);
3437 // Make all implicit casts explicit...ICE comes in handy:-)
3438 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3439 // Reuse the ICE type, it is exactly what the doctor ordered.
3440 QualType type = ICE->getType();
3441 if (needToScanForQualifiers(type))
3442 type = Context->getObjCIdType();
3443 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3444 (void)convertBlockPointerToFunctionPointer(type);
3445 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3446 CastKind CK;
Fangrui Song6907ce22018-07-30 19:24:48 +00003447 if (SubExpr->getType()->isIntegralType(*Context) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003448 type->isBooleanType()) {
3449 CK = CK_IntegralToBoolean;
3450 } else if (type->isObjCObjectPointerType()) {
3451 if (SubExpr->getType()->isBlockPointerType()) {
3452 CK = CK_BlockPointerToObjCPointerCast;
3453 } else if (SubExpr->getType()->isPointerType()) {
3454 CK = CK_CPointerToObjCPointerCast;
3455 } else {
3456 CK = CK_BitCast;
3457 }
3458 } else {
3459 CK = CK_BitCast;
3460 }
3461
3462 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3463 }
3464 // Make id<P...> cast into an 'id' cast.
3465 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3466 if (CE->getType()->isObjCQualifiedIdType()) {
3467 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3468 userExpr = CE->getSubExpr();
3469 CastKind CK;
3470 if (userExpr->getType()->isIntegralType(*Context)) {
3471 CK = CK_IntegralToPointer;
3472 } else if (userExpr->getType()->isBlockPointerType()) {
3473 CK = CK_BlockPointerToObjCPointerCast;
3474 } else if (userExpr->getType()->isPointerType()) {
3475 CK = CK_CPointerToObjCPointerCast;
3476 } else {
3477 CK = CK_BitCast;
3478 }
3479 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3480 CK, userExpr);
3481 }
3482 }
3483 MsgExprs.push_back(userExpr);
3484 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3485 // out the argument in the original expression (since we aren't deleting
3486 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3487 //Exp->setArg(i, 0);
3488 }
3489 // Generate the funky cast.
3490 CastExpr *cast;
3491 SmallVector<QualType, 8> ArgTypes;
3492 QualType returnType;
3493
3494 // Push 'id' and 'SEL', the 2 implicit arguments.
3495 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3496 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3497 else
3498 ArgTypes.push_back(Context->getObjCIdType());
3499 ArgTypes.push_back(Context->getObjCSelType());
3500 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3501 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003502 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003503 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003504 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003505 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003506 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3507 (void)convertBlockPointerToFunctionPointer(t);
3508 ArgTypes.push_back(t);
3509 }
3510 returnType = Exp->getType();
3511 convertToUnqualifiedObjCType(returnType);
3512 (void)convertBlockPointerToFunctionPointer(returnType);
3513 } else {
3514 returnType = Context->getObjCIdType();
3515 }
3516 // Get the type, we will need to reference it in a couple spots.
3517 QualType msgSendType = MsgSendFlavor->getType();
3518
3519 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003520 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3521 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003522
3523 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3524 // If we don't do this cast, we get the following bizarre warning/note:
3525 // xx.m:13: warning: function called through a non-compatible type
3526 // xx.m:13: note: if this code is reached, the program will abort
3527 cast = NoTypeInfoCStyleCastExpr(Context,
3528 Context->getPointerType(Context->VoidTy),
3529 CK_BitCast, DRE);
3530
3531 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003532 // If we don't have a method decl, force a variadic cast.
3533 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003534 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003535 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003536 castType = Context->getPointerType(castType);
3537 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3538 cast);
3539
3540 // Don't forget the parens to enforce the proper binding.
3541 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3542
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003543 const FunctionType *FT = msgSendType->castAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00003544 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
Serge Pavlov70e7aa42020-07-24 12:04:19 +07003545 VK_RValue, EndLoc, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003546 Stmt *ReplacingStmt = CE;
3547 if (MsgSendStretFlavor) {
3548 // We have the method which returns a struct/union. Must also generate
3549 // call to objc_msgSend_stret and hang both varieties on a conditional
3550 // expression which dictate which one to envoke depending on size of
3551 // method's return type.
3552
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003553 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3554 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003555 ArgTypes, MsgExprs,
3556 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003557 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003558 }
3559 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3560 return ReplacingStmt;
3561}
3562
3563Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003564 Stmt *ReplacingStmt =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003565 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003566
3567 // Now do the actual rewrite.
3568 ReplaceStmt(Exp, ReplacingStmt);
3569
3570 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3571 return ReplacingStmt;
3572}
3573
3574// typedef struct objc_object Protocol;
3575QualType RewriteModernObjC::getProtocolType() {
3576 if (!ProtocolTypeDecl) {
3577 TypeSourceInfo *TInfo
3578 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3579 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3580 SourceLocation(), SourceLocation(),
3581 &Context->Idents.get("Protocol"),
3582 TInfo);
3583 }
3584 return Context->getTypeDeclType(ProtocolTypeDecl);
3585}
3586
3587/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3588/// a synthesized/forward data reference (to the protocol's metadata).
3589/// The forward references (and metadata) are generated in
3590/// RewriteModernObjC::HandleTranslationUnit().
3591Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003592 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003593 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003594 IdentifierInfo *ID = &Context->Idents.get(Name);
3595 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003596 SourceLocation(), ID, getProtocolType(),
3597 nullptr, SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003598 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3599 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3600 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003601 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003602 ReplaceStmt(Exp, castExpr);
3603 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3604 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3605 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003606}
3607
Fangrui Song6907ce22018-07-30 19:24:48 +00003608/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3609/// is defined inside an objective-c class. If so, it returns true.
3610bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003611 TagDecl *Tag,
3612 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003613 if (!IDecl)
3614 return false;
3615 SourceLocation TagLocation;
3616 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3617 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003618 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003619 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003620 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003621 TagLocation = RD->getLocation();
3622 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003623 IDecl->getLocation(), TagLocation);
3624 }
3625 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3626 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3627 return false;
3628 IsNamedDefinition = true;
3629 TagLocation = ED->getLocation();
3630 return Context->getSourceManager().isBeforeInTranslationUnit(
3631 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003632 }
3633 return false;
3634}
3635
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003636/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003637/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003638bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003639 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003640 if (isa<TypedefType>(Type)) {
3641 Result += "\t";
3642 return false;
3643 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003644
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003645 if (Type->isArrayType()) {
3646 QualType ElemTy = Context->getBaseElementType(Type);
3647 return RewriteObjCFieldDeclType(ElemTy, Result);
3648 }
3649 else if (Type->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003650 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003651 if (RD->isCompleteDefinition()) {
3652 if (RD->isStruct())
3653 Result += "\n\tstruct ";
3654 else if (RD->isUnion())
3655 Result += "\n\tunion ";
3656 else
3657 assert(false && "class not allowed as an ivar type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003658
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003659 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003660 if (GlobalDefinedTags.count(RD)) {
3661 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003662 Result += " ";
3663 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003664 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003665 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003666 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003667 RewriteObjCFieldDecl(FD, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003668 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003669 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003670 }
3671 }
3672 else if (Type->isEnumeralType()) {
Simon Pilgrim8dc170092019-10-07 13:58:15 +00003673 EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003674 if (ED->isCompleteDefinition()) {
3675 Result += "\n\tenum ";
3676 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003677 if (GlobalDefinedTags.count(ED)) {
3678 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003679 Result += " ";
3680 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003681 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003682
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003683 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003684 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003685 Result += "\t"; Result += EC->getName(); Result += " = ";
3686 llvm::APSInt Val = EC->getInitVal();
3687 Result += Val.toString(10);
3688 Result += ",\n";
3689 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003690 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003691 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003692 }
3693 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003694
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003695 Result += "\t";
3696 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003697 return false;
3698}
3699
3700
3701/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3702/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003703void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003704 std::string &Result) {
3705 QualType Type = fieldDecl->getType();
3706 std::string Name = fieldDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003707
3708 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003709 if (!EleboratedType)
3710 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003711 Result += Name;
3712 if (fieldDecl->isBitField()) {
3713 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3714 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003715 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003716 const ArrayType *AT = Context->getAsArrayType(Type);
3717 do {
3718 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003719 Result += "[";
3720 llvm::APInt Dim = CAT->getSize();
3721 Result += utostr(Dim.getZExtValue());
3722 Result += "]";
3723 }
Eli Friedman07bab732012-12-13 01:43:21 +00003724 AT = Context->getAsArrayType(AT->getElementType());
3725 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003726 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003727
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003728 Result += ";\n";
3729}
3730
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003731/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3732/// named aggregate types into the input buffer.
Fangrui Song6907ce22018-07-30 19:24:48 +00003733void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003734 std::string &Result) {
3735 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003736 if (isa<TypedefType>(Type))
3737 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003738 if (Type->isArrayType())
3739 Type = Context->getBaseElementType(Type);
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003740
3741 auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003742
3743 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003744 if (Type->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003745 TD = Type->castAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003746 }
3747 else if (Type->isEnumeralType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003748 TD = Type->castAs<EnumType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003749 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003750
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003751 if (TD) {
3752 if (GlobalDefinedTags.count(TD))
3753 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003754
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003755 bool IsNamedDefinition = false;
3756 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3757 RewriteObjCFieldDeclType(Type, Result);
3758 Result += ";";
3759 }
3760 if (IsNamedDefinition)
3761 GlobalDefinedTags.insert(TD);
3762 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003763}
3764
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003765unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3766 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3767 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3768 return IvarGroupNumber[IV];
3769 }
3770 unsigned GroupNo = 0;
3771 SmallVector<const ObjCIvarDecl *, 8> IVars;
3772 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3773 IVD; IVD = IVD->getNextIvar())
3774 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003775
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003776 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3777 if (IVars[i]->isBitField()) {
3778 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3779 while (i < e && IVars[i]->isBitField())
3780 IvarGroupNumber[IVars[i++]] = GroupNo;
3781 if (i < e)
3782 --i;
3783 }
3784
3785 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3786 return IvarGroupNumber[IV];
3787}
3788
3789QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3790 ObjCIvarDecl *IV,
3791 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3792 std::string StructTagName;
3793 ObjCIvarBitfieldGroupType(IV, StructTagName);
3794 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3795 Context->getTranslationUnitDecl(),
3796 SourceLocation(), SourceLocation(),
3797 &Context->Idents.get(StructTagName));
3798 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3799 ObjCIvarDecl *Ivar = IVars[i];
3800 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3801 &Context->Idents.get(Ivar->getName()),
3802 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003803 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3804 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003805 }
3806 RD->completeDefinition();
3807 return Context->getTagDeclType(RD);
3808}
3809
3810QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3811 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3812 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3813 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3814 if (GroupRecordType.count(tuple))
3815 return GroupRecordType[tuple];
Fangrui Song6907ce22018-07-30 19:24:48 +00003816
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003817 SmallVector<ObjCIvarDecl *, 8> IVars;
3818 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3819 IVD; IVD = IVD->getNextIvar()) {
3820 if (IVD->isBitField())
3821 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3822 else {
3823 if (!IVars.empty()) {
3824 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3825 // Generate the struct type for this group of bitfield ivars.
3826 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3827 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3828 IVars.clear();
3829 }
3830 }
3831 }
3832 if (!IVars.empty()) {
3833 // Do the last one.
3834 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3835 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3836 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3837 }
3838 QualType RetQT = GroupRecordType[tuple];
3839 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
Fangrui Song6907ce22018-07-30 19:24:48 +00003840
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003841 return RetQT;
3842}
3843
3844/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3845/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3846void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3847 std::string &Result) {
3848 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3849 Result += CDecl->getName();
3850 Result += "__GRBF_";
3851 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3852 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003853}
3854
3855/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3856/// Name of the struct would be: classname__T_n where n is the group number for
3857/// this ivar.
3858void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3859 std::string &Result) {
3860 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3861 Result += CDecl->getName();
3862 Result += "__T_";
3863 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3864 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003865}
3866
3867/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3868/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3869/// this ivar.
3870void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3871 std::string &Result) {
3872 Result += "OBJC_IVAR_$_";
3873 ObjCIvarBitfieldGroupDecl(IV, Result);
3874}
3875
3876#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3877 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3878 ++IX; \
3879 if (IX < ENDIX) \
3880 --IX; \
3881}
3882
Fariborz Jahanian11671902012-02-07 17:11:38 +00003883/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3884/// an objective-c class with ivars.
3885void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3886 std::string &Result) {
3887 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3888 assert(CDecl->getName() != "" &&
3889 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003890 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003891 SmallVector<ObjCIvarDecl *, 8> IVars;
3892 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003893 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003894 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003895
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003896 SourceLocation LocStart = CDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003897 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00003898
Fariborz Jahanian11671902012-02-07 17:11:38 +00003899 const char *startBuf = SM->getCharacterData(LocStart);
3900 const char *endBuf = SM->getCharacterData(LocEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +00003901
Fariborz Jahanian11671902012-02-07 17:11:38 +00003902 // If no ivars and no root or if its root, directly or indirectly,
3903 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003904 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003905 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3906 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3907 ReplaceText(LocStart, endBuf-startBuf, Result);
3908 return;
3909 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003910
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003911 // Insert named struct/union definitions inside class to
3912 // outer scope. This follows semantics of locally defined
3913 // struct/unions in objective-c classes.
3914 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3915 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003916
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003917 // Insert named structs which are syntheized to group ivar bitfields
3918 // to outer scope as well.
3919 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3920 if (IVars[i]->isBitField()) {
3921 ObjCIvarDecl *IV = IVars[i];
3922 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3923 RewriteObjCFieldDeclType(QT, Result);
3924 Result += ";";
3925 // skip over ivar bitfields in this group.
3926 SKIP_BITFIELDS(i , e, IVars);
3927 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003928
Fariborz Jahanian11671902012-02-07 17:11:38 +00003929 Result += "\nstruct ";
3930 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003931 Result += "_IMPL {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003932
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003933 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003934 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3935 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3936 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003937 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003938
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003939 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3940 if (IVars[i]->isBitField()) {
3941 ObjCIvarDecl *IV = IVars[i];
3942 Result += "\tstruct ";
3943 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3944 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3945 // skip over ivar bitfields in this group.
3946 SKIP_BITFIELDS(i , e, IVars);
3947 }
3948 else
3949 RewriteObjCFieldDecl(IVars[i], Result);
3950 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003951
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003952 Result += "};\n";
3953 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3954 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003955 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003956 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003957 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003958}
3959
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003960/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3961/// have been referenced in an ivar access expression.
3962void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3963 std::string &Result) {
3964 // write out ivar offset symbols which have been referenced in an ivar
3965 // access expression.
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003966 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3967
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003968 if (Ivars.empty())
3969 return;
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003970
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003971 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003972 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003973 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3974 unsigned GroupNo = 0;
3975 if (IvarDecl->isBitField()) {
3976 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3977 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3978 continue;
3979 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003980 Result += "\n";
3981 if (LangOpts.MicrosoftExt)
3982 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003983 Result += "extern \"C\" ";
Fangrui Song6907ce22018-07-30 19:24:48 +00003984 if (LangOpts.MicrosoftExt &&
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003985 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003986 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3987 Result += "__declspec(dllimport) ";
3988
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003989 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003990 if (IvarDecl->isBitField()) {
3991 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3992 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3993 }
3994 else
3995 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003996 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003997 }
3998}
3999
Fariborz Jahanian11671902012-02-07 17:11:38 +00004000//===----------------------------------------------------------------------===//
4001// Meta Data Emission
4002//===----------------------------------------------------------------------===//
4003
Fariborz Jahanian11671902012-02-07 17:11:38 +00004004/// RewriteImplementations - This routine rewrites all method implementations
4005/// and emits meta-data.
4006
4007void RewriteModernObjC::RewriteImplementations() {
4008 int ClsDefCount = ClassImplementation.size();
4009 int CatDefCount = CategoryImplementation.size();
4010
4011 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004012 for (int i = 0; i < ClsDefCount; i++) {
4013 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4014 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4015 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004016 assert(false &&
4017 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004018 RewriteImplementationDecl(OIMP);
4019 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004020
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004021 for (int i = 0; i < CatDefCount; i++) {
4022 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4023 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4024 if (CDecl->isImplicitInterfaceDecl())
4025 assert(false &&
4026 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004027 RewriteImplementationDecl(CIMP);
4028 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004029}
4030
Fangrui Song6907ce22018-07-30 19:24:48 +00004031void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004032 const std::string &Name,
4033 ValueDecl *VD, bool def) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004034 assert(BlockByRefDeclNo.count(VD) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004035 "RewriteByRefString: ByRef decl missing");
4036 if (def)
4037 ResultStr += "struct ";
Fangrui Song6907ce22018-07-30 19:24:48 +00004038 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004039 "_" + utostr(BlockByRefDeclNo[VD]) ;
4040}
4041
4042static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4043 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4044 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4045 return false;
4046}
4047
4048std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4049 StringRef funcName,
4050 std::string Tag) {
4051 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004052 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004053 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004054 SourceLocation BlockLoc = CE->getExprLoc();
4055 std::string S;
4056 ConvertSourceLocationToLineDirective(BlockLoc, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00004057
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004058 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4059 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004060
4061 BlockDecl *BD = CE->getBlockDecl();
4062
4063 if (isa<FunctionNoProtoType>(AFT)) {
4064 // No user-supplied arguments. Still need to pass in a pointer to the
4065 // block (to reference imported block decl refs).
4066 S += "(" + StructRef + " *__cself)";
4067 } else if (BD->param_empty()) {
4068 S += "(" + StructRef + " *__cself)";
4069 } else {
4070 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4071 assert(FT && "SynthesizeBlockFunc: No function proto");
4072 S += '(';
4073 // first add the implicit argument.
4074 S += StructRef + " *__cself, ";
4075 std::string ParamStr;
4076 for (BlockDecl::param_iterator AI = BD->param_begin(),
4077 E = BD->param_end(); AI != E; ++AI) {
4078 if (AI != BD->param_begin()) S += ", ";
4079 ParamStr = (*AI)->getNameAsString();
4080 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004081 (void)convertBlockPointerToFunctionPointer(QT);
4082 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004083 S += ParamStr;
4084 }
4085 if (FT->isVariadic()) {
4086 if (!BD->param_empty()) S += ", ";
4087 S += "...";
4088 }
4089 S += ')';
4090 }
4091 S += " {\n";
4092
4093 // Create local declarations to avoid rewriting all closure decl ref exprs.
4094 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004095 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004096 E = BlockByRefDecls.end(); I != E; ++I) {
4097 S += " ";
4098 std::string Name = (*I)->getNameAsString();
4099 std::string TypeString;
4100 RewriteByRefString(TypeString, Name, (*I));
4101 TypeString += " *";
4102 Name = TypeString + Name;
4103 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4104 }
4105 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004106 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004107 E = BlockByCopyDecls.end(); I != E; ++I) {
4108 S += " ";
4109 // Handle nested closure invocation. For example:
4110 //
4111 // void (^myImportedClosure)(void);
4112 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4113 //
4114 // void (^anotherClosure)(void);
4115 // anotherClosure = ^(void) {
4116 // myImportedClosure(); // import and invoke the closure
4117 // };
4118 //
4119 if (isTopLevelBlockPointerType((*I)->getType())) {
4120 RewriteBlockPointerTypeVariable(S, (*I));
4121 S += " = (";
4122 RewriteBlockPointerType(S, (*I)->getType());
4123 S += ")";
4124 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4125 }
4126 else {
4127 std::string Name = (*I)->getNameAsString();
4128 QualType QT = (*I)->getType();
4129 if (HasLocalVariableExternalStorage(*I))
4130 QT = Context->getPointerType(QT);
4131 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00004132 S += Name + " = __cself->" +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004133 (*I)->getNameAsString() + "; // bound by copy\n";
4134 }
4135 }
4136 std::string RewrittenStr = RewrittenBlockExprs[CE];
4137 const char *cstr = RewrittenStr.c_str();
4138 while (*cstr++ != '{') ;
4139 S += cstr;
4140 S += "\n";
4141 return S;
4142}
4143
4144std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4145 StringRef funcName,
4146 std::string Tag) {
4147 std::string StructRef = "struct " + Tag;
4148 std::string S = "static void __";
4149
4150 S += funcName;
4151 S += "_block_copy_" + utostr(i);
4152 S += "(" + StructRef;
4153 S += "*dst, " + StructRef;
4154 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004155 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004156 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004157 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004158 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004159 S += VD->getNameAsString();
4160 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004161 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4162 else if (VD->getType()->isBlockPointerType())
4163 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4164 else
4165 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4166 }
4167 S += "}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004168
Fariborz Jahanian11671902012-02-07 17:11:38 +00004169 S += "\nstatic void __";
4170 S += funcName;
4171 S += "_block_dispose_" + utostr(i);
4172 S += "(" + StructRef;
4173 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004174 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004175 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004176 S += VD->getNameAsString();
4177 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004178 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4179 else if (VD->getType()->isBlockPointerType())
4180 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4181 else
4182 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4183 }
4184 S += "}\n";
4185 return S;
4186}
4187
Fangrui Song6907ce22018-07-30 19:24:48 +00004188std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004189 std::string Desc) {
4190 std::string S = "\nstruct " + Tag;
4191 std::string Constructor = " " + Tag;
4192
4193 S += " {\n struct __block_impl impl;\n";
4194 S += " struct " + Desc;
4195 S += "* Desc;\n";
4196
4197 Constructor += "(void *fp, "; // Invoke function pointer.
4198 Constructor += "struct " + Desc; // Descriptor pointer.
4199 Constructor += " *desc";
4200
4201 if (BlockDeclRefs.size()) {
4202 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004203 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004204 E = BlockByCopyDecls.end(); I != E; ++I) {
4205 S += " ";
4206 std::string FieldName = (*I)->getNameAsString();
4207 std::string ArgName = "_" + FieldName;
4208 // Handle nested closure invocation. For example:
4209 //
4210 // void (^myImportedBlock)(void);
4211 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4212 //
4213 // void (^anotherBlock)(void);
4214 // anotherBlock = ^(void) {
4215 // myImportedBlock(); // import and invoke the closure
4216 // };
4217 //
4218 if (isTopLevelBlockPointerType((*I)->getType())) {
4219 S += "struct __block_impl *";
4220 Constructor += ", void *" + ArgName;
4221 } else {
4222 QualType QT = (*I)->getType();
4223 if (HasLocalVariableExternalStorage(*I))
4224 QT = Context->getPointerType(QT);
4225 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4226 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4227 Constructor += ", " + ArgName;
4228 }
4229 S += FieldName + ";\n";
4230 }
4231 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004232 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004233 E = BlockByRefDecls.end(); I != E; ++I) {
4234 S += " ";
4235 std::string FieldName = (*I)->getNameAsString();
4236 std::string ArgName = "_" + FieldName;
4237 {
4238 std::string TypeString;
4239 RewriteByRefString(TypeString, FieldName, (*I));
4240 TypeString += " *";
4241 FieldName = TypeString + FieldName;
4242 ArgName = TypeString + ArgName;
4243 Constructor += ", " + ArgName;
4244 }
4245 S += FieldName + "; // by ref\n";
4246 }
4247 // Finish writing the constructor.
4248 Constructor += ", int flags=0)";
4249 // Initialize all "by copy" arguments.
4250 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004251 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004252 E = BlockByCopyDecls.end(); I != E; ++I) {
4253 std::string Name = (*I)->getNameAsString();
4254 if (firsTime) {
4255 Constructor += " : ";
4256 firsTime = false;
4257 }
4258 else
4259 Constructor += ", ";
4260 if (isTopLevelBlockPointerType((*I)->getType()))
4261 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4262 else
4263 Constructor += Name + "(_" + Name + ")";
4264 }
4265 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004266 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004267 E = BlockByRefDecls.end(); I != E; ++I) {
4268 std::string Name = (*I)->getNameAsString();
4269 if (firsTime) {
4270 Constructor += " : ";
4271 firsTime = false;
4272 }
4273 else
4274 Constructor += ", ";
4275 Constructor += Name + "(_" + Name + "->__forwarding)";
4276 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004277
Fariborz Jahanian11671902012-02-07 17:11:38 +00004278 Constructor += " {\n";
4279 if (GlobalVarDecl)
4280 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4281 else
4282 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4283 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4284
4285 Constructor += " Desc = desc;\n";
4286 } else {
4287 // Finish writing the constructor.
4288 Constructor += ", int flags=0) {\n";
4289 if (GlobalVarDecl)
4290 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4291 else
4292 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4293 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4294 Constructor += " Desc = desc;\n";
4295 }
4296 Constructor += " ";
4297 Constructor += "}\n";
4298 S += Constructor;
4299 S += "};\n";
4300 return S;
4301}
4302
Fangrui Song6907ce22018-07-30 19:24:48 +00004303std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004304 std::string ImplTag, int i,
4305 StringRef FunName,
4306 unsigned hasCopy) {
4307 std::string S = "\nstatic struct " + DescTag;
Fangrui Song6907ce22018-07-30 19:24:48 +00004308
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004309 S += " {\n size_t reserved;\n";
4310 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004311 if (hasCopy) {
4312 S += " void (*copy)(struct ";
4313 S += ImplTag; S += "*, struct ";
4314 S += ImplTag; S += "*);\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004315
Fariborz Jahanian11671902012-02-07 17:11:38 +00004316 S += " void (*dispose)(struct ";
4317 S += ImplTag; S += "*);\n";
4318 }
4319 S += "} ";
4320
4321 S += DescTag + "_DATA = { 0, sizeof(struct ";
4322 S += ImplTag + ")";
4323 if (hasCopy) {
4324 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4325 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4326 }
4327 S += "};\n";
4328 return S;
4329}
4330
4331void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4332 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004333 bool RewriteSC = (GlobalVarDecl &&
4334 !Blocks.empty() &&
4335 GlobalVarDecl->getStorageClass() == SC_Static &&
4336 GlobalVarDecl->getType().getCVRQualifiers());
4337 if (RewriteSC) {
4338 std::string SC(" void __");
4339 SC += GlobalVarDecl->getNameAsString();
4340 SC += "() {}";
4341 InsertText(FunLocStart, SC);
4342 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004343
Fariborz Jahanian11671902012-02-07 17:11:38 +00004344 // Insert closures that were part of the function.
4345 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4346 CollectBlockDeclRefInfo(Blocks[i]);
4347 // Need to copy-in the inner copied-in variables not actually used in this
4348 // block.
4349 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004350 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004351 ValueDecl *VD = Exp->getDecl();
4352 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004353 if (!VD->hasAttr<BlocksAttr>()) {
4354 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4355 BlockByCopyDeclsPtrSet.insert(VD);
4356 BlockByCopyDecls.push_back(VD);
4357 }
4358 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004359 }
John McCall113bee02012-03-10 09:33:50 +00004360
4361 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004362 BlockByRefDeclsPtrSet.insert(VD);
4363 BlockByRefDecls.push_back(VD);
4364 }
John McCall113bee02012-03-10 09:33:50 +00004365
Fariborz Jahanian11671902012-02-07 17:11:38 +00004366 // imported objects in the inner blocks not used in the outer
4367 // blocks must be copied/disposed in the outer block as well.
Fangrui Song6907ce22018-07-30 19:24:48 +00004368 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004369 VD->getType()->isBlockPointerType())
4370 ImportedBlockDecls.insert(VD);
4371 }
4372
4373 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4374 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4375
4376 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4377
4378 InsertText(FunLocStart, CI);
4379
4380 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4381
4382 InsertText(FunLocStart, CF);
4383
4384 if (ImportedBlockDecls.size()) {
4385 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4386 InsertText(FunLocStart, HF);
4387 }
4388 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4389 ImportedBlockDecls.size() > 0);
4390 InsertText(FunLocStart, BD);
4391
4392 BlockDeclRefs.clear();
4393 BlockByRefDecls.clear();
4394 BlockByRefDeclsPtrSet.clear();
4395 BlockByCopyDecls.clear();
4396 BlockByCopyDeclsPtrSet.clear();
4397 ImportedBlockDecls.clear();
4398 }
4399 if (RewriteSC) {
4400 // Must insert any 'const/volatile/static here. Since it has been
4401 // removed as result of rewriting of block literals.
4402 std::string SC;
4403 if (GlobalVarDecl->getStorageClass() == SC_Static)
4404 SC = "static ";
4405 if (GlobalVarDecl->getType().isConstQualified())
4406 SC += "const ";
4407 if (GlobalVarDecl->getType().isVolatileQualified())
4408 SC += "volatile ";
4409 if (GlobalVarDecl->getType().isRestrictQualified())
4410 SC += "restrict ";
4411 InsertText(FunLocStart, SC);
4412 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004413 if (GlobalConstructionExp) {
4414 // extra fancy dance for global literal expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00004415
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004416 // Always the latest block expression on the block stack.
4417 std::string Tag = "__";
4418 Tag += FunName;
4419 Tag += "_block_impl_";
4420 Tag += utostr(Blocks.size()-1);
4421 std::string globalBuf = "static ";
4422 globalBuf += Tag; globalBuf += " ";
4423 std::string SStr;
Fangrui Song6907ce22018-07-30 19:24:48 +00004424
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004425 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004426 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4427 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004428 globalBuf += constructorExprBuf.str();
4429 globalBuf += ";\n";
4430 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004431 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004432 }
4433
Fariborz Jahanian11671902012-02-07 17:11:38 +00004434 Blocks.clear();
4435 InnerDeclRefsCount.clear();
4436 InnerDeclRefs.clear();
4437 RewrittenBlockExprs.clear();
4438}
4439
4440void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004441 SourceLocation FunLocStart =
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004442 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4443 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004444 StringRef FuncName = FD->getName();
4445
4446 SynthesizeBlockLiterals(FunLocStart, FuncName);
4447}
4448
4449static void BuildUniqueMethodName(std::string &Name,
4450 ObjCMethodDecl *MD) {
4451 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Benjamin Krameradcd0262020-01-28 20:23:46 +01004452 Name = std::string(IFace->getName());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004453 Name += "__" + MD->getSelector().getAsString();
4454 // Convert colons to underscores.
4455 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00004456 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004457 Name.replace(loc, 1, "_");
4458}
4459
4460void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004461 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4462 // SourceLocation FunLocStart = MD->getBeginLoc();
4463 SourceLocation FunLocStart = MD->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004464 std::string FuncName;
4465 BuildUniqueMethodName(FuncName, MD);
4466 SynthesizeBlockLiterals(FunLocStart, FuncName);
4467}
4468
4469void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004470 for (Stmt *SubStmt : S->children())
4471 if (SubStmt) {
4472 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004473 GetBlockDeclRefExprs(CBE->getBody());
4474 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004475 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004476 }
4477 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004478 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004479 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004480 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004481 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004482 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004483}
4484
Craig Topper5603df42013-07-05 19:34:19 +00004485void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4486 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004487 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004488 for (Stmt *SubStmt : S->children())
4489 if (SubStmt) {
4490 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004491 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4492 GetInnerBlockDeclRefExprs(CBE->getBody(),
4493 InnerBlockDeclRefs,
4494 InnerContexts);
4495 }
4496 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004497 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004498 }
4499 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004500 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004501 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004502 HasLocalVariableExternalStorage(DRE->getDecl())) {
4503 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004504 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004505 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004506 if (Var->isFunctionOrMethodVarDecl())
4507 ImportedLocalExternalDecls.insert(Var);
4508 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004509 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004510}
4511
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004512/// convertObjCTypeToCStyleType - This routine converts such objc types
4513/// as qualified objects, and blocks to their closest c/c++ types that
4514/// it can. It returns true if input type was modified.
4515bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4516 QualType oldT = T;
4517 convertBlockPointerToFunctionPointer(T);
4518 if (T->isFunctionPointerType()) {
4519 QualType PointeeTy;
4520 if (const PointerType* PT = T->getAs<PointerType>()) {
4521 PointeeTy = PT->getPointeeType();
4522 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4523 T = convertFunctionTypeOfBlocks(FT);
4524 T = Context->getPointerType(T);
4525 }
4526 }
4527 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004528
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004529 convertToUnqualifiedObjCType(T);
4530 return T != oldT;
4531}
4532
Fariborz Jahanian11671902012-02-07 17:11:38 +00004533/// convertFunctionTypeOfBlocks - This routine converts a function type
4534/// whose result type may be a block pointer or whose argument type(s)
4535/// might be block pointers to an equivalent function type replacing
4536/// all block pointers to function pointers.
4537QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4538 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4539 // FTP will be null for closures that don't take arguments.
4540 // Generate a funky cast.
4541 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004542 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004543 bool modified = convertObjCTypeToCStyleType(Res);
Fangrui Song6907ce22018-07-30 19:24:48 +00004544
Fariborz Jahanian11671902012-02-07 17:11:38 +00004545 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004546 for (auto &I : FTP->param_types()) {
4547 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004548 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004549 if (convertObjCTypeToCStyleType(t))
4550 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004551 ArgTypes.push_back(t);
4552 }
4553 }
4554 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004555 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004556 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004557 else FuncType = QualType(FT, 0);
4558 return FuncType;
4559}
4560
4561Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4562 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004563 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004564
4565 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4566 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004567 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4568 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004569 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004570 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4571 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4572 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004573 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004574 CPT = IEXPR->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004575 else if (const ConditionalOperator *CEXPR =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004576 dyn_cast<ConditionalOperator>(BlockExp)) {
4577 Expr *LHSExp = CEXPR->getLHS();
4578 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4579 Expr *RHSExp = CEXPR->getRHS();
4580 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4581 Expr *CONDExp = CEXPR->getCond();
4582 ConditionalOperator *CondExpr =
4583 new (Context) ConditionalOperator(CONDExp,
4584 SourceLocation(), cast<Expr>(LHSStmt),
4585 SourceLocation(), cast<Expr>(RHSStmt),
4586 Exp->getType(), VK_RValue, OK_Ordinary);
4587 return CondExpr;
4588 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4589 CPT = IRE->getType()->getAs<BlockPointerType>();
4590 } else if (const PseudoObjectExpr *POE
4591 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4592 CPT = POE->getType()->castAs<BlockPointerType>();
4593 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004594 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004595 }
4596 assert(CPT && "RewriteBlockClass: Bad type");
4597 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4598 assert(FT && "RewriteBlockClass: Bad type");
4599 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4600 // FTP will be null for closures that don't take arguments.
4601
4602 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4603 SourceLocation(), SourceLocation(),
4604 &Context->Idents.get("__block_impl"));
4605 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4606
4607 // Generate a funky cast.
4608 SmallVector<QualType, 8> ArgTypes;
4609
4610 // Push the block argument type.
4611 ArgTypes.push_back(PtrBlock);
4612 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004613 for (auto &I : FTP->param_types()) {
4614 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004615 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4616 if (!convertBlockPointerToFunctionPointer(t))
4617 convertToUnqualifiedObjCType(t);
4618 ArgTypes.push_back(t);
4619 }
4620 }
4621 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004622 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004623
4624 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4625
4626 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4627 CK_BitCast,
4628 const_cast<Expr*>(BlockExp));
4629 // Don't forget the parens to enforce the proper binding.
4630 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4631 BlkCast);
4632 //PE->dump();
4633
Craig Topper8ae12032014-05-07 06:21:57 +00004634 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004635 SourceLocation(),
4636 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004637 Context->VoidPtrTy, nullptr,
4638 /*BitWidth=*/nullptr, /*Mutable=*/true,
4639 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004640 MemberExpr *ME = MemberExpr::CreateImplicit(
4641 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004642
4643 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4644 CK_BitCast, ME);
4645 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004646
4647 SmallVector<Expr*, 8> BlkExprs;
4648 // Add the implicit argument.
4649 BlkExprs.push_back(BlkCast);
4650 // Add the user arguments.
4651 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4652 E = Exp->arg_end(); I != E; ++I) {
4653 BlkExprs.push_back(*I);
4654 }
Serge Pavlov70e7aa42020-07-24 12:04:19 +07004655 CallExpr *CE =
4656 CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_RValue,
4657 SourceLocation(), FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004658 return CE;
4659}
4660
4661// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004662// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004663// For example:
4664//
4665// int main() {
4666// __block Foo *f;
4667// __block int i;
4668//
4669// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004670// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004671// i = 77;
4672// };
4673//}
John McCall113bee02012-03-10 09:33:50 +00004674Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004675 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanian11671902012-02-07 17:11:38 +00004676 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004677 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004678 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004679 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004680
4681 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004682 SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004683 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004684 Context->VoidPtrTy, nullptr,
4685 /*BitWidth=*/nullptr, /*Mutable=*/true,
4686 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004687 MemberExpr *ME = MemberExpr::CreateImplicit(
4688 *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004689
4690 StringRef Name = VD->getName();
4691 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004692 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004693 Context->VoidPtrTy, nullptr,
4694 /*BitWidth=*/nullptr, /*Mutable=*/true,
4695 ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00004696 ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4697 VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004698
4699 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004700 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4701 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004702 ME);
4703 ReplaceStmt(DeclRefExp, PE);
4704 return PE;
4705}
4706
Fangrui Song6907ce22018-07-30 19:24:48 +00004707// Rewrites the imported local variable V with external storage
Fariborz Jahanian11671902012-02-07 17:11:38 +00004708// (static, extern, etc.) as *V
4709//
4710Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4711 ValueDecl *VD = DRE->getDecl();
4712 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4713 if (!ImportedLocalExternalDecls.count(Var))
4714 return DRE;
Melanie Blowerf4aaed32020-06-26 09:23:45 -07004715 Expr *Exp = UnaryOperator::Create(
4716 const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
4717 VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004718 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004719 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004720 Exp);
4721 ReplaceStmt(DRE, PE);
4722 return PE;
4723}
4724
4725void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4726 SourceLocation LocStart = CE->getLParenLoc();
4727 SourceLocation LocEnd = CE->getRParenLoc();
4728
4729 // Need to avoid trying to rewrite synthesized casts.
4730 if (LocStart.isInvalid())
4731 return;
4732 // Need to avoid trying to rewrite casts contained in macros.
4733 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4734 return;
4735
4736 const char *startBuf = SM->getCharacterData(LocStart);
4737 const char *endBuf = SM->getCharacterData(LocEnd);
4738 QualType QT = CE->getType();
4739 const Type* TypePtr = QT->getAs<Type>();
4740 if (isa<TypeOfExprType>(TypePtr)) {
4741 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4742 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4743 std::string TypeAsString = "(";
4744 RewriteBlockPointerType(TypeAsString, QT);
4745 TypeAsString += ")";
4746 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4747 return;
4748 }
4749 // advance the location to startArgList.
4750 const char *argPtr = startBuf;
4751
4752 while (*argPtr++ && (argPtr < endBuf)) {
4753 switch (*argPtr) {
4754 case '^':
4755 // Replace the '^' with '*'.
4756 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4757 ReplaceText(LocStart, 1, "*");
4758 break;
4759 }
4760 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004761}
4762
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004763void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4764 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004765 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4766 CastKind != CK_AnyPointerToBlockPointerCast)
4767 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004768
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004769 QualType QT = IC->getType();
4770 (void)convertBlockPointerToFunctionPointer(QT);
4771 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4772 std::string Str = "(";
4773 Str += TypeString;
4774 Str += ")";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004775 InsertText(IC->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004776}
4777
Fariborz Jahanian11671902012-02-07 17:11:38 +00004778void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4779 SourceLocation DeclLoc = FD->getLocation();
4780 unsigned parenCount = 0;
4781
4782 // We have 1 or more arguments that have closure pointers.
4783 const char *startBuf = SM->getCharacterData(DeclLoc);
4784 const char *startArgList = strchr(startBuf, '(');
4785
4786 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4787
4788 parenCount++;
4789 // advance the location to startArgList.
4790 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4791 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4792
4793 const char *argPtr = startArgList;
4794
4795 while (*argPtr++ && parenCount) {
4796 switch (*argPtr) {
4797 case '^':
4798 // Replace the '^' with '*'.
4799 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4800 ReplaceText(DeclLoc, 1, "*");
4801 break;
4802 case '(':
4803 parenCount++;
4804 break;
4805 case ')':
4806 parenCount--;
4807 break;
4808 }
4809 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004810}
4811
4812bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4813 const FunctionProtoType *FTP;
4814 const PointerType *PT = QT->getAs<PointerType>();
4815 if (PT) {
4816 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4817 } else {
4818 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4819 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4820 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4821 }
4822 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004823 for (const auto &I : FTP->param_types())
4824 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004825 return true;
4826 }
4827 return false;
4828}
4829
4830bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4831 const FunctionProtoType *FTP;
4832 const PointerType *PT = QT->getAs<PointerType>();
4833 if (PT) {
4834 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4835 } else {
4836 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4837 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4838 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4839 }
4840 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004841 for (const auto &I : FTP->param_types()) {
4842 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004843 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004844 if (I->isObjCObjectPointerType() &&
4845 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004846 return true;
4847 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004848
Fariborz Jahanian11671902012-02-07 17:11:38 +00004849 }
4850 return false;
4851}
4852
4853void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4854 const char *&RParen) {
4855 const char *argPtr = strchr(Name, '(');
4856 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4857
4858 LParen = argPtr; // output the start.
4859 argPtr++; // skip past the left paren.
4860 unsigned parenCount = 1;
4861
4862 while (*argPtr && parenCount) {
4863 switch (*argPtr) {
4864 case '(': parenCount++; break;
4865 case ')': parenCount--; break;
4866 default: break;
4867 }
4868 if (parenCount) argPtr++;
4869 }
4870 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4871 RParen = argPtr; // output the end
4872}
4873
4874void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4875 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4876 RewriteBlockPointerFunctionArgs(FD);
4877 return;
4878 }
4879 // Handle Variables and Typedefs.
4880 SourceLocation DeclLoc = ND->getLocation();
4881 QualType DeclT;
4882 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4883 DeclT = VD->getType();
4884 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4885 DeclT = TDD->getUnderlyingType();
4886 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4887 DeclT = FD->getType();
4888 else
4889 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4890
4891 const char *startBuf = SM->getCharacterData(DeclLoc);
4892 const char *endBuf = startBuf;
4893 // scan backward (from the decl location) for the end of the previous decl.
4894 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4895 startBuf--;
4896 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4897 std::string buf;
4898 unsigned OrigLength=0;
4899 // *startBuf != '^' if we are dealing with a pointer to function that
4900 // may take block argument types (which will be handled below).
4901 if (*startBuf == '^') {
4902 // Replace the '^' with '*', computing a negative offset.
4903 buf = '*';
4904 startBuf++;
4905 OrigLength++;
4906 }
4907 while (*startBuf != ')') {
4908 buf += *startBuf;
4909 startBuf++;
4910 OrigLength++;
4911 }
4912 buf += ')';
4913 OrigLength++;
Fangrui Song6907ce22018-07-30 19:24:48 +00004914
Fariborz Jahanian11671902012-02-07 17:11:38 +00004915 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4916 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4917 // Replace the '^' with '*' for arguments.
4918 // Replace id<P> with id/*<>*/
4919 DeclLoc = ND->getLocation();
4920 startBuf = SM->getCharacterData(DeclLoc);
4921 const char *argListBegin, *argListEnd;
4922 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4923 while (argListBegin < argListEnd) {
4924 if (*argListBegin == '^')
4925 buf += '*';
4926 else if (*argListBegin == '<') {
Fangrui Song6907ce22018-07-30 19:24:48 +00004927 buf += "/*";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004928 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004929 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004930 while (*argListBegin != '>') {
4931 buf += *argListBegin++;
4932 OrigLength++;
4933 }
4934 buf += *argListBegin;
4935 buf += "*/";
4936 }
4937 else
4938 buf += *argListBegin;
4939 argListBegin++;
4940 OrigLength++;
4941 }
4942 buf += ')';
4943 OrigLength++;
4944 }
4945 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004946}
4947
Fariborz Jahanian11671902012-02-07 17:11:38 +00004948/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4949/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4950/// struct Block_byref_id_object *src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004951/// _Block_object_assign (&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004952/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4953/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004954/// _Block_object_assign(&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004955/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4956/// [|BLOCK_FIELD_IS_WEAK]) // block
4957/// }
4958/// And:
4959/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004960/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004961/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4962/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004963/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004964/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4965/// [|BLOCK_FIELD_IS_WEAK]) // block
4966/// }
4967
4968std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4969 int flag) {
4970 std::string S;
4971 if (CopyDestroyCache.count(flag))
4972 return S;
4973 CopyDestroyCache.insert(flag);
4974 S = "static void __Block_byref_id_object_copy_";
4975 S += utostr(flag);
4976 S += "(void *dst, void *src) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004977
Fariborz Jahanian11671902012-02-07 17:11:38 +00004978 // offset into the object pointer is computed as:
4979 // void * + void* + int + int + void* + void *
Fangrui Song6907ce22018-07-30 19:24:48 +00004980 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004981 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004982 unsigned VoidPtrSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004983 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004984
Fariborz Jahanian11671902012-02-07 17:11:38 +00004985 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4986 S += " _Block_object_assign((char*)dst + ";
4987 S += utostr(offset);
4988 S += ", *(void * *) ((char*)src + ";
4989 S += utostr(offset);
4990 S += "), ";
4991 S += utostr(flag);
4992 S += ");\n}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004993
Fariborz Jahanian11671902012-02-07 17:11:38 +00004994 S += "static void __Block_byref_id_object_dispose_";
4995 S += utostr(flag);
4996 S += "(void *src) {\n";
4997 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4998 S += utostr(offset);
4999 S += "), ";
5000 S += utostr(flag);
5001 S += ");\n}\n";
5002 return S;
5003}
5004
5005/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5006/// the declaration into:
5007/// struct __Block_byref_ND {
5008/// void *__isa; // NULL for everything except __weak pointers
5009/// struct __Block_byref_ND *__forwarding;
5010/// int32_t __flags;
5011/// int32_t __size;
5012/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5013/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5014/// typex ND;
5015/// };
5016///
5017/// It then replaces declaration of ND variable with:
Fangrui Song6907ce22018-07-30 19:24:48 +00005018/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5019/// __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005020/// ND=initializer-if-any};
5021///
5022///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005023void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5024 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005025 int flag = 0;
5026 int isa = 0;
5027 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5028 if (DeclLoc.isInvalid())
5029 // If type location is missing, it is because of missing type (a warning).
5030 // Use variable's location which is good for this case.
5031 DeclLoc = ND->getLocation();
5032 const char *startBuf = SM->getCharacterData(DeclLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005033 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005034 X = SM->getExpansionLoc(X);
5035 const char *endBuf = SM->getCharacterData(X);
5036 std::string Name(ND->getNameAsString());
5037 std::string ByrefType;
5038 RewriteByRefString(ByrefType, Name, ND, true);
5039 ByrefType += " {\n";
5040 ByrefType += " void *__isa;\n";
5041 RewriteByRefString(ByrefType, Name, ND);
5042 ByrefType += " *__forwarding;\n";
5043 ByrefType += " int __flags;\n";
5044 ByrefType += " int __size;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005045 // Add void *__Block_byref_id_object_copy;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005046 // void *__Block_byref_id_object_dispose; if needed.
5047 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005048 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005049 if (HasCopyAndDispose) {
5050 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5051 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5052 }
5053
5054 QualType T = Ty;
5055 (void)convertBlockPointerToFunctionPointer(T);
5056 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00005057
Fariborz Jahanian11671902012-02-07 17:11:38 +00005058 ByrefType += " " + Name + ";\n";
5059 ByrefType += "};\n";
5060 // Insert this type in global scope. It is needed by helper function.
5061 SourceLocation FunLocStart;
5062 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005063 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005064 else {
5065 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005066 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005067 }
5068 InsertText(FunLocStart, ByrefType);
Fangrui Song6907ce22018-07-30 19:24:48 +00005069
Fariborz Jahanian11671902012-02-07 17:11:38 +00005070 if (Ty.isObjCGCWeak()) {
5071 flag |= BLOCK_FIELD_IS_WEAK;
5072 isa = 1;
5073 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005074 if (HasCopyAndDispose) {
5075 flag = BLOCK_BYREF_CALLER;
5076 QualType Ty = ND->getType();
5077 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5078 if (Ty->isBlockPointerType())
5079 flag |= BLOCK_FIELD_IS_BLOCK;
5080 else
5081 flag |= BLOCK_FIELD_IS_OBJECT;
5082 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5083 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005084 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005085 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005086
5087 // struct __Block_byref_ND ND =
5088 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005089 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005090 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005091 // FIXME. rewriter does not support __block c++ objects which
5092 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005093 if (hasInit)
5094 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5095 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5096 if (CXXDecl && CXXDecl->isDefaultConstructor())
5097 hasInit = false;
5098 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005099
Fariborz Jahanian11671902012-02-07 17:11:38 +00005100 unsigned flags = 0;
5101 if (HasCopyAndDispose)
5102 flags |= BLOCK_HAS_COPY_DISPOSE;
5103 Name = ND->getNameAsString();
5104 ByrefType.clear();
5105 RewriteByRefString(ByrefType, Name, ND);
5106 std::string ForwardingCastType("(");
5107 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005108 ByrefType += " " + Name + " = {(void*)";
5109 ByrefType += utostr(isa);
5110 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5111 ByrefType += utostr(flags);
5112 ByrefType += ", ";
5113 ByrefType += "sizeof(";
5114 RewriteByRefString(ByrefType, Name, ND);
5115 ByrefType += ")";
5116 if (HasCopyAndDispose) {
5117 ByrefType += ", __Block_byref_id_object_copy_";
5118 ByrefType += utostr(flag);
5119 ByrefType += ", __Block_byref_id_object_dispose_";
5120 ByrefType += utostr(flag);
5121 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005122
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005123 if (!firstDecl) {
5124 // In multiple __block declarations, and for all but 1st declaration,
5125 // find location of the separating comma. This would be start location
5126 // where new text is to be inserted.
5127 DeclLoc = ND->getLocation();
5128 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5129 const char *commaBuf = startDeclBuf;
5130 while (*commaBuf != ',')
5131 commaBuf--;
5132 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5133 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5134 startBuf = commaBuf;
5135 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005136
Fariborz Jahanian11671902012-02-07 17:11:38 +00005137 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005138 ByrefType += "};\n";
5139 unsigned nameSize = Name.size();
Simon Pilgrim2c518802017-03-30 14:13:19 +00005140 // for block or function pointer declaration. Name is already
Fariborz Jahanian11671902012-02-07 17:11:38 +00005141 // part of the declaration.
5142 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5143 nameSize = 1;
5144 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5145 }
5146 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005147 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005148 SourceLocation startLoc;
5149 Expr *E = ND->getInit();
5150 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5151 startLoc = ECE->getLParenLoc();
5152 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005153 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005154 startLoc = SM->getExpansionLoc(startLoc);
5155 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005156 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005157
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005158 const char separator = lastDecl ? ';' : ',';
5159 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5160 const char *separatorBuf = strchr(startInitializerBuf, separator);
Fangrui Song6907ce22018-07-30 19:24:48 +00005161 assert((*separatorBuf == separator) &&
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005162 "RewriteByRefVar: can't find ';' or ','");
5163 SourceLocation separatorLoc =
5164 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00005165
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005166 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005167 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005168}
5169
5170void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5171 // Add initializers for any closure decl refs.
5172 GetBlockDeclRefExprs(Exp->getBody());
5173 if (BlockDeclRefs.size()) {
5174 // Unique all "by copy" declarations.
5175 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005176 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005177 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5178 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5179 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5180 }
5181 }
5182 // Unique all "by ref" declarations.
5183 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005184 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005185 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5186 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5187 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5188 }
5189 }
5190 // Find any imported blocks...they will need special attention.
5191 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005192 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005193 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005194 BlockDeclRefs[i]->getType()->isBlockPointerType())
5195 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5196 }
5197}
5198
5199FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5200 IdentifierInfo *ID = &Context->Idents.get(name);
5201 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5202 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005203 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005204 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005205}
5206
5207Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005208 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005209 const BlockDecl *block = Exp->getBlockDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00005210
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211 Blocks.push_back(Exp);
5212
5213 CollectBlockDeclRefInfo(Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00005214
Fariborz Jahanian11671902012-02-07 17:11:38 +00005215 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005216 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005217 if (!InnerBlockDeclRefs.empty()) {
5218 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005219 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005220 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005221 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005222 // We need to save the copied-in variables in nested
5223 // blocks because it is needed at the end for some of the API generations.
5224 // See SynthesizeBlockLiterals routine.
5225 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5226 BlockDeclRefs.push_back(Exp);
5227 BlockByCopyDeclsPtrSet.insert(VD);
5228 BlockByCopyDecls.push_back(VD);
5229 }
John McCall113bee02012-03-10 09:33:50 +00005230 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005231 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5232 BlockDeclRefs.push_back(Exp);
5233 BlockByRefDeclsPtrSet.insert(VD);
5234 BlockByRefDecls.push_back(VD);
5235 }
5236 }
5237 // Find any imported blocks...they will need special attention.
5238 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005239 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005240 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005241 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5242 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5243 }
5244 InnerDeclRefsCount.push_back(countOfInnerDecls);
Fangrui Song6907ce22018-07-30 19:24:48 +00005245
Fariborz Jahanian11671902012-02-07 17:11:38 +00005246 std::string FuncName;
5247
5248 if (CurFunctionDef)
5249 FuncName = CurFunctionDef->getNameAsString();
5250 else if (CurMethodDef)
5251 BuildUniqueMethodName(FuncName, CurMethodDef);
5252 else if (GlobalVarDecl)
5253 FuncName = std::string(GlobalVarDecl->getNameAsString());
5254
Fangrui Song6907ce22018-07-30 19:24:48 +00005255 bool GlobalBlockExpr =
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005256 block->getDeclContext()->getRedeclContext()->isFileContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005257
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005258 if (GlobalBlockExpr && !GlobalVarDecl) {
5259 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5260 GlobalBlockExpr = false;
5261 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005262
Fariborz Jahanian11671902012-02-07 17:11:38 +00005263 std::string BlockNumber = utostr(Blocks.size()-1);
5264
Fariborz Jahanian11671902012-02-07 17:11:38 +00005265 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5266
5267 // Get a pointer to the function type so we can cast appropriately.
5268 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5269 QualType FType = Context->getPointerType(BFT);
5270
5271 FunctionDecl *FD;
5272 Expr *NewRep;
5273
Benjamin Kramer60509af2013-09-09 14:48:42 +00005274 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005275 std::string Tag;
Fangrui Song6907ce22018-07-30 19:24:48 +00005276
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005277 if (GlobalBlockExpr)
5278 Tag = "__global_";
5279 else
5280 Tag = "__";
5281 Tag += FuncName + "_block_impl_" + BlockNumber;
Fangrui Song6907ce22018-07-30 19:24:48 +00005282
Fariborz Jahanian11671902012-02-07 17:11:38 +00005283 FD = SynthBlockInitFunctionDecl(Tag);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005284 DeclRefExpr *DRE = new (Context)
5285 DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005286
5287 SmallVector<Expr*, 4> InitExprs;
5288
5289 // Initialize the block function.
5290 FD = SynthBlockInitFunctionDecl(Func);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005291 DeclRefExpr *Arg = new (Context) DeclRefExpr(
5292 *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005293 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5294 CK_BitCast, Arg);
5295 InitExprs.push_back(castExpr);
5296
5297 // Initialize the block descriptor.
5298 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5299
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005300 VarDecl *NewVD = VarDecl::Create(
5301 *Context, TUDecl, SourceLocation(), SourceLocation(),
5302 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
Melanie Blowerf5360d42020-05-01 10:32:06 -07005303 UnaryOperator *DescRefExpr = UnaryOperator::Create(
5304 const_cast<ASTContext &>(*Context),
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005305 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5306 VK_LValue, SourceLocation()),
5307 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07005308 OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00005309 InitExprs.push_back(DescRefExpr);
5310
Fariborz Jahanian11671902012-02-07 17:11:38 +00005311 // Add initializers for any closure decl refs.
5312 if (BlockDeclRefs.size()) {
5313 Expr *Exp;
5314 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005315 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005316 E = BlockByCopyDecls.end(); I != E; ++I) {
5317 if (isObjCType((*I)->getType())) {
5318 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5319 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005320 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005321 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005322 if (HasLocalVariableExternalStorage(*I)) {
5323 QualType QT = (*I)->getType();
5324 QT = Context->getPointerType(QT);
Melanie Blowerf4aaed32020-06-26 09:23:45 -07005325 Exp = UnaryOperator::Create(
5326 const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
5327 OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005328 }
5329 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5330 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005331 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005332 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005333 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5334 CK_BitCast, Arg);
5335 } else {
5336 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005337 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005338 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005339 if (HasLocalVariableExternalStorage(*I)) {
5340 QualType QT = (*I)->getType();
5341 QT = Context->getPointerType(QT);
Melanie Blowerf4aaed32020-06-26 09:23:45 -07005342 Exp = UnaryOperator::Create(
5343 const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
5344 OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005345 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005346
Fariborz Jahanian11671902012-02-07 17:11:38 +00005347 }
5348 InitExprs.push_back(Exp);
5349 }
5350 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005351 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005352 E = BlockByRefDecls.end(); I != E; ++I) {
5353 ValueDecl *ND = (*I);
5354 std::string Name(ND->getNameAsString());
5355 std::string RecName;
5356 RewriteByRefString(RecName, Name, ND, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005357 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
Fariborz Jahanian11671902012-02-07 17:11:38 +00005358 + sizeof("struct"));
5359 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5360 SourceLocation(), SourceLocation(),
5361 II);
5362 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5363 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00005364
Fariborz Jahanian11671902012-02-07 17:11:38 +00005365 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005366 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5367 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005368 bool isNestedCapturedVar = false;
5369 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005370 for (const auto &CI : block->captures()) {
5371 const VarDecl *variable = CI.getVariable();
5372 if (variable == ND && CI.isNested()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005373 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005374 "SynthBlockInitExpr - captured block variable is not byref");
5375 isNestedCapturedVar = true;
5376 break;
5377 }
5378 }
5379 // captured nested byref variable has its address passed. Do not take
5380 // its address again.
5381 if (!isNestedCapturedVar)
Melanie Blowerf5360d42020-05-01 10:32:06 -07005382 Exp = UnaryOperator::Create(
5383 const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
5384 Context->getPointerType(Exp->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07005385 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5387 InitExprs.push_back(Exp);
5388 }
5389 }
5390 if (ImportedBlockDecls.size()) {
5391 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5392 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Fangrui Song6907ce22018-07-30 19:24:48 +00005393 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005394 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00005395 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005396 Context->IntTy, SourceLocation());
5397 InitExprs.push_back(FlagExp);
5398 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00005399 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
Serge Pavlov70e7aa42020-07-24 12:04:19 +07005400 SourceLocation(), FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00005401
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005402 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005403 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005404 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5405 GlobalConstructionExp = NewRep;
5406 NewRep = DRE;
5407 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005408
Melanie Blowerf5360d42020-05-01 10:32:06 -07005409 NewRep = UnaryOperator::Create(
5410 const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
5411 Context->getPointerType(NewRep->getType()), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07005412 SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005413 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5414 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005415 // Put Paren around the call.
5416 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5417 NewRep);
Fangrui Song6907ce22018-07-30 19:24:48 +00005418
Fariborz Jahanian11671902012-02-07 17:11:38 +00005419 BlockDeclRefs.clear();
5420 BlockByRefDecls.clear();
5421 BlockByRefDeclsPtrSet.clear();
5422 BlockByCopyDecls.clear();
5423 BlockByCopyDeclsPtrSet.clear();
5424 ImportedBlockDecls.clear();
5425 return NewRep;
5426}
5427
5428bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005429 if (const ObjCForCollectionStmt * CS =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005430 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5431 return CS->getElement() == DS;
5432 return false;
5433}
5434
5435//===----------------------------------------------------------------------===//
5436// Function Body / Expression rewriting
5437//===----------------------------------------------------------------------===//
5438
5439Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5440 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5441 isa<DoStmt>(S) || isa<ForStmt>(S))
5442 Stmts.push_back(S);
5443 else if (isa<ObjCForCollectionStmt>(S)) {
5444 Stmts.push_back(S);
5445 ObjCBcLabelNo.push_back(++BcLabelCount);
5446 }
5447
5448 // Pseudo-object operations and ivar references need special
5449 // treatment because we're going to recursively rewrite them.
5450 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5451 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5452 return RewritePropertyOrImplicitSetter(PseudoOp);
5453 } else {
5454 return RewritePropertyOrImplicitGetter(PseudoOp);
5455 }
5456 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5457 return RewriteObjCIvarRefExpr(IvarRefExpr);
5458 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005459 else if (isa<OpaqueValueExpr>(S))
5460 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005461
5462 SourceRange OrigStmtRange = S->getSourceRange();
5463
5464 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005465 for (Stmt *&childStmt : S->children())
5466 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005467 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5468 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005469 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005470 }
5471 }
5472
5473 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005474 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005475 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5476 InnerContexts.insert(BE->getBlockDecl());
5477 ImportedLocalExternalDecls.clear();
5478 GetInnerBlockDeclRefExprs(BE->getBody(),
5479 InnerBlockDeclRefs, InnerContexts);
5480 // Rewrite the block body in place.
5481 Stmt *SaveCurrentBody = CurrentBody;
5482 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005483 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005484 // block literal on rhs of a property-dot-sytax assignment
5485 // must be replaced by its synthesize ast so getRewrittenText
5486 // works as expected. In this case, what actually ends up on RHS
5487 // is the blockTranscribed which is the helper function for the
5488 // block literal; as in: self.c = ^() {[ace ARR];};
5489 bool saveDisableReplaceStmt = DisableReplaceStmt;
5490 DisableReplaceStmt = false;
5491 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5492 DisableReplaceStmt = saveDisableReplaceStmt;
5493 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005494 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005495 ImportedLocalExternalDecls.clear();
5496 // Now we snarf the rewritten text and stash it away for later use.
5497 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5498 RewrittenBlockExprs[BE] = Str;
5499
5500 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
Fangrui Song6907ce22018-07-30 19:24:48 +00005501
Fariborz Jahanian11671902012-02-07 17:11:38 +00005502 //blockTranscribed->dump();
5503 ReplaceStmt(S, blockTranscribed);
5504 return blockTranscribed;
5505 }
5506 // Handle specific things.
5507 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5508 return RewriteAtEncode(AtEncode);
5509
5510 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5511 return RewriteAtSelector(AtSelector);
5512
5513 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5514 return RewriteObjCStringLiteral(AtString);
Fangrui Song6907ce22018-07-30 19:24:48 +00005515
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005516 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5517 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005518
Patrick Beard0caa3942012-04-19 00:25:12 +00005519 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5520 return RewriteObjCBoxedExpr(BoxedExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005521
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005522 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5523 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005524
5525 if (ObjCDictionaryLiteral *DictionaryLitExpr =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005526 dyn_cast<ObjCDictionaryLiteral>(S))
5527 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005528
5529 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5530#if 0
5531 // Before we rewrite it, put the original message expression in a comment.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005532 SourceLocation startLoc = MessExpr->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005533 SourceLocation endLoc = MessExpr->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005534
5535 const char *startBuf = SM->getCharacterData(startLoc);
5536 const char *endBuf = SM->getCharacterData(endLoc);
5537
5538 std::string messString;
5539 messString += "// ";
5540 messString.append(startBuf, endBuf-startBuf+1);
5541 messString += "\n";
5542
5543 // FIXME: Missing definition of
5544 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005545 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005546 // Tried this, but it didn't work either...
5547 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5548#endif
5549 return RewriteMessageExpr(MessExpr);
5550 }
5551
Fangrui Song6907ce22018-07-30 19:24:48 +00005552 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005553 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5554 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5555 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005556
Fariborz Jahanian11671902012-02-07 17:11:38 +00005557 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5558 return RewriteObjCTryStmt(StmtTry);
5559
5560 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5561 return RewriteObjCSynchronizedStmt(StmtTry);
5562
5563 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5564 return RewriteObjCThrowStmt(StmtThrow);
5565
5566 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5567 return RewriteObjCProtocolExpr(ProtocolExp);
5568
5569 if (ObjCForCollectionStmt *StmtForCollection =
5570 dyn_cast<ObjCForCollectionStmt>(S))
5571 return RewriteObjCForCollectionStmt(StmtForCollection,
5572 OrigStmtRange.getEnd());
5573 if (BreakStmt *StmtBreakStmt =
5574 dyn_cast<BreakStmt>(S))
5575 return RewriteBreakStmt(StmtBreakStmt);
5576 if (ContinueStmt *StmtContinueStmt =
5577 dyn_cast<ContinueStmt>(S))
5578 return RewriteContinueStmt(StmtContinueStmt);
5579
5580 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5581 // and cast exprs.
5582 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5583 // FIXME: What we're doing here is modifying the type-specifier that
5584 // precedes the first Decl. In the future the DeclGroup should have
5585 // a separate type-specifier that we can rewrite.
5586 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5587 // the context of an ObjCForCollectionStmt. For example:
5588 // NSArray *someArray;
5589 // for (id <FooProtocol> index in someArray) ;
Fangrui Song6907ce22018-07-30 19:24:48 +00005590 // This is because RewriteObjCForCollectionStmt() does textual rewriting
Fariborz Jahanian11671902012-02-07 17:11:38 +00005591 // and it depends on the original text locations/positions.
5592 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5593 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5594
5595 // Blocks rewrite rules.
5596 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5597 DI != DE; ++DI) {
5598 Decl *SD = *DI;
5599 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5600 if (isTopLevelBlockPointerType(ND->getType()))
5601 RewriteBlockPointerDecl(ND);
5602 else if (ND->getType()->isFunctionPointerType())
5603 CheckFunctionPointerDecl(ND->getType(), ND);
5604 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5605 if (VD->hasAttr<BlocksAttr>()) {
5606 static unsigned uniqueByrefDeclCount = 0;
5607 assert(!BlockByRefDeclNo.count(ND) &&
5608 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5609 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005610 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005611 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005612 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005613 RewriteTypeOfDecl(VD);
5614 }
5615 }
5616 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5617 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5618 RewriteBlockPointerDecl(TD);
5619 else if (TD->getUnderlyingType()->isFunctionPointerType())
5620 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5621 }
5622 }
5623 }
5624
5625 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5626 RewriteObjCQualifiedInterfaceTypes(CE);
5627
5628 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5629 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5630 assert(!Stmts.empty() && "Statement stack is empty");
5631 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5632 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5633 && "Statement stack mismatch");
5634 Stmts.pop_back();
5635 }
5636 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005638 ValueDecl *VD = DRE->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005639 if (VD->hasAttr<BlocksAttr>())
5640 return RewriteBlockDeclRefExpr(DRE);
5641 if (HasLocalVariableExternalStorage(VD))
5642 return RewriteLocalVariableExternalStorage(DRE);
5643 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005644
Fariborz Jahanian11671902012-02-07 17:11:38 +00005645 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5646 if (CE->getCallee()->getType()->isBlockPointerType()) {
5647 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5648 ReplaceStmt(S, BlockCall);
5649 return BlockCall;
5650 }
5651 }
5652 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5653 RewriteCastExpr(CE);
5654 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5656 RewriteImplicitCastObjCExpr(ICE);
5657 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005658#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005659
Fariborz Jahanian11671902012-02-07 17:11:38 +00005660 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5661 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5662 ICE->getSubExpr(),
5663 SourceLocation());
5664 // Get the new text.
5665 std::string SStr;
5666 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005667 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005668 const std::string &Str = Buf.str();
5669
5670 printf("CAST = %s\n", &Str[0]);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005671 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005672 delete S;
5673 return Replacement;
5674 }
5675#endif
5676 // Return this stmt unmodified.
5677 return S;
5678}
5679
5680void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005681 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005682 if (isTopLevelBlockPointerType(FD->getType()))
5683 RewriteBlockPointerDecl(FD);
5684 if (FD->getType()->isObjCQualifiedIdType() ||
5685 FD->getType()->isObjCQualifiedInterfaceType())
5686 RewriteObjCQualifiedInterfaceTypes(FD);
5687 }
5688}
5689
5690/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5691/// main file of the input.
5692void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5693 switch (D->getKind()) {
5694 case Decl::Function: {
5695 FunctionDecl *FD = cast<FunctionDecl>(D);
5696 if (FD->isOverloadedOperator())
5697 return;
5698
5699 // Since function prototypes don't have ParmDecl's, we check the function
5700 // prototype. This enables us to rewrite function declarations and
5701 // definitions using the same code.
5702 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5703
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005704 if (!FD->isThisDeclarationADefinition())
5705 break;
5706
Fariborz Jahanian11671902012-02-07 17:11:38 +00005707 // FIXME: If this should support Obj-C++, support CXXTryStmt
5708 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5709 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005710 CurrentBody = Body;
5711 Body =
5712 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5713 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005714 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005715 if (PropParentMap) {
5716 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005717 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005718 }
5719 // This synthesizes and inserts the block "impl" struct, invoke function,
5720 // and any copy/dispose helper functions.
5721 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005722 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005723 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005724 }
5725 break;
5726 }
5727 case Decl::ObjCMethod: {
5728 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5729 if (CompoundStmt *Body = MD->getCompoundBody()) {
5730 CurMethodDef = MD;
5731 CurrentBody = Body;
5732 Body =
5733 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5734 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005735 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005736 if (PropParentMap) {
5737 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005738 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005739 }
5740 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005741 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005742 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005743 }
5744 break;
5745 }
5746 case Decl::ObjCImplementation: {
5747 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5748 ClassImplementation.push_back(CI);
5749 break;
5750 }
5751 case Decl::ObjCCategoryImpl: {
5752 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5753 CategoryImplementation.push_back(CI);
5754 break;
5755 }
5756 case Decl::Var: {
5757 VarDecl *VD = cast<VarDecl>(D);
5758 RewriteObjCQualifiedInterfaceTypes(VD);
5759 if (isTopLevelBlockPointerType(VD->getType()))
5760 RewriteBlockPointerDecl(VD);
5761 else if (VD->getType()->isFunctionPointerType()) {
5762 CheckFunctionPointerDecl(VD->getType(), VD);
5763 if (VD->getInit()) {
5764 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5765 RewriteCastExpr(CE);
5766 }
5767 }
5768 } else if (VD->getType()->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00005769 RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005770 if (RD->isCompleteDefinition())
5771 RewriteRecordBody(RD);
5772 }
5773 if (VD->getInit()) {
5774 GlobalVarDecl = VD;
5775 CurrentBody = VD->getInit();
5776 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005777 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005778 if (PropParentMap) {
5779 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005780 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005781 }
5782 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005783 GlobalVarDecl = nullptr;
5784
Fariborz Jahanian11671902012-02-07 17:11:38 +00005785 // This is needed for blocks.
5786 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5787 RewriteCastExpr(CE);
5788 }
5789 }
5790 break;
5791 }
5792 case Decl::TypeAlias:
5793 case Decl::Typedef: {
5794 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5795 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5796 RewriteBlockPointerDecl(TD);
5797 else if (TD->getUnderlyingType()->isFunctionPointerType())
5798 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005799 else
5800 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005801 }
5802 break;
5803 }
5804 case Decl::CXXRecord:
5805 case Decl::Record: {
5806 RecordDecl *RD = cast<RecordDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00005807 if (RD->isCompleteDefinition())
Fariborz Jahanian11671902012-02-07 17:11:38 +00005808 RewriteRecordBody(RD);
5809 break;
5810 }
5811 default:
5812 break;
5813 }
5814 // Nothing yet.
5815}
5816
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005817/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5818/// protocol reference symbols in the for of:
5819/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Fangrui Song6907ce22018-07-30 19:24:48 +00005820static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005821 ObjCProtocolDecl *PDecl,
5822 std::string &Result) {
5823 // Also output .objc_protorefs$B section and its meta-data.
5824 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005825 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005826 Result += "struct _protocol_t *";
5827 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5828 Result += PDecl->getNameAsString();
5829 Result += " = &";
5830 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5831 Result += ";\n";
5832}
5833
Fariborz Jahanian11671902012-02-07 17:11:38 +00005834void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5835 if (Diags.hasErrorOccurred())
5836 return;
5837
5838 RewriteInclude();
5839
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005840 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005841 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005842 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005843 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005844 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5845 HandleTopLevelSingleDecl(FDecl);
5846 }
5847
Fariborz Jahanian11671902012-02-07 17:11:38 +00005848 // Here's a great place to add any extra declarations that may be needed.
5849 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005850 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5851 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5852 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005853 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005854
5855 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005856
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005857 if (ClassImplementation.size() || CategoryImplementation.size())
5858 RewriteImplementations();
Fangrui Song6907ce22018-07-30 19:24:48 +00005859
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005860 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5861 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5862 // Write struct declaration for the class matching its ivar declarations.
5863 // Note that for modern abi, this is postponed until the end of TU
5864 // because class extensions and the implementation might declare their own
5865 // private ivars.
5866 RewriteInterfaceDecl(CDecl);
5867 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005868
Fariborz Jahanian11671902012-02-07 17:11:38 +00005869 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5870 // we are done.
5871 if (const RewriteBuffer *RewriteBuf =
5872 Rewrite.getRewriteBufferFor(MainFileID)) {
5873 //printf("Changed:\n");
5874 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5875 } else {
5876 llvm::errs() << "No changes\n";
5877 }
5878
5879 if (ClassImplementation.size() || CategoryImplementation.size() ||
5880 ProtocolExprDecls.size()) {
5881 // Rewrite Objective-c meta data*
5882 std::string ResultStr;
5883 RewriteMetaDataIntoBuffer(ResultStr);
5884 // Emit metadata.
5885 *OutFile << ResultStr;
5886 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005887 // Emit ImageInfo;
5888 {
5889 std::string ResultStr;
5890 WriteImageInfo(ResultStr);
5891 *OutFile << ResultStr;
5892 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005893 OutFile->flush();
5894}
5895
5896void RewriteModernObjC::Initialize(ASTContext &context) {
5897 InitializeCommon(context);
Fangrui Song6907ce22018-07-30 19:24:48 +00005898
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005899 Preamble += "#ifndef __OBJC2__\n";
5900 Preamble += "#define __OBJC2__\n";
5901 Preamble += "#endif\n";
5902
Fariborz Jahanian11671902012-02-07 17:11:38 +00005903 // declaring objc_selector outside the parameter list removes a silly
5904 // scope related warning...
5905 if (IsHeader)
5906 Preamble = "#pragma once\n";
5907 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005908 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5909 Preamble += "\n\tstruct objc_object *superClass; ";
5910 // Add a constructor for creating temporary objects.
5911 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5912 Preamble += ": object(o), superClass(s) {} ";
5913 Preamble += "\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005914
Fariborz Jahanian11671902012-02-07 17:11:38 +00005915 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005916 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005917 // These are currently generated.
5918 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005919 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005920 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005921 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5922 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005923 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005924 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005925 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5926 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005927 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005928
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005929 // These need be generated for performance. Currently they are not,
5930 // using API calls instead.
5931 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5932 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5933 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005934
Fariborz Jahanian11671902012-02-07 17:11:38 +00005935 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005936 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5937 Preamble += "typedef struct objc_object Protocol;\n";
5938 Preamble += "#define _REWRITER_typedef_Protocol\n";
5939 Preamble += "#endif\n";
5940 if (LangOpts.MicrosoftExt) {
5941 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5942 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005943 }
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005944 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005945 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005946
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005947 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5951 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5952
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005953 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005954 Preamble += "(const char *);\n";
5955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5956 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005957 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005958 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005959 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005960 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005961 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5962 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005963 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005964 Preamble += "#ifdef _WIN64\n";
5965 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5966 Preamble += "#else\n";
5967 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5968 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005969 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5970 Preamble += "struct __objcFastEnumerationState {\n\t";
5971 Preamble += "unsigned long state;\n\t";
5972 Preamble += "void **itemsPtr;\n\t";
5973 Preamble += "unsigned long *mutationsPtr;\n\t";
5974 Preamble += "unsigned long extra[5];\n};\n";
5975 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5976 Preamble += "#define __FASTENUMERATIONSTATE\n";
5977 Preamble += "#endif\n";
5978 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5979 Preamble += "struct __NSConstantStringImpl {\n";
5980 Preamble += " int *isa;\n";
5981 Preamble += " int flags;\n";
5982 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005983 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005984 Preamble += " long long length;\n";
5985 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005986 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005987 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005988 Preamble += "};\n";
5989 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5990 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5991 Preamble += "#else\n";
5992 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5993 Preamble += "#endif\n";
5994 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5995 Preamble += "#endif\n";
5996 // Blocks preamble.
5997 Preamble += "#ifndef BLOCK_IMPL\n";
5998 Preamble += "#define BLOCK_IMPL\n";
5999 Preamble += "struct __block_impl {\n";
6000 Preamble += " void *isa;\n";
6001 Preamble += " int Flags;\n";
6002 Preamble += " int Reserved;\n";
6003 Preamble += " void *FuncPtr;\n";
6004 Preamble += "};\n";
6005 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6006 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6007 Preamble += "extern \"C\" __declspec(dllexport) "
6008 "void _Block_object_assign(void *, const void *, const int);\n";
6009 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6010 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6011 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6012 Preamble += "#else\n";
6013 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6014 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6015 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6016 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6017 Preamble += "#endif\n";
6018 Preamble += "#endif\n";
6019 if (LangOpts.MicrosoftExt) {
6020 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6021 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6022 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6023 Preamble += "#define __attribute__(X)\n";
6024 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006025 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006026 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006027 Preamble += "#endif\n";
6028 Preamble += "#ifndef __block\n";
6029 Preamble += "#define __block\n";
6030 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006031 }
6032 else {
6033 Preamble += "#define __block\n";
6034 Preamble += "#define __weak\n";
6035 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006036
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006037 // Declarations required for modern objective-c array and dictionary literals.
6038 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006039 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006040 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006041 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006042 Preamble += "\tva_list marker;\n";
6043 Preamble += "\tva_start(marker, count);\n";
6044 Preamble += "\tarr = new void *[count];\n";
6045 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6046 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6047 Preamble += "\tva_end( marker );\n";
6048 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006049 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006050 Preamble += "\tdelete[] arr;\n";
6051 Preamble += " }\n";
6052 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006053
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006054 // Declaration required for implementation of @autoreleasepool statement.
6055 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6056 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6057 Preamble += "struct __AtAutoreleasePool {\n";
6058 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6059 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6060 Preamble += " void * atautoreleasepoolobj;\n";
6061 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006062
Fariborz Jahanian11671902012-02-07 17:11:38 +00006063 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6064 // as this avoids warning in any 64bit/32bit compilation model.
6065 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6066}
6067
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00006068/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian11671902012-02-07 17:11:38 +00006069/// ivar offset.
6070void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6071 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006072 Result += "__OFFSETOFIVAR__(struct ";
6073 Result += ivar->getContainingInterface()->getNameAsString();
6074 if (LangOpts.MicrosoftExt)
6075 Result += "_IMPL";
6076 Result += ", ";
6077 if (ivar->isBitField())
6078 ObjCIvarBitfieldGroupDecl(ivar, Result);
6079 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006080 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006081 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082}
6083
6084/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6085/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006086/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006087/// char *attributes;
6088/// }
6089
6090/// struct _prop_list_t {
6091/// uint32_t entsize; // sizeof(struct _prop_t)
6092/// uint32_t count_of_properties;
6093/// struct _prop_t prop_list[count_of_properties];
6094/// }
6095
6096/// struct _protocol_t;
6097
6098/// struct _protocol_list_t {
6099/// long protocol_count; // Note, this is 32/64 bit
6100/// struct _protocol_t * protocol_list[protocol_count];
6101/// }
6102
6103/// struct _objc_method {
6104/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006105/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006106/// char *_imp;
6107/// }
6108
6109/// struct _method_list_t {
6110/// uint32_t entsize; // sizeof(struct _objc_method)
6111/// uint32_t method_count;
6112/// struct _objc_method method_list[method_count];
6113/// }
6114
6115/// struct _protocol_t {
6116/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006117/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006118/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006119/// const struct method_list_t *instance_methods;
6120/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006121/// const struct method_list_t *optionalInstanceMethods;
6122/// const struct method_list_t *optionalClassMethods;
6123/// const struct _prop_list_t * properties;
6124/// const uint32_t size; // sizeof(struct _protocol_t)
6125/// const uint32_t flags; // = 0
6126/// const char ** extendedMethodTypes;
6127/// }
6128
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006129/// struct _ivar_t {
6130/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006131/// const char *name;
6132/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006133/// uint32_t alignment;
6134/// uint32_t size;
6135/// }
6136
6137/// struct _ivar_list_t {
6138/// uint32 entsize; // sizeof(struct _ivar_t)
6139/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006140/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006141/// }
6142
6143/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006144/// uint32_t flags;
6145/// uint32_t instanceStart;
6146/// uint32_t instanceSize;
6147/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006148/// const uint8_t *ivarLayout;
6149/// const char *name;
6150/// const struct _method_list_t *baseMethods;
6151/// const struct _protocol_list_t *baseProtocols;
6152/// const struct _ivar_list_t *ivars;
6153/// const uint8_t *weakIvarLayout;
6154/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006155/// }
6156
6157/// struct _class_t {
6158/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006159/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006160/// void *cache;
6161/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006162/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006163/// }
6164
6165/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006166/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006167/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006168/// const struct _method_list_t *instance_methods;
6169/// const struct _method_list_t *class_methods;
6170/// const struct _protocol_list_t *protocols;
6171/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006172/// }
6173
6174/// MessageRefTy - LLVM for:
6175/// struct _message_ref_t {
6176/// IMP messenger;
6177/// SEL name;
6178/// };
6179
6180/// SuperMessageRefTy - LLVM for:
6181/// struct _super_message_ref_t {
6182/// SUPER_IMP messenger;
6183/// SEL name;
6184/// };
6185
Fariborz Jahanian45489622012-03-14 18:09:23 +00006186static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006187 static bool meta_data_declared = false;
6188 if (meta_data_declared)
6189 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006190
Fariborz Jahanian11671902012-02-07 17:11:38 +00006191 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006192 Result += "\tconst char *name;\n";
6193 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006194 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006195
Fariborz Jahanian11671902012-02-07 17:11:38 +00006196 Result += "\nstruct _protocol_t;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006197
Fariborz Jahanian11671902012-02-07 17:11:38 +00006198 Result += "\nstruct _objc_method {\n";
6199 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006200 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006201 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006203
Fariborz Jahanian11671902012-02-07 17:11:38 +00006204 Result += "\nstruct _protocol_t {\n";
6205 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006206 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006207 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006208 Result += "\tconst struct method_list_t *instance_methods;\n";
6209 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006210 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6211 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6212 Result += "\tconst struct _prop_list_t * properties;\n";
6213 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6214 Result += "\tconst unsigned int flags; // = 0\n";
6215 Result += "\tconst char ** extendedMethodTypes;\n";
6216 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006217
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006218 Result += "\nstruct _ivar_t {\n";
6219 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006220 Result += "\tconst char *name;\n";
6221 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006222 Result += "\tunsigned int alignment;\n";
6223 Result += "\tunsigned int size;\n";
6224 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006225
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006226 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006227 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006228 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006229 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006230 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6231 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006232 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006233 Result += "\tconst unsigned char *ivarLayout;\n";
6234 Result += "\tconst char *name;\n";
6235 Result += "\tconst struct _method_list_t *baseMethods;\n";
6236 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6237 Result += "\tconst struct _ivar_list_t *ivars;\n";
6238 Result += "\tconst unsigned char *weakIvarLayout;\n";
6239 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006240 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006241
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006242 Result += "\nstruct _class_t {\n";
6243 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006244 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006245 Result += "\tvoid *cache;\n";
6246 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006247 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006248 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006249
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006250 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006251 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006252 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006253 Result += "\tconst struct _method_list_t *instance_methods;\n";
6254 Result += "\tconst struct _method_list_t *class_methods;\n";
6255 Result += "\tconst struct _protocol_list_t *protocols;\n";
6256 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006257 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006258
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006259 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006260 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006261 meta_data_declared = true;
6262}
6263
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006264static void Write_protocol_list_t_TypeDecl(std::string &Result,
6265 long super_protocol_count) {
6266 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6267 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6268 Result += "\tstruct _protocol_t *super_protocols[";
6269 Result += utostr(super_protocol_count); Result += "];\n";
6270 Result += "}";
6271}
6272
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006273static void Write_method_list_t_TypeDecl(std::string &Result,
6274 unsigned int method_count) {
6275 Result += "struct /*_method_list_t*/"; Result += " {\n";
6276 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6277 Result += "\tunsigned int method_count;\n";
6278 Result += "\tstruct _objc_method method_list[";
6279 Result += utostr(method_count); Result += "];\n";
6280 Result += "}";
6281}
6282
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006283static void Write__prop_list_t_TypeDecl(std::string &Result,
6284 unsigned int property_count) {
6285 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6286 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6287 Result += "\tunsigned int count_of_properties;\n";
6288 Result += "\tstruct _prop_t prop_list[";
6289 Result += utostr(property_count); Result += "];\n";
6290 Result += "}";
6291}
6292
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006293static void Write__ivar_list_t_TypeDecl(std::string &Result,
6294 unsigned int ivar_count) {
6295 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6296 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6297 Result += "\tunsigned int count;\n";
6298 Result += "\tstruct _ivar_t ivar_list[";
6299 Result += utostr(ivar_count); Result += "];\n";
6300 Result += "}";
6301}
6302
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006303static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6304 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6305 StringRef VarName,
6306 StringRef ProtocolName) {
6307 if (SuperProtocols.size() > 0) {
6308 Result += "\nstatic ";
6309 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6310 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006311 Result += ProtocolName;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006312 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6313 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6314 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6315 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00006316 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006317 Result += SuperPD->getNameAsString();
6318 if (i == e-1)
6319 Result += "\n};\n";
6320 else
6321 Result += ",\n";
6322 }
6323 }
6324}
6325
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006326static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6327 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006328 ArrayRef<ObjCMethodDecl *> Methods,
6329 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006330 StringRef TopLevelDeclName,
6331 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006332 if (Methods.size() > 0) {
6333 Result += "\nstatic ";
6334 Write_method_list_t_TypeDecl(Result, Methods.size());
6335 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006336 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006337 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6338 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6339 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6340 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6341 ObjCMethodDecl *MD = Methods[i];
6342 if (i == 0)
6343 Result += "\t{{(struct objc_selector *)\"";
6344 else
6345 Result += "\t{(struct objc_selector *)\"";
6346 Result += (MD)->getSelector().getAsString(); Result += "\"";
6347 Result += ", ";
John McCall843dfcc2016-11-29 21:57:00 +00006348 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006349 Result += "\""; Result += MethodTypeString; Result += "\"";
6350 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006351 if (!MethodImpl)
6352 Result += "0";
6353 else {
6354 Result += "(void *)";
6355 Result += RewriteObj.MethodInternalNames[MD];
6356 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006357 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006358 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006359 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006360 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006361 }
6362 Result += "};\n";
6363 }
6364}
6365
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006366static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006367 ASTContext *Context, std::string &Result,
6368 ArrayRef<ObjCPropertyDecl *> Properties,
6369 const Decl *Container,
6370 StringRef VarName,
6371 StringRef ProtocolName) {
6372 if (Properties.size() > 0) {
6373 Result += "\nstatic ";
6374 Write__prop_list_t_TypeDecl(Result, Properties.size());
6375 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006376 Result += ProtocolName;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006377 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6378 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6379 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6380 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6381 ObjCPropertyDecl *PropDecl = Properties[i];
6382 if (i == 0)
6383 Result += "\t{{\"";
6384 else
6385 Result += "\t{\"";
6386 Result += PropDecl->getName(); Result += "\",";
John McCall843dfcc2016-11-29 21:57:00 +00006387 std::string PropertyTypeString =
6388 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6389 std::string QuotePropertyTypeString;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006390 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6391 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6392 if (i == e-1)
6393 Result += "}}\n";
6394 else
6395 Result += "},\n";
6396 }
6397 Result += "};\n";
6398 }
6399}
6400
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006401// Metadata flags
6402enum MetaDataDlags {
6403 CLS = 0x0,
6404 CLS_META = 0x1,
6405 CLS_ROOT = 0x2,
6406 OBJC2_CLS_HIDDEN = 0x10,
6407 CLS_EXCEPTION = 0x20,
Fangrui Song6907ce22018-07-30 19:24:48 +00006408
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006409 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6410 CLS_HAS_IVAR_RELEASER = 0x40,
6411 /// class was compiled with -fobjc-arr
6412 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6413};
6414
Fangrui Song6907ce22018-07-30 19:24:48 +00006415static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6416 unsigned int flags,
6417 const std::string &InstanceStart,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006418 const std::string &InstanceSize,
6419 ArrayRef<ObjCMethodDecl *>baseMethods,
6420 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6421 ArrayRef<ObjCIvarDecl *>ivars,
6422 ArrayRef<ObjCPropertyDecl *>Properties,
6423 StringRef VarName,
6424 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006425 Result += "\nstatic struct _class_ro_t ";
6426 Result += VarName; Result += ClassName;
6427 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006428 Result += "\t";
6429 Result += llvm::utostr(flags); Result += ", ";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006430 Result += InstanceStart; Result += ", ";
6431 Result += InstanceSize; Result += ", \n";
6432 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006433 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6434 if (Triple.getArch() == llvm::Triple::x86_64)
6435 // uint32_t const reserved; // only when building for 64bit targets
6436 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006437 // const uint8_t * const ivarLayout;
6438 Result += "0, \n\t";
6439 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006440 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006441 if (baseMethods.size() > 0) {
6442 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006443 if (metaclass)
6444 Result += "_OBJC_$_CLASS_METHODS_";
6445 else
6446 Result += "_OBJC_$_INSTANCE_METHODS_";
6447 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006448 Result += ",\n\t";
6449 }
6450 else
6451 Result += "0, \n\t";
6452
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006453 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006454 Result += "(const struct _objc_protocol_list *)&";
6455 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6456 Result += ",\n\t";
6457 }
6458 else
6459 Result += "0, \n\t";
6460
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006461 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006462 Result += "(const struct _ivar_list_t *)&";
6463 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6464 Result += ",\n\t";
6465 }
6466 else
6467 Result += "0, \n\t";
6468
6469 // weakIvarLayout
6470 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006471 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006472 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006473 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006474 Result += ",\n";
6475 }
6476 else
6477 Result += "0, \n";
6478
6479 Result += "};\n";
6480}
6481
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006482static void Write_class_t(ASTContext *Context, std::string &Result,
6483 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006484 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6485 bool rootClass = (!CDecl->getSuperClass());
6486 const ObjCInterfaceDecl *RootClass = CDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +00006487
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006488 if (!rootClass) {
6489 // Find the Root class
6490 RootClass = CDecl->getSuperClass();
6491 while (RootClass->getSuperClass()) {
6492 RootClass = RootClass->getSuperClass();
6493 }
6494 }
6495
6496 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006497 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006498 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006499 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006500 if (CDecl->getImplementation())
6501 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006502 else
6503 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006504
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006505 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006506 Result += CDecl->getNameAsString();
6507 Result += ";\n";
6508 }
6509 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006510 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006511 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006512 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006513 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006514 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006515 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006516 else
6517 Result += "__declspec(dllimport) ";
6518
Fangrui Song6907ce22018-07-30 19:24:48 +00006519 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006520 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006521 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006522 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006523
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006524 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006525 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006526 if (RootClass->getImplementation())
6527 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006528 else
6529 Result += "__declspec(dllimport) ";
6530
Fangrui Song6907ce22018-07-30 19:24:48 +00006531 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006532 Result += VarName;
6533 Result += RootClass->getNameAsString();
6534 Result += ";\n";
6535 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006536 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006537
6538 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006539 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006540 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6541 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006542 if (metaclass) {
6543 if (!rootClass) {
6544 Result += "0, // &"; Result += VarName;
6545 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006546 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006547 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006548 Result += CDecl->getSuperClass()->getNameAsString();
6549 Result += ",\n\t";
6550 }
6551 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006552 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006553 Result += CDecl->getNameAsString();
6554 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006555 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006556 Result += ",\n\t";
6557 }
6558 }
6559 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006560 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006561 Result += CDecl->getNameAsString();
6562 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006563 if (!rootClass) {
6564 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006565 Result += CDecl->getSuperClass()->getNameAsString();
6566 Result += ",\n\t";
6567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006568 else
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006569 Result += "0,\n\t";
6570 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006571 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6572 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6573 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006574 Result += "&_OBJC_METACLASS_RO_$_";
6575 else
6576 Result += "&_OBJC_CLASS_RO_$_";
6577 Result += CDecl->getNameAsString();
6578 Result += ",\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006579
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006580 // Add static function to initialize some of the meta-data fields.
6581 // avoid doing it twice.
6582 if (metaclass)
6583 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006584
6585 const ObjCInterfaceDecl *SuperClass =
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006586 rootClass ? CDecl : CDecl->getSuperClass();
Fangrui Song6907ce22018-07-30 19:24:48 +00006587
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006588 Result += "static void OBJC_CLASS_SETUP_$_";
6589 Result += CDecl->getNameAsString();
6590 Result += "(void ) {\n";
6591 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6592 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006593 Result += RootClass->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();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006596 Result += ".superclass = ";
6597 if (rootClass)
6598 Result += "&OBJC_CLASS_$_";
6599 else
6600 Result += "&OBJC_METACLASS_$_";
6601
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006602 Result += SuperClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006603
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006604 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6605 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006606
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006607 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6608 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6609 Result += CDecl->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006610
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006611 if (!rootClass) {
6612 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6613 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6614 Result += SuperClass->getNameAsString(); Result += ";\n";
6615 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006616
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006617 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6618 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6619 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006620}
6621
Fangrui Song6907ce22018-07-30 19:24:48 +00006622static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006623 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006624 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006625 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006626 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6627 ArrayRef<ObjCMethodDecl *> ClassMethods,
6628 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6629 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006630 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006631 StringRef ClassName = ClassDecl->getName();
Fangrui Song6907ce22018-07-30 19:24:48 +00006632 // must declare an extern class object in case this class is not implemented
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006633 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006634 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006635 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006636 if (ClassDecl->getImplementation())
6637 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006638 else
6639 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006640
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006641 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006642 Result += "OBJC_CLASS_$_"; Result += ClassName;
6643 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006644
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006645 Result += "\nstatic struct _category_t ";
6646 Result += "_OBJC_$_CATEGORY_";
6647 Result += ClassName; Result += "_$_"; Result += CatName;
6648 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6649 Result += "{\n";
6650 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006651 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006652 Result += ",\n";
6653 if (InstanceMethods.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_INSTANCE_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 (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006663 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006664 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
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 (RefedProtocols.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006672 Result += "\t(const struct _protocol_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006673 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6674 Result += ClassName; Result += "_$_"; Result += CatName;
6675 Result += ",\n";
6676 }
6677 else
6678 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006679
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006680 if (ClassProperties.size() > 0) {
6681 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6682 Result += ClassName; Result += "_$_"; Result += CatName;
6683 Result += ",\n";
6684 }
6685 else
6686 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006687
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006688 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006689
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006690 // Add static function to initialize the class pointer in the category structure.
6691 Result += "static void OBJC_CATEGORY_SETUP_$_";
6692 Result += ClassDecl->getNameAsString();
6693 Result += "_$_";
6694 Result += CatName;
6695 Result += "(void ) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006696 Result += "\t_OBJC_$_CATEGORY_";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006697 Result += ClassDecl->getNameAsString();
6698 Result += "_$_";
6699 Result += CatName;
6700 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6701 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006702}
6703
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006704static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6705 ASTContext *Context, std::string &Result,
6706 ArrayRef<ObjCMethodDecl *> Methods,
6707 StringRef VarName,
6708 StringRef ProtocolName) {
6709 if (Methods.size() == 0)
6710 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006711
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006712 Result += "\nstatic const char *";
6713 Result += VarName; Result += ProtocolName;
6714 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6715 Result += "{\n";
6716 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6717 ObjCMethodDecl *MD = Methods[i];
John McCall843dfcc2016-11-29 21:57:00 +00006718 std::string MethodTypeString =
6719 Context->getObjCEncodingForMethodDecl(MD, true);
6720 std::string QuoteMethodTypeString;
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006721 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6722 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6723 if (i == e-1)
6724 Result += "\n};\n";
6725 else {
6726 Result += ",\n";
6727 }
6728 }
6729}
6730
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006731static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6732 ASTContext *Context,
Fangrui Song6907ce22018-07-30 19:24:48 +00006733 std::string &Result,
6734 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006735 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006736 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6737 // this is what happens:
6738 /**
6739 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6740 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6741 Class->getVisibility() == HiddenVisibility)
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006742 Visibility should be: HiddenVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006743 else
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006744 Visibility should be: DefaultVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006745 */
Fangrui Song6907ce22018-07-30 19:24:48 +00006746
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006747 Result += "\n";
6748 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6749 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006750 if (Context->getLangOpts().MicrosoftExt)
6751 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006752
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006753 if (!Context->getLangOpts().MicrosoftExt ||
6754 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006755 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fangrui Song6907ce22018-07-30 19:24:48 +00006756 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006757 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006758 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006759 if (Ivars[i]->isBitField())
6760 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6761 else
6762 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006763 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6764 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006765 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6766 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006767 if (Ivars[i]->isBitField()) {
6768 // skip over rest of the ivar bitfields.
6769 SKIP_BITFIELDS(i , e, Ivars);
6770 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006771 }
6772}
6773
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006774static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6775 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006776 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006777 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006778 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006779 if (OriginalIvars.size() > 0) {
6780 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6781 SmallVector<ObjCIvarDecl *, 8> Ivars;
6782 // strip off all but the first ivar bitfield from each group of ivars.
6783 // Such ivars in the ivar list table will be replaced by their grouping struct
6784 // 'ivar'.
6785 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6786 if (OriginalIvars[i]->isBitField()) {
6787 Ivars.push_back(OriginalIvars[i]);
6788 // skip over rest of the ivar bitfields.
6789 SKIP_BITFIELDS(i , e, OriginalIvars);
6790 }
6791 else
6792 Ivars.push_back(OriginalIvars[i]);
6793 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006794
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006795 Result += "\nstatic ";
6796 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6797 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006798 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006799 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6800 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6801 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6802 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6803 ObjCIvarDecl *IvarDecl = Ivars[i];
6804 if (i == 0)
6805 Result += "\t{{";
6806 else
6807 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006808 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006809 if (Ivars[i]->isBitField())
6810 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6811 else
6812 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006813 Result += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006814
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006815 Result += "\"";
6816 if (Ivars[i]->isBitField())
6817 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6818 else
6819 Result += IvarDecl->getName();
6820 Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006821
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006822 QualType IVQT = IvarDecl->getType();
6823 if (IvarDecl->isBitField())
6824 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00006825
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006826 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006827 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006828 IvarDecl);
6829 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6830 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006831
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006832 // FIXME. this alignment represents the host alignment and need be changed to
6833 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006834 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006835 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006836 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006837 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006838 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006839 if (i == e-1)
6840 Result += "}}\n";
6841 else
6842 Result += "},\n";
6843 }
6844 Result += "};\n";
6845 }
6846}
6847
Fariborz Jahanian11671902012-02-07 17:11:38 +00006848/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fangrui Song6907ce22018-07-30 19:24:48 +00006849void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006850 std::string &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006851
Fariborz Jahanian11671902012-02-07 17:11:38 +00006852 // Do not synthesize the protocol more than once.
6853 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6854 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006855 WriteModernMetadataDeclarations(Context, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006856
Fariborz Jahanian11671902012-02-07 17:11:38 +00006857 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6858 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006859 // Must write out all protocol definitions in current qualifier list,
6860 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006861 for (auto *I : PDecl->protocols())
6862 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006863
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006864 // Construct method lists.
6865 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6866 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006867 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006868 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6869 OptInstanceMethods.push_back(MD);
6870 } else {
6871 InstanceMethods.push_back(MD);
6872 }
6873 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006874
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006875 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006876 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6877 OptClassMethods.push_back(MD);
6878 } else {
6879 ClassMethods.push_back(MD);
6880 }
6881 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006882 std::vector<ObjCMethodDecl *> AllMethods;
6883 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6884 AllMethods.push_back(InstanceMethods[i]);
6885 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6886 AllMethods.push_back(ClassMethods[i]);
6887 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6888 AllMethods.push_back(OptInstanceMethods[i]);
6889 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6890 AllMethods.push_back(OptClassMethods[i]);
6891
6892 Write__extendedMethodTypes_initializer(*this, Context, Result,
6893 AllMethods,
6894 "_OBJC_PROTOCOL_METHOD_TYPES_",
6895 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006896 // Protocol's super protocol list
Fangrui Song6907ce22018-07-30 19:24:48 +00006897 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006898 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6899 "_OBJC_PROTOCOL_REFS_",
6900 PDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00006901
6902 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006903 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006904 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006905
6906 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006907 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006908 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006909
Fangrui Song6907ce22018-07-30 19:24:48 +00006910 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006911 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006912 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006913
6914 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006915 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006916 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006917
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006918 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006919 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6920 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006921 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006922 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006923 "_OBJC_PROTOCOL_PROPERTIES_",
6924 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006925
Fariborz Jahanian48985802012-02-08 00:50:52 +00006926 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006927 Result += "\n";
6928 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006929 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006930 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006931 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006932 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006933 Result += "\t0,\n"; // id is; is null
6934 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006935 if (SuperProtocols.size() > 0) {
6936 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6937 Result += PDecl->getNameAsString(); Result += ",\n";
6938 }
6939 else
6940 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006941 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006942 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006943 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006944 }
6945 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006946 Result += "\t0,\n";
6947
6948 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006949 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006950 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006951 }
6952 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006953 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006954
Fariborz Jahanian48985802012-02-08 00:50:52 +00006955 if (OptInstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006956 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006957 Result += PDecl->getNameAsString(); Result += ",\n";
6958 }
6959 else
6960 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006961
Fariborz Jahanian48985802012-02-08 00:50:52 +00006962 if (OptClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006963 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006964 Result += PDecl->getNameAsString(); Result += ",\n";
6965 }
6966 else
6967 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006968
Fariborz Jahanian48985802012-02-08 00:50:52 +00006969 if (ProtocolProperties.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006970 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006971 Result += PDecl->getNameAsString(); Result += ",\n";
6972 }
6973 else
6974 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006975
Fariborz Jahanian48985802012-02-08 00:50:52 +00006976 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6977 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006978
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006979 if (AllMethods.size() > 0) {
6980 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6981 Result += PDecl->getNameAsString();
6982 Result += "\n};\n";
6983 }
6984 else
6985 Result += "\t0\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006986
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006987 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006988 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006989 Result += "struct _protocol_t *";
6990 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6991 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6992 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006993
Fariborz Jahanian11671902012-02-07 17:11:38 +00006994 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00006995 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00006996 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00006997}
6998
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006999/// hasObjCExceptionAttribute - Return true if this class or any super
7000/// class has the __objc_exception__ attribute.
7001/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7002static bool hasObjCExceptionAttribute(ASTContext &Context,
7003 const ObjCInterfaceDecl *OID) {
7004 if (OID->hasAttr<ObjCExceptionAttr>())
7005 return true;
7006 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7007 return hasObjCExceptionAttribute(Context, Super);
7008 return false;
7009}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007010
Fariborz Jahanian11671902012-02-07 17:11:38 +00007011void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7012 std::string &Result) {
7013 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00007014
Fariborz Jahanian11671902012-02-07 17:11:38 +00007015 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007016 if (CDecl->isImplicitInterfaceDecl())
Fangrui Song6907ce22018-07-30 19:24:48 +00007017 assert(false &&
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007018 "Legacy implicit interface rewriting not supported in moder abi");
Fangrui Song6907ce22018-07-30 19:24:48 +00007019
Fariborz Jahanian45489622012-03-14 18:09:23 +00007020 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007021 SmallVector<ObjCIvarDecl *, 8> IVars;
Fangrui Song6907ce22018-07-30 19:24:48 +00007022
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007023 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7024 IVD; IVD = IVD->getNextIvar()) {
7025 // Ignore unnamed bit-fields.
7026 if (!IVD->getDeclName())
7027 continue;
7028 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007029 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007030
7031 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007032 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007033 CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00007034
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007035 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007036 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007037
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007038 // If any of our property implementations have associated getters or
7039 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007040 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007041 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007043 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007044 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007045 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007046 if (!PD)
7047 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007048 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007049 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007050 InstanceMethods.push_back(Getter);
7051 if (PD->isReadOnly())
7052 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007053 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007054 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007055 InstanceMethods.push_back(Setter);
7056 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007057
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007058 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7059 "_OBJC_$_INSTANCE_METHODS_",
7060 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007061
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007062 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007063
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007064 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7065 "_OBJC_$_CLASS_METHODS_",
7066 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007067
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007068 // Protocols referenced in class declaration?
7069 // Protocol's super protocol list
7070 std::vector<ObjCProtocolDecl *> RefedProtocols;
7071 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7072 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7073 E = Protocols.end();
7074 I != E; ++I) {
7075 RefedProtocols.push_back(*I);
7076 // Must write out all protocol definitions in current qualifier list,
7077 // and in their nested qualifiers before writing out current definition.
7078 RewriteObjCProtocolMetaData(*I, Result);
7079 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007080
7081 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007082 RefedProtocols,
7083 "_OBJC_CLASS_PROTOCOLS_$_",
7084 IDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007085
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007086 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007087 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7088 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007089 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007090 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007091 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007092 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007093
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007094 // Data for initializing _class_ro_t metaclass meta-data
7095 uint32_t flags = CLS_META;
7096 std::string InstanceSize;
7097 std::string InstanceStart;
Fangrui Song6907ce22018-07-30 19:24:48 +00007098
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007099 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7100 if (classIsHidden)
7101 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007102
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007103 if (!CDecl->getSuperClass())
7104 // class is root
7105 flags |= CLS_ROOT;
7106 InstanceSize = "sizeof(struct _class_t)";
7107 InstanceStart = InstanceSize;
Fangrui Song6907ce22018-07-30 19:24:48 +00007108 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007109 InstanceStart, InstanceSize,
7110 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007111 nullptr,
7112 nullptr,
7113 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007114 "_OBJC_METACLASS_RO_$_",
7115 CDecl->getNameAsString());
7116
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007117 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007118 flags = CLS;
7119 if (classIsHidden)
7120 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007121
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007122 if (hasObjCExceptionAttribute(*Context, CDecl))
7123 flags |= CLS_EXCEPTION;
7124
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007125 if (!CDecl->getSuperClass())
7126 // class is root
7127 flags |= CLS_ROOT;
Fangrui Song6907ce22018-07-30 19:24:48 +00007128
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007129 InstanceSize.clear();
7130 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007131 if (!ObjCSynthesizedStructs.count(CDecl)) {
7132 InstanceSize = "0";
7133 InstanceStart = "0";
7134 }
7135 else {
7136 InstanceSize = "sizeof(struct ";
7137 InstanceSize += CDecl->getNameAsString();
7138 InstanceSize += "_IMPL)";
Fangrui Song6907ce22018-07-30 19:24:48 +00007139
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007140 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7141 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007142 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007143 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007144 else
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007145 InstanceStart = InstanceSize;
7146 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007147 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007148 InstanceStart, InstanceSize,
7149 InstanceMethods,
7150 RefedProtocols,
7151 IVars,
7152 ClassProperties,
7153 "_OBJC_CLASS_RO_$_",
7154 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007155
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007156 Write_class_t(Context, Result,
7157 "OBJC_METACLASS_$_",
7158 CDecl, /*metaclass*/true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007159
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007160 Write_class_t(Context, Result,
7161 "OBJC_CLASS_$_",
7162 CDecl, /*metaclass*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00007163
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007164 if (ImplementationIsNonLazy(IDecl))
7165 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007166}
7167
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007168void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7169 int ClsDefCount = ClassImplementation.size();
7170 if (!ClsDefCount)
7171 return;
7172 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7173 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7174 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7175 for (int i = 0; i < ClsDefCount; i++) {
7176 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7177 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7178 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7179 Result += CDecl->getName(); Result += ",\n";
7180 }
7181 Result += "};\n";
7182}
7183
Fariborz Jahanian11671902012-02-07 17:11:38 +00007184void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7185 int ClsDefCount = ClassImplementation.size();
7186 int CatDefCount = CategoryImplementation.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00007187
Fariborz Jahanian11671902012-02-07 17:11:38 +00007188 // For each implemented class, write out all its meta data.
7189 for (int i = 0; i < ClsDefCount; i++)
7190 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007191
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007192 RewriteClassSetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007193
Fariborz Jahanian11671902012-02-07 17:11:38 +00007194 // For each implemented category, write out all its meta data.
7195 for (int i = 0; i < CatDefCount; i++)
7196 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007197
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007198 RewriteCategorySetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007199
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007200 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007201 if (LangOpts.MicrosoftExt)
7202 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007203 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7204 Result += llvm::utostr(ClsDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007205 Result +=
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007206 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7207 "regular,no_dead_strip\")))= {\n";
7208 for (int i = 0; i < ClsDefCount; i++) {
7209 Result += "\t&OBJC_CLASS_$_";
7210 Result += ClassImplementation[i]->getNameAsString();
7211 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007212 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007213 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007214
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007215 if (!DefinedNonLazyClasses.empty()) {
7216 if (LangOpts.MicrosoftExt)
7217 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7218 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7219 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7220 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7221 Result += ",\n";
7222 }
7223 Result += "};\n";
7224 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007225 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007226
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007227 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007228 if (LangOpts.MicrosoftExt)
7229 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007230 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7231 Result += llvm::utostr(CatDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007232 Result +=
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007233 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7234 "regular,no_dead_strip\")))= {\n";
7235 for (int i = 0; i < CatDefCount; i++) {
7236 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007237 Result +=
7238 CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007239 Result += "_$_";
7240 Result += CategoryImplementation[i]->getNameAsString();
7241 Result += ",\n";
7242 }
7243 Result += "};\n";
7244 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007245
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007246 if (!DefinedNonLazyCategories.empty()) {
7247 if (LangOpts.MicrosoftExt)
7248 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7249 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7250 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7251 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007252 Result +=
7253 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007254 Result += "_$_";
7255 Result += DefinedNonLazyCategories[i]->getNameAsString();
7256 Result += ",\n";
7257 }
7258 Result += "};\n";
7259 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007260}
7261
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007262void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7263 if (LangOpts.MicrosoftExt)
7264 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007265
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007266 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7267 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007268 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007269}
7270
Fariborz Jahanian11671902012-02-07 17:11:38 +00007271/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7272/// implementation.
7273void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7274 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007275 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007276 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7277 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007278 ObjCCategoryDecl *CDecl
7279 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fangrui Song6907ce22018-07-30 19:24:48 +00007280
Fariborz Jahanian11671902012-02-07 17:11:38 +00007281 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007282 FullCategoryName += "_$_";
7283 FullCategoryName += CDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00007284
Fariborz Jahanian11671902012-02-07 17:11:38 +00007285 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007286 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007287
Fariborz Jahanian11671902012-02-07 17:11:38 +00007288 // If any of our property implementations have associated getters or
7289 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007290 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007291 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007292 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007293 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007294 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007295 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007296 if (!PD)
7297 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007298 if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007299 InstanceMethods.push_back(Getter);
7300 if (PD->isReadOnly())
7301 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -08007302 if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007303 InstanceMethods.push_back(Setter);
7304 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007305
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007306 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7307 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7308 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007309
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007310 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007311
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007312 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7313 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7314 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007315
Fariborz Jahanian11671902012-02-07 17:11:38 +00007316 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007317 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007318 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7319 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007320 // Must write out all protocol definitions in current qualifier list,
7321 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007322 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007323
7324 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007325 RefedProtocols,
7326 "_OBJC_CATEGORY_PROTOCOLS_$_",
7327 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007328
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007329 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007330 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7331 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007332 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007333 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007334 "_OBJC_$_PROP_LIST_",
7335 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007336
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007337 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007338 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007339 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007340 InstanceMethods,
7341 ClassMethods,
7342 RefedProtocols,
7343 ClassProperties);
Fangrui Song6907ce22018-07-30 19:24:48 +00007344
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007345 // Determine if this category is also "non-lazy".
7346 if (ImplementationIsNonLazy(IDecl))
7347 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007348}
7349
7350void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7351 int CatDefCount = CategoryImplementation.size();
7352 if (!CatDefCount)
7353 return;
7354 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7355 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7356 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7357 for (int i = 0; i < CatDefCount; i++) {
7358 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7359 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7360 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7361 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7362 Result += ClassDecl->getName();
7363 Result += "_$_";
7364 Result += CatDecl->getName();
7365 Result += ",\n";
7366 }
7367 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007368}
7369
7370// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7371/// class methods.
7372template<typename MethodIterator>
7373void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7374 MethodIterator MethodEnd,
7375 bool IsInstanceMethod,
7376 StringRef prefix,
7377 StringRef ClassName,
7378 std::string &Result) {
7379 if (MethodBegin == MethodEnd) return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007380
Fariborz Jahanian11671902012-02-07 17:11:38 +00007381 if (!objc_impl_method) {
7382 /* struct _objc_method {
7383 SEL _cmd;
7384 char *method_types;
7385 void *_imp;
7386 }
7387 */
7388 Result += "\nstruct _objc_method {\n";
7389 Result += "\tSEL _cmd;\n";
7390 Result += "\tchar *method_types;\n";
7391 Result += "\tvoid *_imp;\n";
7392 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007393
Fariborz Jahanian11671902012-02-07 17:11:38 +00007394 objc_impl_method = true;
7395 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007396
Fariborz Jahanian11671902012-02-07 17:11:38 +00007397 // Build _objc_method_list for class's methods if needed
Fangrui Song6907ce22018-07-30 19:24:48 +00007398
Fariborz Jahanian11671902012-02-07 17:11:38 +00007399 /* struct {
7400 struct _objc_method_list *next_method;
7401 int method_count;
7402 struct _objc_method method_list[];
7403 }
7404 */
7405 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007406 Result += "\n";
7407 if (LangOpts.MicrosoftExt) {
7408 if (IsInstanceMethod)
7409 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7410 else
7411 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7412 }
7413 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007414 Result += "\tstruct _objc_method_list *next_method;\n";
7415 Result += "\tint method_count;\n";
7416 Result += "\tstruct _objc_method method_list[";
7417 Result += utostr(NumMethods);
7418 Result += "];\n} _OBJC_";
7419 Result += prefix;
7420 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7421 Result += "_METHODS_";
7422 Result += ClassName;
7423 Result += " __attribute__ ((used, section (\"__OBJC, __";
7424 Result += IsInstanceMethod ? "inst" : "cls";
7425 Result += "_meth\")))= ";
7426 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007427
Fariborz Jahanian11671902012-02-07 17:11:38 +00007428 Result += "\t,{{(SEL)\"";
7429 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7430 std::string MethodTypeString;
7431 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7432 Result += "\", \"";
7433 Result += MethodTypeString;
7434 Result += "\", (void *)";
7435 Result += MethodInternalNames[*MethodBegin];
7436 Result += "}\n";
7437 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7438 Result += "\t ,{(SEL)\"";
7439 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7440 std::string MethodTypeString;
7441 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7442 Result += "\", \"";
7443 Result += MethodTypeString;
7444 Result += "\", (void *)";
7445 Result += MethodInternalNames[*MethodBegin];
7446 Result += "}\n";
7447 }
7448 Result += "\t }\n};\n";
7449}
7450
7451Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7452 SourceRange OldRange = IV->getSourceRange();
7453 Expr *BaseExpr = IV->getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00007454
Fariborz Jahanian11671902012-02-07 17:11:38 +00007455 // Rewrite the base, but without actually doing replaces.
7456 {
7457 DisableReplaceStmtScope S(*this);
7458 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7459 IV->setBase(BaseExpr);
7460 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007461
Fariborz Jahanian11671902012-02-07 17:11:38 +00007462 ObjCIvarDecl *D = IV->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00007463
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464 Expr *Replacement = IV;
Fangrui Song6907ce22018-07-30 19:24:48 +00007465
Fariborz Jahanian11671902012-02-07 17:11:38 +00007466 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7467 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007468 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007469 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7470 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007471 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007472 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7473 clsDeclared);
7474 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Fangrui Song6907ce22018-07-30 19:24:48 +00007475
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007476 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007477 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007478 if (D->isBitField())
7479 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7480 else
7481 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007482
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007483 ReferencedIvars[clsDeclared].insert(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00007484
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007485 // cast offset to "char *".
Fangrui Song6907ce22018-07-30 19:24:48 +00007486 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007487 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007488 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007489 BaseExpr);
7490 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7491 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007492 Context->UnsignedLongTy, nullptr,
7493 SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00007494 DeclRefExpr *DRE = new (Context)
7495 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7496 VK_LValue, SourceLocation());
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07007497 BinaryOperator *addExpr = BinaryOperator::Create(
7498 *Context, castExpr, DRE, BO_Add,
7499 Context->getPointerType(Context->CharTy), VK_RValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07007500 SourceLocation(), FPOptionsOverride());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007501 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007502 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7503 SourceLocation(),
7504 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007505 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007506 if (D->isBitField())
7507 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007508
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007509 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00007510 RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007511 RD = RD->getDefinition();
7512 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007513 // decltype(((Foo_IMPL*)0)->bar) *
Simon Pilgrim7bfc3bf2020-03-12 16:49:35 +00007514 auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007515 // ivar in class extensions requires special treatment.
7516 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7517 CDecl = CatDecl->getClassInterface();
Benjamin Krameradcd0262020-01-28 20:23:46 +01007518 std::string RecName = std::string(CDecl->getName());
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007519 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007520 RecordDecl *RD = RecordDecl::Create(
7521 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7522 &Context->Idents.get(RecName));
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007523 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00007524 unsigned UnsignedIntSize =
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007525 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7526 Expr *Zero = IntegerLiteral::Create(*Context,
7527 llvm::APInt(UnsignedIntSize, 0),
7528 Context->UnsignedIntTy, SourceLocation());
7529 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7530 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7531 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007532 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007533 SourceLocation(),
7534 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007535 IvarT, nullptr,
7536 /*BitWidth=*/nullptr,
7537 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00007538 MemberExpr *ME = MemberExpr::CreateImplicit(
7539 *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007540 IvarT = Context->getDecltypeType(ME, ME->getType());
7541 }
7542 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007543 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007544 QualType castT = Context->getPointerType(IvarT);
Fangrui Song6907ce22018-07-30 19:24:48 +00007545
7546 castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007547 castT,
7548 CK_BitCast,
7549 PE);
Fangrui Song6907ce22018-07-30 19:24:48 +00007550
Melanie Blowerf4aaed32020-06-26 09:23:45 -07007551 Expr *Exp = UnaryOperator::Create(
7552 const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
7553 VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007554 PE = new (Context) ParenExpr(OldRange.getBegin(),
7555 OldRange.getEnd(),
7556 Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00007557
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007558 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007559 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007560 SourceLocation(),
7561 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007562 D->getType(), nullptr,
7563 /*BitWidth=*/D->getBitWidth(),
7564 /*Mutable=*/true, ICIS_NoInit);
Richard Smithdcf17de2019-06-06 23:24:15 +00007565 MemberExpr *ME =
7566 MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7567 FD->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007568 Replacement = ME;
7569
7570 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007571 else
7572 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007573 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007574
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007575 ReplaceStmtWithRange(IV, Replacement, OldRange);
Fangrui Song6907ce22018-07-30 19:24:48 +00007576 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007577}
Alp Toker0621cb22014-07-16 16:48:33 +00007578
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007579#endif // CLANG_ENABLE_OBJC_REWRITER