blob: 9ed8b1568b980a598b59c46e7fb9cacd9366df6f [file] [log] [blame]
Fariborz Jahanian11671902012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
NAKAMURA Takumi7f633df2017-07-18 08:55:03 +000024#include "clang/Config/config.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000025#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000032#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000033
NAKAMURA Takumid9739822017-10-18 05:21:17 +000034#if CLANG_ENABLE_OBJC_REWRITER
Alp Toker0621cb22014-07-16 16:48:33 +000035
Fariborz Jahanian11671902012-02-07 17:11:38 +000036using namespace clang;
37using llvm::utostr;
38
39namespace {
40 class RewriteModernObjC : public ASTConsumer {
41 protected:
Fangrui Song6907ce22018-07-30 19:24:48 +000042
Fariborz Jahanian11671902012-02-07 17:11:38 +000043 enum {
44 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
45 block, ... */
46 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
Fangrui Song6907ce22018-07-30 19:24:48 +000047 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
Fariborz Jahanian11671902012-02-07 17:11:38 +000048 __block variable */
49 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
50 helpers */
51 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
52 support routines */
53 BLOCK_BYREF_CURRENT_MAX = 256
54 };
Fangrui Song6907ce22018-07-30 19:24:48 +000055
Fariborz Jahanian11671902012-02-07 17:11:38 +000056 enum {
57 BLOCK_NEEDS_FREE = (1 << 24),
58 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
59 BLOCK_HAS_CXX_OBJ = (1 << 26),
60 BLOCK_IS_GC = (1 << 27),
61 BLOCK_IS_GLOBAL = (1 << 28),
62 BLOCK_HAS_DESCRIPTOR = (1 << 29)
63 };
Fangrui Song6907ce22018-07-30 19:24:48 +000064
Fariborz Jahanian11671902012-02-07 17:11:38 +000065 Rewriter Rewrite;
66 DiagnosticsEngine &Diags;
67 const LangOptions &LangOpts;
68 ASTContext *Context;
69 SourceManager *SM;
70 TranslationUnitDecl *TUDecl;
71 FileID MainFileID;
72 const char *MainFileStart, *MainFileEnd;
73 Stmt *CurrentBody;
74 ParentMap *PropParentMap; // created lazily.
75 std::string InFileName;
Peter Collingbourne03f89072016-07-15 00:55:40 +000076 std::unique_ptr<raw_ostream> OutFile;
Fariborz Jahanian11671902012-02-07 17:11:38 +000077 std::string Preamble;
Fangrui Song6907ce22018-07-30 19:24:48 +000078
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 TypeDecl *ProtocolTypeDecl;
80 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000081 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000082 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000083 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000084 // ObjC string constant support.
85 unsigned NumObjCStringLiterals;
86 VarDecl *ConstantStringClassReference;
87 RecordDecl *NSStringRecord;
88
89 // ObjC foreach break/continue generation support.
90 int BcLabelCount;
Fangrui Song6907ce22018-07-30 19:24:48 +000091
Fariborz Jahanian11671902012-02-07 17:11:38 +000092 unsigned TryFinallyContainsReturnDiag;
93 // Needed for super.
94 ObjCMethodDecl *CurMethodDef;
95 RecordDecl *SuperStructDecl;
96 RecordDecl *ConstantStringDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +000097
Fariborz Jahanian11671902012-02-07 17:11:38 +000098 FunctionDecl *MsgSendFunctionDecl;
99 FunctionDecl *MsgSendSuperFunctionDecl;
100 FunctionDecl *MsgSendStretFunctionDecl;
101 FunctionDecl *MsgSendSuperStretFunctionDecl;
102 FunctionDecl *MsgSendFpretFunctionDecl;
103 FunctionDecl *GetClassFunctionDecl;
104 FunctionDecl *GetMetaClassFunctionDecl;
105 FunctionDecl *GetSuperClassFunctionDecl;
106 FunctionDecl *SelGetUidFunctionDecl;
107 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000108 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000109 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000110
111 /* Misc. containers needed for meta-data rewrite. */
112 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
113 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
115 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000116 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000117 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000118 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000119 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
120 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
Fangrui Song6907ce22018-07-30 19:24:48 +0000121
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000122 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000123 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fangrui Song6907ce22018-07-30 19:24:48 +0000124
Fariborz Jahanian11671902012-02-07 17:11:38 +0000125 SmallVector<Stmt *, 32> Stmts;
126 SmallVector<int, 8> ObjCBcLabelNo;
127 // Remember all the @protocol(<expr>) expressions.
128 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000129
Fariborz Jahanian11671902012-02-07 17:11:38 +0000130 llvm::DenseSet<uint64_t> CopyDestroyCache;
131
132 // Block expressions.
133 SmallVector<BlockExpr *, 32> Blocks;
134 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000135 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000136
John McCall113bee02012-03-10 09:33:50 +0000137 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000138
139 // Block related declarations.
140 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142 SmallVector<ValueDecl *, 8> BlockByRefDecls;
143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000147
Fariborz Jahanian11671902012-02-07 17:11:38 +0000148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000149 llvm::DenseMap<ObjCInterfaceDecl *,
Mandeep Singh Granga2baff02017-07-06 18:49:57 +0000150 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
Fangrui Song6907ce22018-07-30 19:24:48 +0000151
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000152 // ivar bitfield grouping containers
153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155 // This container maps an <class, group number for ivar> tuple to the type
156 // of the struct where the bitfield belongs.
157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fangrui Song6907ce22018-07-30 19:24:48 +0000159
Fariborz Jahanian11671902012-02-07 17:11:38 +0000160 // This maps an original source AST to it's rewritten form. This allows
161 // us to avoid rewriting the same node twice (which is very uncommon).
162 // This is needed to support some of the exotic property rewriting.
163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
164
165 // Needed for header files being rewritten
166 bool IsHeader;
167 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000168 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000169 bool objc_impl_method;
Fangrui Song6907ce22018-07-30 19:24:48 +0000170
Fariborz Jahanian11671902012-02-07 17:11:38 +0000171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
174 bool SavedValue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000175
Fariborz Jahanian11671902012-02-07 17:11:38 +0000176 public:
177 DisableReplaceStmtScope(RewriteModernObjC &R)
178 : R(R), SavedValue(R.DisableReplaceStmt) {
179 R.DisableReplaceStmt = true;
180 }
181 ~DisableReplaceStmtScope() {
182 R.DisableReplaceStmt = SavedValue;
183 }
184 };
185 void InitializeCommon(ASTContext &context);
186
187 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Fariborz Jahanian11671902012-02-07 17:11:38 +0000190 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000191 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000192 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
193 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
194 if (!Class->isThisDeclarationADefinition()) {
195 RewriteForwardClassDecl(D);
196 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 } else {
198 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000199 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000200 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000201 }
202 }
203
204 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
205 if (!Proto->isThisDeclarationADefinition()) {
206 RewriteForwardProtocolDecl(D);
207 break;
208 }
209 }
210
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000211 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
212 // Under modern abi, we cannot translate body of the function
213 // yet until all class extensions and its implementation is seen.
214 // This is because they may introduce new bitfields which must go
215 // into their grouping struct.
216 if (FDecl->isThisDeclarationADefinition() &&
217 // Not c functions defined inside an objc container.
218 !FDecl->isTopLevelDeclInObjCContainer()) {
219 FunctionDefinitionsSeen.push_back(FDecl);
220 break;
221 }
222 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000223 HandleTopLevelSingleDecl(*I);
224 }
225 return true;
226 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000227
228 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000229 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
230 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
231 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
232 RewriteBlockPointerDecl(TD);
233 else if (TD->getUnderlyingType()->isFunctionPointerType())
234 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
235 else
236 RewriteObjCQualifiedInterfaceTypes(TD);
237 }
238 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000239 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000240
Fariborz Jahanian11671902012-02-07 17:11:38 +0000241 void HandleTopLevelSingleDecl(Decl *D);
242 void HandleDeclInMainFile(Decl *D);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000243 RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
244 DiagnosticsEngine &D, const LangOptions &LOpts,
245 bool silenceMacroWarn, bool LineInfo);
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000247 ~RewriteModernObjC() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000248
249 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000250
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000252 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000253 }
254
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000257
258 Stmt *ReplacingStmt = ReplacedNodes[Old];
259 if (ReplacingStmt)
260 return; // We can't rewrite the same node twice.
261
Fariborz Jahanian11671902012-02-07 17:11:38 +0000262 if (DisableReplaceStmt)
263 return;
264
265 // Measure the old text.
266 int Size = Rewrite.getRangeSize(SrcRange);
267 if (Size == -1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000268 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
269 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000270 return;
271 }
272 // Get the new text.
273 std::string SStr;
274 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000276 const std::string &Str = S.str();
277
278 // If replacement succeeded or warning disabled return with no warning.
279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280 ReplacedNodes[Old] = New;
281 return;
282 }
283 if (SilenceRewriteMacroWarning)
284 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000285 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
286 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000287 }
288
289 void InsertText(SourceLocation Loc, StringRef Str,
290 bool InsertAfter = true) {
291 // If insertion succeeded or warning disabled return with no warning.
292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293 SilenceRewriteMacroWarning)
294 return;
295
296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297 }
298
299 void ReplaceText(SourceLocation Start, unsigned OrigLength,
300 StringRef Str) {
301 // If removal succeeded or warning disabled return with no warning.
302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303 SilenceRewriteMacroWarning)
304 return;
305
306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307 }
308
309 // Syntactic Rewriting.
310 void RewriteRecordBody(RecordDecl *RD);
311 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000312 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000313 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000315 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fangrui Song6907ce22018-07-30 19:24:48 +0000317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000318 const std::string &typedefString);
319 void RewriteImplementations();
320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321 ObjCImplementationDecl *IMD,
322 ObjCCategoryImplDecl *CID);
323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324 void RewriteImplementationDecl(Decl *Dcl);
325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326 ObjCMethodDecl *MDecl, std::string &ResultStr);
327 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328 const FunctionType *&FPRetType);
329 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330 ValueDecl *VD, bool def=false);
331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000335 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336 void RewriteProperty(ObjCPropertyDecl *prop);
337 void RewriteFunctionDecl(FunctionDecl *FD);
338 void RewriteBlockPointerType(std::string& Str, QualType Type);
339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342 void RewriteTypeOfDecl(VarDecl *VD);
343 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +0000344
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000345 std::string getIvarAccessString(ObjCIvarDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000346
Fariborz Jahanian11671902012-02-07 17:11:38 +0000347 // Expression Rewriting.
348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365 SourceLocation OrigEnd);
366 Stmt *RewriteBreakStmt(BreakStmt *S);
367 Stmt *RewriteContinueStmt(ContinueStmt *S);
368 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000369 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fangrui Song6907ce22018-07-30 19:24:48 +0000370
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000371 // Computes ivar bitfield group no.
372 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
373 // Names field decl. for ivar bitfield group.
374 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
375 // Names struct type for ivar bitfield group.
376 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
377 // Names symbol for ivar bitfield group field offset.
378 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
379 // Given an ivar bitfield, it builds (or finds) its group record type.
380 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
381 QualType SynthesizeBitfieldGroupStructType(
382 ObjCIvarDecl *IV,
383 SmallVectorImpl<ObjCIvarDecl *> &IVars);
Fangrui Song6907ce22018-07-30 19:24:48 +0000384
Fariborz Jahanian11671902012-02-07 17:11:38 +0000385 // Block rewriting.
386 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000387
Fariborz Jahanian11671902012-02-07 17:11:38 +0000388 // Block specific rewrite rules.
389 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000390 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000391 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000392 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
393 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fangrui Song6907ce22018-07-30 19:24:48 +0000394
Fariborz Jahanian11671902012-02-07 17:11:38 +0000395 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000397
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000398 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000399 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000400 bool &IsNamedDefinition);
Fangrui Song6907ce22018-07-30 19:24:48 +0000401 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000402 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000403
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000404 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000405
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000406 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
407 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000408
409 void Initialize(ASTContext &context) override;
410
Benjamin Kramer474261a2012-06-02 10:20:41 +0000411 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000412 // rewriting routines on the new ASTs.
413 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000414 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000415 SourceLocation StartLoc=SourceLocation(),
416 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000417
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000418 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +0000419 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000420 SmallVectorImpl<QualType> &ArgTypes,
421 SmallVectorImpl<Expr*> &MsgExprs,
422 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000423
424 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
425 SourceLocation StartLoc=SourceLocation(),
426 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000427
Fariborz Jahanian11671902012-02-07 17:11:38 +0000428 void SynthCountByEnumWithState(std::string &buf);
429 void SynthMsgSendFunctionDecl();
430 void SynthMsgSendSuperFunctionDecl();
431 void SynthMsgSendStretFunctionDecl();
432 void SynthMsgSendFpretFunctionDecl();
433 void SynthMsgSendSuperStretFunctionDecl();
434 void SynthGetClassFunctionDecl();
435 void SynthGetMetaClassFunctionDecl();
436 void SynthGetSuperClassFunctionDecl();
437 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000438 void SynthSuperConstructorFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000439
Fariborz Jahanian11671902012-02-07 17:11:38 +0000440 // Rewriting metadata
441 template<typename MethodIterator>
442 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
443 MethodIterator MethodEnd,
444 bool IsInstanceMethod,
445 StringRef prefix,
446 StringRef ClassName,
447 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000448 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
449 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000450 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000451 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000452 void RewriteClassSetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000453
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000454 void RewriteMetaDataIntoBuffer(std::string &Result);
455 void WriteImageInfo(std::string &Result);
456 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000457 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000458 void RewriteCategorySetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000459
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000461 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000462 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000463 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000464
Fangrui Song6907ce22018-07-30 19:24:48 +0000465
Fariborz Jahanian11671902012-02-07 17:11:38 +0000466 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
467 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
468 StringRef funcName, std::string Tag);
469 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
470 StringRef funcName, std::string Tag);
Fangrui Song6907ce22018-07-30 19:24:48 +0000471 std::string SynthesizeBlockImpl(BlockExpr *CE,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000472 std::string Tag, std::string Desc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000473 std::string SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string ImplTag,
475 int i, StringRef funcName,
476 unsigned hasCopy);
477 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
478 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
479 StringRef FunName);
480 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
481 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000482 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000483
484 // Misc. helper routines.
485 QualType getProtocolType();
486 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000487 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
488 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
489 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
490
491 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
492 void CollectBlockDeclRefInfo(BlockExpr *Exp);
493 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000494 void GetInnerBlockDeclRefExprs(Stmt *S,
495 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000496 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000497
498 // We avoid calling Type::isBlockPointerType(), since it operates on the
499 // canonical type. We only care if the top-level type is a closure pointer.
500 bool isTopLevelBlockPointerType(QualType T) {
501 return isa<BlockPointerType>(T);
502 }
503
504 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
505 /// to a function pointer type and upon success, returns true; false
506 /// otherwise.
507 bool convertBlockPointerToFunctionPointer(QualType &T) {
508 if (isTopLevelBlockPointerType(T)) {
509 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
510 T = Context->getPointerType(BPT->getPointeeType());
511 return true;
512 }
513 return false;
514 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000515
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000516 bool convertObjCTypeToCStyleType(QualType &T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000517
Fariborz Jahanian11671902012-02-07 17:11:38 +0000518 bool needToScanForQualifiers(QualType T);
519 QualType getSuperStructType();
520 QualType getConstantStringStructType();
521 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000522
Fariborz Jahanian11671902012-02-07 17:11:38 +0000523 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000524 if (T->isObjCQualifiedIdType()) {
525 bool isConst = T.isConstQualified();
Fangrui Song6907ce22018-07-30 19:24:48 +0000526 T = isConst ? Context->getObjCIdType().withConst()
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000527 : Context->getObjCIdType();
528 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000529 else if (T->isObjCQualifiedClassType())
530 T = Context->getObjCClassType();
531 else if (T->isObjCObjectPointerType() &&
532 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
533 if (const ObjCObjectPointerType * OBJPT =
534 T->getAsObjCInterfacePointerType()) {
535 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536 T = QualType(IFaceT, 0);
537 T = Context->getPointerType(T);
538 }
539 }
540 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000541
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 // FIXME: This predicate seems like it would be useful to add to ASTContext.
543 bool isObjCType(QualType T) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000544 if (!LangOpts.ObjC)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000545 return false;
546
547 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
548
549 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550 OCT == Context->getCanonicalType(Context->getObjCClassType()))
551 return true;
552
553 if (const PointerType *PT = OCT->getAs<PointerType>()) {
554 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555 PT->getPointeeType()->isObjCQualifiedIdType())
556 return true;
557 }
558 return false;
559 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000560
Fariborz Jahanian11671902012-02-07 17:11:38 +0000561 bool PointerTypeTakesAnyBlockArguments(QualType QT);
562 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
563 void GetExtentOfArgList(const char *Name, const char *&LParen,
564 const char *&RParen);
Fangrui Song6907ce22018-07-30 19:24:48 +0000565
Fariborz Jahanian11671902012-02-07 17:11:38 +0000566 void QuoteDoublequotes(std::string &From, std::string &To) {
567 for (unsigned i = 0; i < From.length(); i++) {
568 if (From[i] == '"')
569 To += "\\\"";
570 else
571 To += From[i];
572 }
573 }
574
575 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000576 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000577 bool variadic = false) {
578 if (result == Context->getObjCInstanceType())
579 result = Context->getObjCIdType();
580 FunctionProtoType::ExtProtoInfo fpi;
581 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000582 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000583 }
584
585 // Helper function: create a CStyleCastExpr with trivial type source info.
586 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
587 CastKind Kind, Expr *E) {
588 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000589 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
590 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000591 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000592
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000593 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
594 IdentifierInfo* II = &Context->Idents.get("load");
595 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000596 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000597 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000598
599 StringLiteral *getStringLiteral(StringRef Str) {
600 QualType StrType = Context->getConstantArrayType(
601 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
602 0);
603 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
604 /*Pascal=*/false, StrType, SourceLocation());
605 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000606 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000607} // end anonymous namespace
Fariborz Jahanian11671902012-02-07 17:11:38 +0000608
609void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
610 NamedDecl *D) {
611 if (const FunctionProtoType *fproto
612 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000613 for (const auto &I : fproto->param_types())
614 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000615 // All the args are checked/rewritten. Don't call twice!
616 RewriteBlockPointerDecl(D);
617 break;
618 }
619 }
620}
621
622void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
623 const PointerType *PT = funcType->getAs<PointerType>();
624 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
625 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
626}
627
628static bool IsHeaderFile(const std::string &Filename) {
629 std::string::size_type DotPos = Filename.rfind('.');
630
631 if (DotPos == std::string::npos) {
632 // no file extension
633 return false;
634 }
635
636 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
637 // C header: .h
638 // C++ header: .hh or .H;
639 return Ext == "h" || Ext == "hh" || Ext == "H";
640}
641
Peter Collingbourne03f89072016-07-15 00:55:40 +0000642RewriteModernObjC::RewriteModernObjC(std::string inFile,
643 std::unique_ptr<raw_ostream> OS,
644 DiagnosticsEngine &D,
645 const LangOptions &LOpts,
646 bool silenceMacroWarn, bool LineInfo)
647 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
648 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000649 IsHeader = IsHeaderFile(inFile);
650 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
651 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000652 // FIXME. This should be an error. But if block is not called, it is OK. And it
653 // may break including some headers.
654 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655 "rewriting block literal declared in global scope is not implemented");
Fangrui Song6907ce22018-07-30 19:24:48 +0000656
Fariborz Jahanian11671902012-02-07 17:11:38 +0000657 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
658 DiagnosticsEngine::Warning,
659 "rewriter doesn't support user-specified control flow semantics "
660 "for @try/@finally (code may not execute properly)");
661}
662
David Blaikie6beb6aa2014-08-10 19:56:51 +0000663std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000664 const std::string &InFile, std::unique_ptr<raw_ostream> OS,
665 DiagnosticsEngine &Diags, const LangOptions &LOpts,
666 bool SilenceRewriteMacroWarning, bool LineInfo) {
667 return llvm::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
668 LOpts, SilenceRewriteMacroWarning,
669 LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000670}
671
672void RewriteModernObjC::InitializeCommon(ASTContext &context) {
673 Context = &context;
674 SM = &Context->getSourceManager();
675 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000676 MsgSendFunctionDecl = nullptr;
677 MsgSendSuperFunctionDecl = nullptr;
678 MsgSendStretFunctionDecl = nullptr;
679 MsgSendSuperStretFunctionDecl = nullptr;
680 MsgSendFpretFunctionDecl = nullptr;
681 GetClassFunctionDecl = nullptr;
682 GetMetaClassFunctionDecl = nullptr;
683 GetSuperClassFunctionDecl = nullptr;
684 SelGetUidFunctionDecl = nullptr;
685 CFStringFunctionDecl = nullptr;
686 ConstantStringClassReference = nullptr;
687 NSStringRecord = nullptr;
688 CurMethodDef = nullptr;
689 CurFunctionDef = nullptr;
690 GlobalVarDecl = nullptr;
691 GlobalConstructionExp = nullptr;
692 SuperStructDecl = nullptr;
693 ProtocolTypeDecl = nullptr;
694 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000695 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000696 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000697 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000698 PropParentMap = nullptr;
699 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000700 DisableReplaceStmt = false;
701 objc_impl_method = false;
702
703 // Get the ID and start/end of the main file.
704 MainFileID = SM->getMainFileID();
705 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
706 MainFileStart = MainBuf->getBufferStart();
707 MainFileEnd = MainBuf->getBufferEnd();
708
David Blaikiebbafb8a2012-03-11 07:00:24 +0000709 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000710}
711
712//===----------------------------------------------------------------------===//
713// Top Level Driver Code
714//===----------------------------------------------------------------------===//
715
716void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
717 if (Diags.hasErrorOccurred())
718 return;
719
720 // Two cases: either the decl could be in the main file, or it could be in a
721 // #included file. If the former, rewrite it now. If the later, check to see
722 // if we rewrote the #include/#import.
723 SourceLocation Loc = D->getLocation();
724 Loc = SM->getExpansionLoc(Loc);
725
726 // If this is for a builtin, ignore it.
727 if (Loc.isInvalid()) return;
728
729 // Look for built-in declarations that we need to refer during the rewrite.
730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
731 RewriteFunctionDecl(FD);
732 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
733 // declared in <Foundation/NSString.h>
734 if (FVD->getName() == "_NSConstantStringClassReference") {
735 ConstantStringClassReference = FVD;
736 return;
737 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000738 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
739 RewriteCategoryDecl(CD);
740 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
741 if (PD->isThisDeclarationADefinition())
742 RewriteProtocolDecl(PD);
743 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
744 // Recurse into linkage specifications
745 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
746 DIEnd = LSD->decls_end();
747 DI != DIEnd; ) {
748 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
749 if (!IFace->isThisDeclarationADefinition()) {
750 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000751 SourceLocation StartLoc = IFace->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000752 do {
753 if (isa<ObjCInterfaceDecl>(*DI) &&
754 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000755 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000756 DG.push_back(*DI);
757 else
758 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000759
Fariborz Jahanian11671902012-02-07 17:11:38 +0000760 ++DI;
761 } while (DI != DIEnd);
762 RewriteForwardClassDecl(DG);
763 continue;
764 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000765 else {
766 // Keep track of all interface declarations seen.
767 ObjCInterfacesSeen.push_back(IFace);
768 ++DI;
769 continue;
770 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000771 }
772
773 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
774 if (!Proto->isThisDeclarationADefinition()) {
775 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000776 SourceLocation StartLoc = Proto->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000777 do {
778 if (isa<ObjCProtocolDecl>(*DI) &&
779 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000780 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000781 DG.push_back(*DI);
782 else
783 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000784
Fariborz Jahanian11671902012-02-07 17:11:38 +0000785 ++DI;
786 } while (DI != DIEnd);
787 RewriteForwardProtocolDecl(DG);
788 continue;
789 }
790 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000791
Fariborz Jahanian11671902012-02-07 17:11:38 +0000792 HandleTopLevelSingleDecl(*DI);
793 ++DI;
794 }
795 }
796 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000797 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000798 return HandleDeclInMainFile(D);
799}
800
801//===----------------------------------------------------------------------===//
802// Syntactic (non-AST) Rewriting Code
803//===----------------------------------------------------------------------===//
804
805void RewriteModernObjC::RewriteInclude() {
806 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
807 StringRef MainBuf = SM->getBufferData(MainFileID);
808 const char *MainBufStart = MainBuf.begin();
809 const char *MainBufEnd = MainBuf.end();
810 size_t ImportLen = strlen("import");
811
812 // Loop over the whole file, looking for includes.
813 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
814 if (*BufPtr == '#') {
815 if (++BufPtr == MainBufEnd)
816 return;
817 while (*BufPtr == ' ' || *BufPtr == '\t')
818 if (++BufPtr == MainBufEnd)
819 return;
820 if (!strncmp(BufPtr, "import", ImportLen)) {
821 // replace import with include
822 SourceLocation ImportLoc =
823 LocStart.getLocWithOffset(BufPtr-MainBufStart);
824 ReplaceText(ImportLoc, ImportLen, "include");
825 BufPtr += ImportLen;
826 }
827 }
828 }
829}
830
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000831static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
832 ObjCIvarDecl *IvarDecl, std::string &Result) {
833 Result += "OBJC_IVAR_$_";
834 Result += IDecl->getName();
835 Result += "$";
836 Result += IvarDecl->getName();
837}
838
Fangrui Song6907ce22018-07-30 19:24:48 +0000839std::string
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000840RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
841 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +0000842
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000843 // Build name of symbol holding ivar offset.
844 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000845 if (D->isBitField())
846 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
847 else
848 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +0000849
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850 std::string S = "(*(";
851 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000852 if (D->isBitField())
853 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000854
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000855 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
856 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
857 RD = RD->getDefinition();
858 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
859 // decltype(((Foo_IMPL*)0)->bar) *
Fangrui Song6907ce22018-07-30 19:24:48 +0000860 ObjCContainerDecl *CDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000861 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
862 // ivar in class extensions requires special treatment.
863 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
864 CDecl = CatDecl->getClassInterface();
865 std::string RecName = CDecl->getName();
866 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000867 RecordDecl *RD =
868 RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
869 SourceLocation(), &Context->Idents.get(RecName));
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000870 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +0000871 unsigned UnsignedIntSize =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000872 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
873 Expr *Zero = IntegerLiteral::Create(*Context,
874 llvm::APInt(UnsignedIntSize, 0),
875 Context->UnsignedIntTy, SourceLocation());
876 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
877 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
878 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000879 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000880 SourceLocation(),
881 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000882 IvarT, nullptr,
883 /*BitWidth=*/nullptr, /*Mutable=*/true,
884 ICIS_NoInit);
885 MemberExpr *ME = new (Context)
886 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
887 FD->getType(), VK_LValue, OK_Ordinary);
888 IvarT = Context->getDecltypeType(ME, ME->getType());
889 }
890 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000891 convertObjCTypeToCStyleType(IvarT);
892 QualType castT = Context->getPointerType(IvarT);
893 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
894 S += TypeString;
895 S += ")";
Fangrui Song6907ce22018-07-30 19:24:48 +0000896
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000897 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
898 S += "((char *)self + ";
899 S += IvarOffsetName;
900 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000901 if (D->isBitField()) {
902 S += ".";
903 S += D->getNameAsString();
904 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000905 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000906 return S;
907}
908
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000909/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
910/// been found in the class implementation. In this case, it must be synthesized.
911static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
912 ObjCPropertyDecl *PD,
913 bool getter) {
914 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
915 : !IMP->getInstanceMethod(PD->getSetterName());
Fangrui Song6907ce22018-07-30 19:24:48 +0000916
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000917}
918
Fariborz Jahanian11671902012-02-07 17:11:38 +0000919void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
920 ObjCImplementationDecl *IMD,
921 ObjCCategoryImplDecl *CID) {
922 static bool objcGetPropertyDefined = false;
923 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000924 SourceLocation startGetterSetterLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +0000925
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000926 if (PID->getBeginLoc().isValid()) {
927 SourceLocation startLoc = PID->getBeginLoc();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000928 InsertText(startLoc, "// ");
929 const char *startBuf = SM->getCharacterData(startLoc);
930 assert((*startBuf == '@') && "bogus @synthesize location");
931 const char *semiBuf = strchr(startBuf, ';');
932 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
933 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000934 } else
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000935 startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000936
937 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
938 return; // FIXME: is this correct?
939
940 // Generate the 'getter' function.
941 ObjCPropertyDecl *PD = PID->getPropertyDecl();
942 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000943 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000944
Bill Wendling44426052012-12-20 19:22:21 +0000945 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000946 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000947 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000948 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000949 ObjCPropertyDecl::OBJC_PR_copy));
950 std::string Getr;
951 if (GenGetProperty && !objcGetPropertyDefined) {
952 objcGetPropertyDefined = true;
953 // FIXME. Is this attribute correct in all cases?
954 Getr = "\nextern \"C\" __declspec(dllimport) "
955 "id objc_getProperty(id, SEL, long, bool);\n";
956 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000957 RewriteObjCMethodDecl(OID->getContainingInterface(),
Fariborz Jahanian11671902012-02-07 17:11:38 +0000958 PD->getGetterMethodDecl(), Getr);
959 Getr += "{ ";
960 // Synthesize an explicit cast to gain access to the ivar.
961 // See objc-act.c:objc_synthesize_new_getter() for details.
962 if (GenGetProperty) {
963 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
964 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000965 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000966 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000967 FPRetType);
968 Getr += " _TYPE";
969 if (FPRetType) {
970 Getr += ")"; // close the precedence "scope" for "*".
Fangrui Song6907ce22018-07-30 19:24:48 +0000971
Fariborz Jahanian11671902012-02-07 17:11:38 +0000972 // Now, emit the argument types (if any).
973 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
974 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000975 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000976 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000977 std::string ParamStr =
978 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000979 Getr += ParamStr;
980 }
981 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000982 if (FT->getNumParams())
983 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000984 Getr += "...";
985 }
986 Getr += ")";
987 } else
988 Getr += "()";
989 }
990 Getr += ";\n";
991 Getr += "return (_TYPE)";
992 Getr += "objc_getProperty(self, _cmd, ";
993 RewriteIvarOffsetComputation(OID, Getr);
994 Getr += ", 1)";
995 }
996 else
997 Getr += "return " + getIvarAccessString(OID);
998 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000999 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001000 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001001
1002 if (PD->isReadOnly() ||
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001003 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001004 return;
1005
1006 // Generate the 'setter' function.
1007 std::string Setr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001008 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001009 ObjCPropertyDecl::OBJC_PR_copy);
1010 if (GenSetProperty && !objcSetPropertyDefined) {
1011 objcSetPropertyDefined = true;
1012 // FIXME. Is this attribute correct in all cases?
1013 Setr = "\nextern \"C\" __declspec(dllimport) "
1014 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1015 }
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00001016
Fangrui Song6907ce22018-07-30 19:24:48 +00001017 RewriteObjCMethodDecl(OID->getContainingInterface(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001018 PD->getSetterMethodDecl(), Setr);
1019 Setr += "{ ";
1020 // Synthesize an explicit cast to initialize the ivar.
1021 // See objc-act.c:objc_synthesize_new_setter() for details.
1022 if (GenSetProperty) {
1023 Setr += "objc_setProperty (self, _cmd, ";
1024 RewriteIvarOffsetComputation(OID, Setr);
1025 Setr += ", (id)";
1026 Setr += PD->getName();
1027 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001028 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001029 Setr += "0, ";
1030 else
1031 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001032 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001033 Setr += "1)";
1034 else
1035 Setr += "0)";
1036 }
1037 else {
1038 Setr += getIvarAccessString(OID) + " = ";
1039 Setr += PD->getName();
1040 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001041 Setr += "; }\n";
1042 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001043}
1044
1045static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1046 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001047 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "#define _REWRITER_typedef_";
1051 typedefString += ForwardDecl->getNameAsString();
1052 typedefString += "\n";
1053 typedefString += "typedef struct objc_object ";
1054 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001055 // typedef struct { } _objc_exc_Classname;
1056 typedefString += ";\ntypedef struct {} _objc_exc_";
1057 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001058 typedefString += ";\n#endif\n";
1059}
1060
1061void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1062 const std::string &typedefString) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001063 SourceLocation startLoc = ClassDecl->getBeginLoc();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001064 const char *startBuf = SM->getCharacterData(startLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001065 const char *semiPtr = strchr(startBuf, ';');
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001066 // Replace the @class with typedefs corresponding to the classes.
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001068}
1069
1070void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1071 std::string typedefString;
1072 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001073 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1074 if (I == D.begin()) {
1075 // Translate to typedef's that forward reference structs with the same name
1076 // as the class. As a convenience, we include the original declaration
1077 // as a comment.
1078 typedefString += "// @class ";
1079 typedefString += ForwardDecl->getNameAsString();
1080 typedefString += ";";
1081 }
1082 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001083 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001084 else
1085 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001086 }
1087 DeclGroupRef::iterator I = D.begin();
1088 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1089}
1090
1091void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001092 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001093 std::string typedefString;
1094 for (unsigned i = 0; i < D.size(); i++) {
1095 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1096 if (i == 0) {
1097 typedefString += "// @class ";
1098 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001099 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001100 }
1101 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1102 }
1103 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1104}
1105
1106void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1107 // When method is a synthesized one, such as a getter/setter there is
1108 // nothing to rewrite.
1109 if (Method->isImplicit())
1110 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001111 SourceLocation LocStart = Method->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001112 SourceLocation LocEnd = Method->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001113
1114 if (SM->getExpansionLineNumber(LocEnd) >
1115 SM->getExpansionLineNumber(LocStart)) {
1116 InsertText(LocStart, "#if 0\n");
1117 ReplaceText(LocEnd, 1, ";\n#endif\n");
1118 } else {
1119 InsertText(LocStart, "// ");
1120 }
1121}
1122
1123void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1124 SourceLocation Loc = prop->getAtLoc();
1125
1126 ReplaceText(Loc, 0, "// ");
1127 // FIXME: handle properties that are declared across multiple lines.
1128}
1129
1130void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001131 SourceLocation LocStart = CatDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001132
1133 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001134 if (CatDecl->getIvarRBraceLoc().isValid()) {
1135 ReplaceText(LocStart, 1, "/** ");
1136 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1137 }
1138 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001139 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001140 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001141
Manman Rena7a8b1f2016-01-26 18:05:23 +00001142 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001143 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001144
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001145 for (auto *I : CatDecl->instance_methods())
1146 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001147 for (auto *I : CatDecl->class_methods())
1148 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001149
1150 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001151 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001152 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001153}
1154
1155void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001156 SourceLocation LocStart = PDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001157 assert(PDecl->isThisDeclarationADefinition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001158
Fariborz Jahanian11671902012-02-07 17:11:38 +00001159 // FIXME: handle protocol headers that are declared across multiple lines.
1160 ReplaceText(LocStart, 0, "// ");
1161
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001162 for (auto *I : PDecl->instance_methods())
1163 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001164 for (auto *I : PDecl->class_methods())
1165 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001166 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001167 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001168
Fariborz Jahanian11671902012-02-07 17:11:38 +00001169 // Lastly, comment out the @end.
1170 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001171 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001172
1173 // Must comment out @optional/@required
1174 const char *startBuf = SM->getCharacterData(LocStart);
1175 const char *endBuf = SM->getCharacterData(LocEnd);
1176 for (const char *p = startBuf; p < endBuf; p++) {
1177 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1178 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1179 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1180
1181 }
1182 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1183 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1184 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1185
1186 }
1187 }
1188}
1189
1190void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001191 SourceLocation LocStart = (*D.begin())->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001192 if (LocStart.isInvalid())
1193 llvm_unreachable("Invalid SourceLocation");
1194 // FIXME: handle forward protocol that are declared across multiple lines.
1195 ReplaceText(LocStart, 0, "// ");
1196}
1197
Fangrui Song6907ce22018-07-30 19:24:48 +00001198void
Craig Topper5603df42013-07-05 19:34:19 +00001199RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001200 SourceLocation LocStart = DG[0]->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001201 if (LocStart.isInvalid())
1202 llvm_unreachable("Invalid SourceLocation");
1203 // FIXME: handle forward protocol that are declared across multiple lines.
1204 ReplaceText(LocStart, 0, "// ");
1205}
1206
1207void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1208 const FunctionType *&FPRetType) {
1209 if (T->isObjCQualifiedIdType())
1210 ResultStr += "id";
1211 else if (T->isFunctionPointerType() ||
1212 T->isBlockPointerType()) {
1213 // needs special handling, since pointer-to-functions have special
1214 // syntax (where a decaration models use).
1215 QualType retType = T;
1216 QualType PointeeTy;
1217 if (const PointerType* PT = retType->getAs<PointerType>())
1218 PointeeTy = PT->getPointeeType();
1219 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1220 PointeeTy = BPT->getPointeeType();
1221 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001222 ResultStr +=
1223 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001224 ResultStr += "(*";
1225 }
1226 } else
1227 ResultStr += T.getAsString(Context->getPrintingPolicy());
1228}
1229
1230void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1231 ObjCMethodDecl *OMD,
1232 std::string &ResultStr) {
1233 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001234 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001235 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001236 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001237 ResultStr += " ";
1238
1239 // Unique method name
1240 std::string NameStr;
1241
1242 if (OMD->isInstanceMethod())
1243 NameStr += "_I_";
1244 else
1245 NameStr += "_C_";
1246
1247 NameStr += IDecl->getNameAsString();
1248 NameStr += "_";
1249
1250 if (ObjCCategoryImplDecl *CID =
1251 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1252 NameStr += CID->getNameAsString();
1253 NameStr += "_";
1254 }
1255 // Append selector names, replacing ':' with '_'
1256 {
1257 std::string selString = OMD->getSelector().getAsString();
1258 int len = selString.size();
1259 for (int i = 0; i < len; i++)
1260 if (selString[i] == ':')
1261 selString[i] = '_';
1262 NameStr += selString;
1263 }
1264 // Remember this name for metadata emission
1265 MethodInternalNames[OMD] = NameStr;
1266 ResultStr += NameStr;
1267
1268 // Rewrite arguments
1269 ResultStr += "(";
1270
1271 // invisible arguments
1272 if (OMD->isInstanceMethod()) {
1273 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1274 selfTy = Context->getPointerType(selfTy);
1275 if (!LangOpts.MicrosoftExt) {
1276 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1277 ResultStr += "struct ";
1278 }
1279 // When rewriting for Microsoft, explicitly omit the structure name.
1280 ResultStr += IDecl->getNameAsString();
1281 ResultStr += " *";
1282 }
1283 else
1284 ResultStr += Context->getObjCClassType().getAsString(
1285 Context->getPrintingPolicy());
1286
1287 ResultStr += " self, ";
1288 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1289 ResultStr += " _cmd";
1290
1291 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001292 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001293 ResultStr += ", ";
1294 if (PDecl->getType()->isObjCQualifiedIdType()) {
1295 ResultStr += "id ";
1296 ResultStr += PDecl->getNameAsString();
1297 } else {
1298 std::string Name = PDecl->getNameAsString();
1299 QualType QT = PDecl->getType();
1300 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001301 (void)convertBlockPointerToFunctionPointer(QT);
1302 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001303 ResultStr += Name;
1304 }
1305 }
1306 if (OMD->isVariadic())
1307 ResultStr += ", ...";
1308 ResultStr += ") ";
1309
1310 if (FPRetType) {
1311 ResultStr += ")"; // close the precedence "scope" for "*".
1312
1313 // Now, emit the argument types (if any).
1314 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1315 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001317 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001318 std::string ParamStr =
1319 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001320 ResultStr += ParamStr;
1321 }
1322 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001323 if (FT->getNumParams())
1324 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001325 ResultStr += "...";
1326 }
1327 ResultStr += ")";
1328 } else {
1329 ResultStr += "()";
1330 }
1331 }
1332}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001333
Fariborz Jahanian11671902012-02-07 17:11:38 +00001334void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1335 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1336 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1337
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001338 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001339 if (IMD->getIvarRBraceLoc().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001340 ReplaceText(IMD->getBeginLoc(), 1, "/** ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001341 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001342 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001343 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001344 InsertText(IMD->getBeginLoc(), "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001345 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001346 }
1347 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001348 InsertText(CID->getBeginLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001349
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001350 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001351 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001352 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001353 SourceLocation LocStart = OMD->getBeginLoc();
1354 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001355
1356 const char *startBuf = SM->getCharacterData(LocStart);
1357 const char *endBuf = SM->getCharacterData(LocEnd);
1358 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1359 }
1360
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001361 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001363 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001364 SourceLocation LocStart = OMD->getBeginLoc();
1365 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001366
1367 const char *startBuf = SM->getCharacterData(LocStart);
1368 const char *endBuf = SM->getCharacterData(LocEnd);
1369 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1370 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001371 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1372 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001373
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001374 InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001375}
1376
1377void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001378 // Do not synthesize more than once.
1379 if (ObjCSynthesizedStructs.count(ClassDecl))
1380 return;
1381 // Make sure super class's are written before current class is written.
1382 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1383 while (SuperClass) {
1384 RewriteInterfaceDecl(SuperClass);
1385 SuperClass = SuperClass->getSuperClass();
1386 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001387 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001388 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001389 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001390 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001391 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
Fangrui Song6907ce22018-07-30 19:24:48 +00001392
Fariborz Jahanianff513382012-02-15 22:01:47 +00001393 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001394 // Mark this typedef as having been written into its c++ equivalent.
1395 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001396
Manman Rena7a8b1f2016-01-26 18:05:23 +00001397 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001398 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001399 for (auto *I : ClassDecl->instance_methods())
1400 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001401 for (auto *I : ClassDecl->class_methods())
1402 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001403
Fariborz Jahanianff513382012-02-15 22:01:47 +00001404 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001405 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001406 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001407 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001408}
1409
1410Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1411 SourceRange OldRange = PseudoOp->getSourceRange();
1412
1413 // We just magically know some things about the structure of this
1414 // expression.
1415 ObjCMessageExpr *OldMsg =
1416 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1417 PseudoOp->getNumSemanticExprs() - 1));
1418
1419 // Because the rewriter doesn't allow us to rewrite rewritten code,
1420 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001421 Expr *Base;
1422 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001423 {
1424 DisableReplaceStmtScope S(*this);
1425
1426 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001427 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001428 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1429 Base = OldMsg->getInstanceReceiver();
1430 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1431 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1432 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001433
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001434 unsigned numArgs = OldMsg->getNumArgs();
1435 for (unsigned i = 0; i < numArgs; i++) {
1436 Expr *Arg = OldMsg->getArg(i);
1437 if (isa<OpaqueValueExpr>(Arg))
1438 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1439 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1440 Args.push_back(Arg);
1441 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001442 }
1443
1444 // TODO: avoid this copy.
1445 SmallVector<SourceLocation, 1> SelLocs;
1446 OldMsg->getSelectorLocs(SelLocs);
1447
Craig Topper8ae12032014-05-07 06:21:57 +00001448 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001449 switch (OldMsg->getReceiverKind()) {
1450 case ObjCMessageExpr::Class:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getClassReceiverTypeInfo(),
1455 OldMsg->getSelector(),
1456 SelLocs,
1457 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001458 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1461 break;
1462
1463 case ObjCMessageExpr::Instance:
1464 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1465 OldMsg->getValueKind(),
1466 OldMsg->getLeftLoc(),
1467 Base,
1468 OldMsg->getSelector(),
1469 SelLocs,
1470 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001471 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1474 break;
1475
1476 case ObjCMessageExpr::SuperClass:
1477 case ObjCMessageExpr::SuperInstance:
1478 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1479 OldMsg->getValueKind(),
1480 OldMsg->getLeftLoc(),
1481 OldMsg->getSuperLoc(),
1482 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1483 OldMsg->getSuperType(),
1484 OldMsg->getSelector(),
1485 SelLocs,
1486 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001487 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001488 OldMsg->getRightLoc(),
1489 OldMsg->isImplicit());
1490 break;
1491 }
1492
1493 Stmt *Replacement = SynthMessageExpr(NewMsg);
1494 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1495 return Replacement;
1496}
1497
1498Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1499 SourceRange OldRange = PseudoOp->getSourceRange();
1500
1501 // We just magically know some things about the structure of this
1502 // expression.
1503 ObjCMessageExpr *OldMsg =
1504 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1505
1506 // Because the rewriter doesn't allow us to rewrite rewritten code,
1507 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001508 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001509 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001510 {
1511 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001512 // Rebuild the base expression if we have one.
1513 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1514 Base = OldMsg->getInstanceReceiver();
1515 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1516 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1517 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001518 unsigned numArgs = OldMsg->getNumArgs();
1519 for (unsigned i = 0; i < numArgs; i++) {
1520 Expr *Arg = OldMsg->getArg(i);
1521 if (isa<OpaqueValueExpr>(Arg))
1522 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1523 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1524 Args.push_back(Arg);
1525 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001526 }
1527
1528 // Intentionally empty.
1529 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001530
Craig Topper8ae12032014-05-07 06:21:57 +00001531 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001532 switch (OldMsg->getReceiverKind()) {
1533 case ObjCMessageExpr::Class:
1534 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1535 OldMsg->getValueKind(),
1536 OldMsg->getLeftLoc(),
1537 OldMsg->getClassReceiverTypeInfo(),
1538 OldMsg->getSelector(),
1539 SelLocs,
1540 OldMsg->getMethodDecl(),
1541 Args,
1542 OldMsg->getRightLoc(),
1543 OldMsg->isImplicit());
1544 break;
1545
1546 case ObjCMessageExpr::Instance:
1547 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1548 OldMsg->getValueKind(),
1549 OldMsg->getLeftLoc(),
1550 Base,
1551 OldMsg->getSelector(),
1552 SelLocs,
1553 OldMsg->getMethodDecl(),
1554 Args,
1555 OldMsg->getRightLoc(),
1556 OldMsg->isImplicit());
1557 break;
1558
1559 case ObjCMessageExpr::SuperClass:
1560 case ObjCMessageExpr::SuperInstance:
1561 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1562 OldMsg->getValueKind(),
1563 OldMsg->getLeftLoc(),
1564 OldMsg->getSuperLoc(),
1565 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1566 OldMsg->getSuperType(),
1567 OldMsg->getSelector(),
1568 SelLocs,
1569 OldMsg->getMethodDecl(),
1570 Args,
1571 OldMsg->getRightLoc(),
1572 OldMsg->isImplicit());
1573 break;
1574 }
1575
1576 Stmt *Replacement = SynthMessageExpr(NewMsg);
1577 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1578 return Replacement;
1579}
1580
1581/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001582/// ((NSUInteger (*)
1583/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001584/// (void *)objc_msgSend)((id)l_collection,
1585/// sel_registerName(
1586/// "countByEnumeratingWithState:objects:count:"),
1587/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001588/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001589///
1590void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001591 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1592 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001593 buf += "\n\t\t";
1594 buf += "((id)l_collection,\n\t\t";
1595 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1596 buf += "\n\t\t";
1597 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001598 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001599}
1600
1601/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1602/// statement to exit to its outer synthesized loop.
1603///
1604Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1605 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1606 return S;
1607 // replace break with goto __break_label
1608 std::string buf;
1609
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001610 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001611 buf = "goto __break_label_";
1612 buf += utostr(ObjCBcLabelNo.back());
1613 ReplaceText(startLoc, strlen("break"), buf);
1614
Craig Topper8ae12032014-05-07 06:21:57 +00001615 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001616}
1617
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001618void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1619 SourceLocation Loc,
1620 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001621 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001622 LineString += "\n#line ";
1623 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1624 LineString += utostr(PLoc.getLine());
1625 LineString += " \"";
1626 LineString += Lexer::Stringify(PLoc.getFilename());
1627 LineString += "\"\n";
1628 }
1629}
1630
Fariborz Jahanian11671902012-02-07 17:11:38 +00001631/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1632/// statement to continue with its inner synthesized loop.
1633///
1634Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1635 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1636 return S;
1637 // replace continue with goto __continue_label
1638 std::string buf;
1639
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001640 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001641 buf = "goto __continue_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 ReplaceText(startLoc, strlen("continue"), buf);
1644
Craig Topper8ae12032014-05-07 06:21:57 +00001645 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001646}
1647
1648/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1649/// It rewrites:
1650/// for ( type elem in collection) { stmts; }
1651
1652/// Into:
1653/// {
1654/// type elem;
1655/// struct __objcFastEnumerationState enumState = { 0 };
1656/// id __rw_items[16];
1657/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001658/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001659/// objects:__rw_items count:16];
1660/// if (limit) {
1661/// unsigned long startMutations = *enumState.mutationsPtr;
1662/// do {
1663/// unsigned long counter = 0;
1664/// do {
1665/// if (startMutations != *enumState.mutationsPtr)
1666/// objc_enumerationMutation(l_collection);
1667/// elem = (type)enumState.itemsPtr[counter++];
1668/// stmts;
1669/// __continue_label: ;
1670/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001671/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1672/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001673/// elem = nil;
1674/// __break_label: ;
1675/// }
1676/// else
1677/// elem = nil;
1678/// }
1679///
1680Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1681 SourceLocation OrigEnd) {
1682 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1683 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1684 "ObjCForCollectionStmt Statement stack mismatch");
1685 assert(!ObjCBcLabelNo.empty() &&
1686 "ObjCForCollectionStmt - Label No stack empty");
1687
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001688 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001689 const char *startBuf = SM->getCharacterData(startLoc);
1690 StringRef elementName;
1691 std::string elementTypeAsString;
1692 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001693 // line directive first.
1694 SourceLocation ForEachLoc = S->getForLoc();
1695 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1696 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001697 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1698 // type elem;
1699 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1700 QualType ElementType = cast<ValueDecl>(D)->getType();
1701 if (ElementType->isObjCQualifiedIdType() ||
1702 ElementType->isObjCQualifiedInterfaceType())
1703 // Simply use 'id' for all qualified types.
1704 elementTypeAsString = "id";
1705 else
1706 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1707 buf += elementTypeAsString;
1708 buf += " ";
1709 elementName = D->getName();
1710 buf += elementName;
1711 buf += ";\n\t";
1712 }
1713 else {
1714 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1715 elementName = DR->getDecl()->getName();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001716 ValueDecl *VD = DR->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001717 if (VD->getType()->isObjCQualifiedIdType() ||
1718 VD->getType()->isObjCQualifiedInterfaceType())
1719 // Simply use 'id' for all qualified types.
1720 elementTypeAsString = "id";
1721 else
1722 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1723 }
1724
1725 // struct __objcFastEnumerationState enumState = { 0 };
1726 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1727 // id __rw_items[16];
1728 buf += "id __rw_items[16];\n\t";
1729 // id l_collection = (id)
1730 buf += "id l_collection = (id)";
1731 // Find start location of 'collection' the hard way!
1732 const char *startCollectionBuf = startBuf;
1733 startCollectionBuf += 3; // skip 'for'
1734 startCollectionBuf = strchr(startCollectionBuf, '(');
1735 startCollectionBuf++; // skip '('
1736 // find 'in' and skip it.
1737 while (*startCollectionBuf != ' ' ||
1738 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1739 (*(startCollectionBuf+3) != ' ' &&
1740 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1741 startCollectionBuf++;
1742 startCollectionBuf += 3;
1743
1744 // Replace: "for (type element in" with string constructed thus far.
1745 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1746 // Replace ')' in for '(' type elem in collection ')' with ';'
1747 SourceLocation rightParenLoc = S->getRParenLoc();
1748 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1749 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1750 buf = ";\n\t";
1751
1752 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1753 // objects:__rw_items count:16];
1754 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001755 // NSUInteger limit =
1756 // ((NSUInteger (*)
1757 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001758 // (void *)objc_msgSend)((id)l_collection,
1759 // sel_registerName(
1760 // "countByEnumeratingWithState:objects:count:"),
1761 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001762 // (id *)__rw_items, (NSUInteger)16);
1763 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001764 SynthCountByEnumWithState(buf);
1765 buf += ";\n\t";
1766 /// if (limit) {
1767 /// unsigned long startMutations = *enumState.mutationsPtr;
1768 /// do {
1769 /// unsigned long counter = 0;
1770 /// do {
1771 /// if (startMutations != *enumState.mutationsPtr)
1772 /// objc_enumerationMutation(l_collection);
1773 /// elem = (type)enumState.itemsPtr[counter++];
1774 buf += "if (limit) {\n\t";
1775 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1776 buf += "do {\n\t\t";
1777 buf += "unsigned long counter = 0;\n\t\t";
1778 buf += "do {\n\t\t\t";
1779 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1780 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1781 buf += elementName;
1782 buf += " = (";
1783 buf += elementTypeAsString;
1784 buf += ")enumState.itemsPtr[counter++];";
1785 // Replace ')' in for '(' type elem in collection ')' with all of these.
1786 ReplaceText(lparenLoc, 1, buf);
1787
1788 /// __continue_label: ;
1789 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001790 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1791 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001792 /// elem = nil;
1793 /// __break_label: ;
1794 /// }
1795 /// else
1796 /// elem = nil;
1797 /// }
1798 ///
1799 buf = ";\n\t";
1800 buf += "__continue_label_";
1801 buf += utostr(ObjCBcLabelNo.back());
1802 buf += ": ;";
1803 buf += "\n\t\t";
1804 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001805 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001806 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001807 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001808 buf += elementName;
1809 buf += " = ((";
1810 buf += elementTypeAsString;
1811 buf += ")0);\n\t";
1812 buf += "__break_label_";
1813 buf += utostr(ObjCBcLabelNo.back());
1814 buf += ": ;\n\t";
1815 buf += "}\n\t";
1816 buf += "else\n\t\t";
1817 buf += elementName;
1818 buf += " = ((";
1819 buf += elementTypeAsString;
1820 buf += ")0);\n\t";
1821 buf += "}\n";
1822
1823 // Insert all these *after* the statement body.
1824 // FIXME: If this should support Obj-C++, support CXXTryStmt
1825 if (isa<CompoundStmt>(S->getBody())) {
1826 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1827 InsertText(endBodyLoc, buf);
1828 } else {
1829 /* Need to treat single statements specially. For example:
1830 *
1831 * for (A *a in b) if (stuff()) break;
1832 * for (A *a in b) xxxyy;
1833 *
1834 * The following code simply scans ahead to the semi to find the actual end.
1835 */
1836 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1837 const char *semiBuf = strchr(stmtBuf, ';');
1838 assert(semiBuf && "Can't find ';'");
1839 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1840 InsertText(endBodyLoc, buf);
1841 }
1842 Stmts.pop_back();
1843 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001844 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001845}
1846
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001847static void Write_RethrowObject(std::string &buf) {
1848 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1849 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1850 buf += "\tid rethrow;\n";
1851 buf += "\t} _fin_force_rethow(_rethrow);";
1852}
1853
Fariborz Jahanian11671902012-02-07 17:11:38 +00001854/// RewriteObjCSynchronizedStmt -
1855/// This routine rewrites @synchronized(expr) stmt;
1856/// into:
1857/// objc_sync_enter(expr);
1858/// @try stmt @finally { objc_sync_exit(expr); }
1859///
1860Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1861 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001862 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001863 const char *startBuf = SM->getCharacterData(startLoc);
1864
1865 assert((*startBuf == '@') && "bogus @synchronized location");
1866
1867 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001868 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1869 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001870 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fangrui Song6907ce22018-07-30 19:24:48 +00001871
Fariborz Jahanian11671902012-02-07 17:11:38 +00001872 const char *lparenBuf = startBuf;
1873 while (*lparenBuf != '(') lparenBuf++;
1874 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001875
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001876 buf = "; objc_sync_enter(_sync_obj);\n";
1877 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1878 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1879 buf += "\n\tid sync_exit;";
1880 buf += "\n\t} _sync_exit(_sync_obj);\n";
1881
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001882 // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001883 // the sync expression is typically a message expression that's already
1884 // been rewritten! (which implies the SourceLocation's are invalid).
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001885 SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001886 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1887 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1888 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001889
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001890 SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001891 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1892 assert (*LBraceLocBuf == '{');
1893 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001894
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001895 SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001896 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1897 "bogus @synchronized block");
Fangrui Song6907ce22018-07-30 19:24:48 +00001898
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001899 buf = "} catch (id e) {_rethrow = e;}\n";
1900 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001901 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001902 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001903
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001904 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001905
Craig Topper8ae12032014-05-07 06:21:57 +00001906 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001907}
1908
1909void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1910{
1911 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001912 for (Stmt *SubStmt : S->children())
1913 if (SubStmt)
1914 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001915
1916 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001917 Diags.Report(Context->getFullLoc(S->getBeginLoc()),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001918 TryFinallyContainsReturnDiag);
1919 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001920}
1921
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001922Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1923 SourceLocation startLoc = S->getAtLoc();
1924 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001925 ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001926 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001927
1928 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001929}
1930
Fariborz Jahanian11671902012-02-07 17:11:38 +00001931Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001932 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001933 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001934 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001935 SourceLocation TryLocation = S->getAtTryLoc();
1936 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001937
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001938 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001939 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001940 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001941 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001942 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001943 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001944 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001945 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001946 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001947 const char *startBuf = SM->getCharacterData(startLoc);
1948
1949 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001950 if (finalStmt)
1951 ReplaceText(startLoc, 1, buf);
1952 else
1953 // @try -> try
1954 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00001955
Fariborz Jahanian11671902012-02-07 17:11:38 +00001956 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1957 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001958 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001959
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001960 startLoc = Catch->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001961 bool AtRemoved = false;
1962 if (catchDecl) {
1963 QualType t = catchDecl->getType();
1964 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1965 // Should be a pointer to a class.
1966 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1967 if (IDecl) {
1968 std::string Result;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001969 ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00001970
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001971 startBuf = SM->getCharacterData(startLoc);
1972 assert((*startBuf == '@') && "bogus @catch location");
1973 SourceLocation rParenLoc = Catch->getRParenLoc();
1974 const char *rParenBuf = SM->getCharacterData(rParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001975
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001976 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001977 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001978 Result += " *_"; Result += catchDecl->getNameAsString();
1979 Result += ")";
1980 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1981 // Foo *e = (Foo *)_e;
1982 Result.clear();
1983 Result = "{ ";
1984 Result += IDecl->getNameAsString();
1985 Result += " *"; Result += catchDecl->getNameAsString();
1986 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1987 Result += "_"; Result += catchDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00001988
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001989 Result += "; ";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001990 SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001991 ReplaceText(lBraceLoc, 1, Result);
1992 AtRemoved = true;
1993 }
1994 }
1995 }
1996 if (!AtRemoved)
1997 // @catch -> catch
1998 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00001999
Fariborz Jahanian11671902012-02-07 17:11:38 +00002000 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002001 if (finalStmt) {
2002 buf.clear();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002003 SourceLocation FinallyLoc = finalStmt->getBeginLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002004
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002005 if (noCatch) {
2006 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2007 buf += "catch (id e) {_rethrow = e;}\n";
2008 }
2009 else {
2010 buf += "}\n";
2011 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2012 buf += "catch (id e) {_rethrow = e;}\n";
2013 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002014
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002015 SourceLocation startFinalLoc = finalStmt->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002016 ReplaceText(startFinalLoc, 8, buf);
2017 Stmt *body = finalStmt->getFinallyBody();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002018 SourceLocation startFinalBodyLoc = body->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002019 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002020 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002021 ReplaceText(startFinalBodyLoc, 1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00002022
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002023 SourceLocation endFinalBodyLoc = body->getEndLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002024 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002025 // Now check for any return/continue/go statements within the @try.
2026 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002027 }
2028
Craig Topper8ae12032014-05-07 06:21:57 +00002029 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002030}
2031
2032// This can't be done with ReplaceStmt(S, ThrowExpr), since
2033// the throw expression is typically a message expression that's already
2034// been rewritten! (which implies the SourceLocation's are invalid).
2035Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2036 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002037 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002038 const char *startBuf = SM->getCharacterData(startLoc);
2039
2040 assert((*startBuf == '@') && "bogus @throw location");
2041
2042 std::string buf;
2043 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2044 if (S->getThrowExpr())
2045 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002046 else
2047 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002048
2049 // handle "@ throw" correctly.
2050 const char *wBuf = strchr(startBuf, 'w');
2051 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2052 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2053
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002054 SourceLocation endLoc = S->getEndLoc();
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002055 const char *endBuf = SM->getCharacterData(endLoc);
2056 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002057 assert((*semiBuf == ';') && "@throw: can't find ';'");
2058 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002059 if (S->getThrowExpr())
2060 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002061 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002062}
2063
2064Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2065 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002066 std::string StrEncoding;
2067 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002068 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002069 ReplaceStmt(Exp, Replacement);
2070
2071 // Replace this subexpr in the parent.
2072 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2073 return Replacement;
2074}
2075
2076Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2077 if (!SelGetUidFunctionDecl)
2078 SynthSelGetUidFunctionDecl();
2079 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2080 // Create a call to sel_registerName("selName").
2081 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002082 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002083 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002084 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002085 ReplaceStmt(Exp, SelExp);
2086 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2087 return SelExp;
2088}
2089
Craig Toppercf2126e2015-10-22 03:13:07 +00002090CallExpr *
2091RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2092 ArrayRef<Expr *> Args,
2093 SourceLocation StartLoc,
2094 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002095 // Get the type, we will need to reference it in a couple spots.
2096 QualType msgSendType = FD->getType();
2097
2098 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002099 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2100 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002101
2102 // Now, we cast the reference to a pointer to the objc_msgSend type.
2103 QualType pToFunc = Context->getPointerType(msgSendType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002104 ImplicitCastExpr *ICE =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002105 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002106 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107
2108 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2109
Craig Toppercf2126e2015-10-22 03:13:07 +00002110 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2111 FT->getCallResultType(*Context),
2112 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002113 return Exp;
2114}
2115
2116static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2117 const char *&startRef, const char *&endRef) {
2118 while (startBuf < endBuf) {
2119 if (*startBuf == '<')
2120 startRef = startBuf; // mark the start.
2121 if (*startBuf == '>') {
2122 if (startRef && *startRef == '<') {
2123 endRef = startBuf; // mark the end.
2124 return true;
2125 }
2126 return false;
2127 }
2128 startBuf++;
2129 }
2130 return false;
2131}
2132
2133static void scanToNextArgument(const char *&argRef) {
2134 int angle = 0;
2135 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2136 if (*argRef == '<')
2137 angle++;
2138 else if (*argRef == '>')
2139 angle--;
2140 argRef++;
2141 }
2142 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2143}
2144
2145bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2146 if (T->isObjCQualifiedIdType())
2147 return true;
2148 if (const PointerType *PT = T->getAs<PointerType>()) {
2149 if (PT->getPointeeType()->isObjCQualifiedIdType())
2150 return true;
2151 }
2152 if (T->isObjCObjectPointerType()) {
2153 T = T->getPointeeType();
2154 return T->isObjCQualifiedInterfaceType();
2155 }
2156 if (T->isArrayType()) {
2157 QualType ElemTy = Context->getBaseElementType(T);
2158 return needToScanForQualifiers(ElemTy);
2159 }
2160 return false;
2161}
2162
2163void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2164 QualType Type = E->getType();
2165 if (needToScanForQualifiers(Type)) {
2166 SourceLocation Loc, EndLoc;
2167
2168 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2169 Loc = ECE->getLParenLoc();
2170 EndLoc = ECE->getRParenLoc();
2171 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002172 Loc = E->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002173 EndLoc = E->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002174 }
2175 // This will defend against trying to rewrite synthesized expressions.
2176 if (Loc.isInvalid() || EndLoc.isInvalid())
2177 return;
2178
2179 const char *startBuf = SM->getCharacterData(Loc);
2180 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002181 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002182 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183 // Get the locations of the startRef, endRef.
2184 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2185 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2186 // Comment out the protocol references.
2187 InsertText(LessLoc, "/*");
2188 InsertText(GreaterLoc, "*/");
2189 }
2190 }
2191}
2192
2193void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2194 SourceLocation Loc;
2195 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002196 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002197 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2198 Loc = VD->getLocation();
2199 Type = VD->getType();
2200 }
2201 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2202 Loc = FD->getLocation();
2203 // Check for ObjC 'id' and class types that have been adorned with protocol
2204 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2205 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2206 assert(funcType && "missing function type");
2207 proto = dyn_cast<FunctionProtoType>(funcType);
2208 if (!proto)
2209 return;
Alp Toker314cc812014-01-25 16:55:45 +00002210 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002211 }
2212 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2213 Loc = FD->getLocation();
2214 Type = FD->getType();
2215 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002216 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2217 Loc = TD->getLocation();
2218 Type = TD->getUnderlyingType();
2219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002220 else
2221 return;
2222
2223 if (needToScanForQualifiers(Type)) {
2224 // Since types are unique, we need to scan the buffer.
2225
2226 const char *endBuf = SM->getCharacterData(Loc);
2227 const char *startBuf = endBuf;
2228 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2229 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002230 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002231 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2232 // Get the locations of the startRef, endRef.
2233 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2234 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2235 // Comment out the protocol references.
2236 InsertText(LessLoc, "/*");
2237 InsertText(GreaterLoc, "*/");
2238 }
2239 }
2240 if (!proto)
2241 return; // most likely, was a variable
2242 // Now check arguments.
2243 const char *startBuf = SM->getCharacterData(Loc);
2244 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002245 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2246 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002247 // Since types are unique, we need to scan the buffer.
2248
2249 const char *endBuf = startBuf;
2250 // scan forward (from the decl location) for argument types.
2251 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002252 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002253 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2254 // Get the locations of the startRef, endRef.
2255 SourceLocation LessLoc =
2256 Loc.getLocWithOffset(startRef-startFuncBuf);
2257 SourceLocation GreaterLoc =
2258 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2259 // Comment out the protocol references.
2260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
2262 }
2263 startBuf = ++endBuf;
2264 }
2265 else {
2266 // If the function name is derived from a macro expansion, then the
2267 // argument buffer will not follow the name. Need to speak with Chris.
2268 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2269 startBuf++; // scan forward (from the decl location) for argument types.
2270 startBuf++;
2271 }
2272 }
2273}
2274
2275void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2276 QualType QT = ND->getType();
2277 const Type* TypePtr = QT->getAs<Type>();
2278 if (!isa<TypeOfExprType>(TypePtr))
2279 return;
2280 while (isa<TypeOfExprType>(TypePtr)) {
2281 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2282 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2283 TypePtr = QT->getAs<Type>();
2284 }
2285 // FIXME. This will not work for multiple declarators; as in:
2286 // __typeof__(a) b,c,d;
2287 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2288 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2289 const char *startBuf = SM->getCharacterData(DeclLoc);
2290 if (ND->getInit()) {
2291 std::string Name(ND->getNameAsString());
2292 TypeAsString += " " + Name + " = ";
2293 Expr *E = ND->getInit();
2294 SourceLocation startLoc;
2295 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2296 startLoc = ECE->getLParenLoc();
2297 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002298 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002299 startLoc = SM->getExpansionLoc(startLoc);
2300 const char *endBuf = SM->getCharacterData(startLoc);
2301 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2302 }
2303 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002304 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002305 X = SM->getExpansionLoc(X);
2306 const char *endBuf = SM->getCharacterData(X);
2307 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2308 }
2309}
2310
2311// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2312void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2313 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2314 SmallVector<QualType, 16> ArgTys;
2315 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2316 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002317 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002318 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002319 SourceLocation(),
2320 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002321 SelGetUidIdent, getFuncType,
2322 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002323}
2324
2325void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2326 // declared in <objc/objc.h>
2327 if (FD->getIdentifier() &&
2328 FD->getName() == "sel_registerName") {
2329 SelGetUidFunctionDecl = FD;
2330 return;
2331 }
2332 RewriteObjCQualifiedInterfaceTypes(FD);
2333}
2334
2335void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2336 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2337 const char *argPtr = TypeString.c_str();
2338 if (!strchr(argPtr, '^')) {
2339 Str += TypeString;
2340 return;
2341 }
2342 while (*argPtr) {
2343 Str += (*argPtr == '^' ? '*' : *argPtr);
2344 argPtr++;
2345 }
2346}
2347
2348// FIXME. Consolidate this routine with RewriteBlockPointerType.
2349void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350 ValueDecl *VD) {
2351 QualType Type = VD->getType();
2352 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2353 const char *argPtr = TypeString.c_str();
2354 int paren = 0;
2355 while (*argPtr) {
2356 switch (*argPtr) {
2357 case '(':
2358 Str += *argPtr;
2359 paren++;
2360 break;
2361 case ')':
2362 Str += *argPtr;
2363 paren--;
2364 break;
2365 case '^':
2366 Str += '*';
2367 if (paren == 1)
2368 Str += VD->getNameAsString();
2369 break;
2370 default:
2371 Str += *argPtr;
2372 break;
2373 }
2374 argPtr++;
2375 }
2376}
2377
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002378void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2379 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2380 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2381 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2382 if (!proto)
2383 return;
Alp Toker314cc812014-01-25 16:55:45 +00002384 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002385 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2386 FdStr += " ";
2387 FdStr += FD->getName();
2388 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002389 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002390 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002391 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002392 RewriteBlockPointerType(FdStr, ArgType);
2393 if (i+1 < numArgs)
2394 FdStr += ", ";
2395 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002396 if (FD->isVariadic()) {
2397 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2398 }
2399 else
2400 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002401 InsertText(FunLocStart, FdStr);
2402}
2403
Benjamin Kramer60509af2013-09-09 14:48:42 +00002404// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2405void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2406 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002407 return;
2408 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2409 SmallVector<QualType, 16> ArgTys;
2410 QualType argT = Context->getObjCIdType();
2411 assert(!argT.isNull() && "Can't find 'id' type");
2412 ArgTys.push_back(argT);
2413 ArgTys.push_back(argT);
2414 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002415 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002416 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002417 SourceLocation(),
2418 SourceLocation(),
2419 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002420 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002421}
2422
2423// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2424void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2425 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2426 SmallVector<QualType, 16> ArgTys;
2427 QualType argT = Context->getObjCIdType();
2428 assert(!argT.isNull() && "Can't find 'id' type");
2429 ArgTys.push_back(argT);
2430 argT = Context->getObjCSelType();
2431 assert(!argT.isNull() && "Can't find 'SEL' type");
2432 ArgTys.push_back(argT);
2433 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002434 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002435 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002436 SourceLocation(),
2437 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002438 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002439 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002440}
2441
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002442// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002443void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2444 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002445 SmallVector<QualType, 2> ArgTys;
2446 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002447 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002448 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002449 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002450 SourceLocation(),
2451 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002452 msgSendIdent, msgSendType,
2453 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002454}
2455
2456// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2457void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2458 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2459 SmallVector<QualType, 16> ArgTys;
2460 QualType argT = Context->getObjCIdType();
2461 assert(!argT.isNull() && "Can't find 'id' type");
2462 ArgTys.push_back(argT);
2463 argT = Context->getObjCSelType();
2464 assert(!argT.isNull() && "Can't find 'SEL' type");
2465 ArgTys.push_back(argT);
2466 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002467 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002468 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002469 SourceLocation(),
2470 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002471 msgSendIdent, msgSendType,
2472 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002473}
2474
2475// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002476// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002477void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2478 IdentifierInfo *msgSendIdent =
2479 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002480 SmallVector<QualType, 2> ArgTys;
2481 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002482 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002483 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002484 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2485 SourceLocation(),
2486 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002487 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002488 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002489 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002490}
2491
2492// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495 SmallVector<QualType, 16> ArgTys;
2496 QualType argT = Context->getObjCIdType();
2497 assert(!argT.isNull() && "Can't find 'id' type");
2498 ArgTys.push_back(argT);
2499 argT = Context->getObjCSelType();
2500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
2502 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002503 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002505 SourceLocation(),
2506 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002507 msgSendIdent, msgSendType,
2508 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002509}
2510
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002511// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002512void RewriteModernObjC::SynthGetClassFunctionDecl() {
2513 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2514 SmallVector<QualType, 16> ArgTys;
2515 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002516 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002517 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002518 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002519 SourceLocation(),
2520 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002521 getClassIdent, getClassType,
2522 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002523}
2524
2525// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2526void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
Fangrui Song6907ce22018-07-30 19:24:48 +00002527 IdentifierInfo *getSuperClassIdent =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002528 &Context->Idents.get("class_getSuperclass");
2529 SmallVector<QualType, 16> ArgTys;
2530 ArgTys.push_back(Context->getObjCClassType());
2531 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002532 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002533 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2534 SourceLocation(),
2535 SourceLocation(),
2536 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002537 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002538 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002539}
2540
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002541// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002542void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2543 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2544 SmallVector<QualType, 16> ArgTys;
2545 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002546 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002547 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002548 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002549 SourceLocation(),
2550 SourceLocation(),
2551 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002552 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002553}
2554
2555Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002556 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002557 QualType strType = getConstantStringStructType();
2558
2559 std::string S = "__NSConstantStringImpl_";
2560
2561 std::string tmpName = InFileName;
2562 unsigned i;
2563 for (i=0; i < tmpName.length(); i++) {
2564 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002565 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002566 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002567 tmpName[i] = '_';
2568 }
2569 S += tmpName;
2570 S += "_";
2571 S += utostr(NumObjCStringLiterals++);
2572
2573 Preamble += "static __NSConstantStringImpl " + S;
2574 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2575 Preamble += "0x000007c8,"; // utf8_str
2576 // The pretty printer for StringLiteral handles escape characters properly.
2577 std::string prettyBufS;
2578 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002579 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002580 Preamble += prettyBuf.str();
2581 Preamble += ",";
2582 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2583
2584 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2585 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002586 strType, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002587 DeclRefExpr *DRE = new (Context)
2588 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2589 Expr *Unop = new (Context)
2590 UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2591 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002592 // cast to NSConstantString *
2593 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2594 CK_CPointerToObjCPointerCast, Unop);
2595 ReplaceStmt(Exp, cast);
2596 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2597 return cast;
2598}
2599
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002600Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2601 unsigned IntSize =
2602 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00002603
2604 Expr *FlagExp = IntegerLiteral::Create(*Context,
2605 llvm::APInt(IntSize, Exp->getValue()),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002606 Context->IntTy, Exp->getLocation());
2607 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2608 CK_BitCast, FlagExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002609 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002610 cast);
2611 ReplaceStmt(Exp, PE);
2612 return PE;
2613}
2614
Patrick Beard0caa3942012-04-19 00:25:12 +00002615Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002616 // synthesize declaration of helper functions needed in this routine.
2617 if (!SelGetUidFunctionDecl)
2618 SynthSelGetUidFunctionDecl();
2619 // use objc_msgSend() for all.
2620 if (!MsgSendFunctionDecl)
2621 SynthMsgSendFunctionDecl();
2622 if (!GetClassFunctionDecl)
2623 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002624
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002625 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002626 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002627 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002628
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002629 // Synthesize a call to objc_msgSend().
2630 SmallVector<Expr*, 4> MsgExprs;
2631 SmallVector<Expr*, 4> ClsExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002632
Patrick Beard0caa3942012-04-19 00:25:12 +00002633 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2634 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2635 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002636
Patrick Beard0caa3942012-04-19 00:25:12 +00002637 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002638 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002639 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002640 StartLoc, EndLoc);
2641 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002642
Patrick Beard0caa3942012-04-19 00:25:12 +00002643 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002644 // it will be the 2nd argument.
2645 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002646 SelExprs.push_back(
2647 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002648 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002649 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002650 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002651
Patrick Beard0caa3942012-04-19 00:25:12 +00002652 // User provided sub-expression is the 3rd, and last, argument.
2653 Expr *subExpr = Exp->getSubExpr();
2654 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002655 QualType type = ICE->getType();
2656 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2657 CastKind CK = CK_BitCast;
2658 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2659 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002660 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002661 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002662 MsgExprs.push_back(subExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00002663
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002664 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002665 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002666 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002667 for (const auto PI : BoxingMethod->parameters())
2668 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002669
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002670 QualType returnType = Exp->getType();
2671 // Get the type, we will need to reference it in a couple spots.
2672 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002673
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002674 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002675 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2676 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002677
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002678 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2679 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002680
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002681 // Now do the "normal" pointer to function cast.
2682 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002683 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002684 castType = Context->getPointerType(castType);
2685 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2686 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002687
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002688 // Don't forget the parens to enforce the proper binding.
2689 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002690
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002691 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002692 CallExpr *CE = new (Context)
2693 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002694 ReplaceStmt(Exp, CE);
2695 return CE;
2696}
2697
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002698Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2699 // synthesize declaration of helper functions needed in this routine.
2700 if (!SelGetUidFunctionDecl)
2701 SynthSelGetUidFunctionDecl();
2702 // use objc_msgSend() for all.
2703 if (!MsgSendFunctionDecl)
2704 SynthMsgSendFunctionDecl();
2705 if (!GetClassFunctionDecl)
2706 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002707
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002708 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002710 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002711
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002712 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002713 QualType IntQT = Context->IntTy;
2714 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002715 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002716 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002717 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002718 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2719 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002720
2721 SmallVector<Expr*, 16> InitExprs;
2722 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002723 unsigned UnsignedIntSize =
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002724 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725 Expr *count = IntegerLiteral::Create(*Context,
2726 llvm::APInt(UnsignedIntSize, NumElements),
2727 Context->UnsignedIntTy, SourceLocation());
2728 InitExprs.push_back(count);
2729 for (unsigned i = 0; i < NumElements; i++)
2730 InitExprs.push_back(Exp->getElement(i));
Fangrui Song6907ce22018-07-30 19:24:48 +00002731 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002732 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002733 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002734
2735 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002736 SourceLocation(),
2737 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002738 Context->getPointerType(Context->VoidPtrTy),
2739 nullptr, /*BitWidth=*/nullptr,
2740 /*Mutable=*/true, ICIS_NoInit);
2741 MemberExpr *ArrayLiteralME = new (Context)
2742 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2743 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2744 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002745 CStyleCastExpr * ArrayLiteralObjects =
2746 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002747 Context->getPointerType(ConstIdT),
2748 CK_BitCast,
2749 ArrayLiteralME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002750
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002751 // Synthesize a call to objc_msgSend().
2752 SmallVector<Expr*, 32> MsgExprs;
2753 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002754 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002755
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002756 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002757 ObjCInterfaceDecl *Class =
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002758 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002759
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002760 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002761 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002762 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002763 StartLoc, EndLoc);
2764 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002765
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002766 // Create a call to sel_registerName("arrayWithObjects:count:").
2767 // it will be the 2nd argument.
2768 SmallVector<Expr*, 4> SelExprs;
2769 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002770 SelExprs.push_back(
2771 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002772 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002773 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002774 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002775
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002776 // (const id [])objects
2777 MsgExprs.push_back(ArrayLiteralObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002778
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002779 // (NSUInteger)cnt
2780 Expr *cnt = IntegerLiteral::Create(*Context,
2781 llvm::APInt(UnsignedIntSize, NumElements),
2782 Context->UnsignedIntTy, SourceLocation());
2783 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002784
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002785 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002786 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002787 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002788 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002789 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002790
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002791 QualType returnType = Exp->getType();
2792 // Get the type, we will need to reference it in a couple spots.
2793 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002794
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002795 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002796 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2797 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002798
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002799 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2800 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002801
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002802 // Now do the "normal" pointer to function cast.
2803 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002804 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002805 castType = Context->getPointerType(castType);
2806 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2807 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002808
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002809 // Don't forget the parens to enforce the proper binding.
2810 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002811
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002812 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002813 CallExpr *CE = new (Context)
2814 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002815 ReplaceStmt(Exp, CE);
2816 return CE;
2817}
2818
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002819Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2820 // synthesize declaration of helper functions needed in this routine.
2821 if (!SelGetUidFunctionDecl)
2822 SynthSelGetUidFunctionDecl();
2823 // use objc_msgSend() for all.
2824 if (!MsgSendFunctionDecl)
2825 SynthMsgSendFunctionDecl();
2826 if (!GetClassFunctionDecl)
2827 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002828
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002829 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002830 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002831 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002832
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002833 // Build the expression: __NSContainer_literal(int, ...).arr
2834 QualType IntQT = Context->IntTy;
2835 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002836 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002837 std::string NSDictFName("__NSContainer_literal");
2838 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002839 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2840 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002841
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002842 SmallVector<Expr*, 16> KeyExprs;
2843 SmallVector<Expr*, 16> ValueExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002844
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002845 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002846 unsigned UnsignedIntSize =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002847 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2848 Expr *count = IntegerLiteral::Create(*Context,
2849 llvm::APInt(UnsignedIntSize, NumElements),
2850 Context->UnsignedIntTy, SourceLocation());
2851 KeyExprs.push_back(count);
2852 ValueExprs.push_back(count);
2853 for (unsigned i = 0; i < NumElements; i++) {
2854 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2855 KeyExprs.push_back(Element.Key);
2856 ValueExprs.push_back(Element.Value);
2857 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002858
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002859 // (const id [])objects
Fangrui Song6907ce22018-07-30 19:24:48 +00002860 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002861 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002862 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002863
2864 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002865 SourceLocation(),
2866 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002867 Context->getPointerType(Context->VoidPtrTy),
2868 nullptr, /*BitWidth=*/nullptr,
2869 /*Mutable=*/true, ICIS_NoInit);
2870 MemberExpr *DictLiteralValueME = new (Context)
2871 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2872 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2873 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002874 CStyleCastExpr * DictValueObjects =
2875 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002876 Context->getPointerType(ConstIdT),
2877 CK_BitCast,
2878 DictLiteralValueME);
2879 // (const id <NSCopying> [])keys
Fangrui Song6907ce22018-07-30 19:24:48 +00002880 Expr *NSKeyCallExpr =
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002881 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2882 NSDictFType, VK_LValue, SourceLocation());
2883
2884 MemberExpr *DictLiteralKeyME = new (Context)
2885 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2886 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2887
Fangrui Song6907ce22018-07-30 19:24:48 +00002888 CStyleCastExpr * DictKeyObjects =
2889 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002890 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002891 CK_BitCast,
2892 DictLiteralKeyME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002893
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002894 // Synthesize a call to objc_msgSend().
2895 SmallVector<Expr*, 32> MsgExprs;
2896 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002897 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002898
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002899 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002900 ObjCInterfaceDecl *Class =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002901 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002902
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002903 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002904 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002905 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002906 StartLoc, EndLoc);
2907 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002908
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002909 // Create a call to sel_registerName("arrayWithObjects:count:").
2910 // it will be the 2nd argument.
2911 SmallVector<Expr*, 4> SelExprs;
2912 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002913 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002914 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002915 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002916 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002917
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 // (const id [])objects
2919 MsgExprs.push_back(DictValueObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002920
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 // (const id <NSCopying> [])keys
2922 MsgExprs.push_back(DictKeyObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002923
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002924 // (NSUInteger)cnt
2925 Expr *cnt = IntegerLiteral::Create(*Context,
2926 llvm::APInt(UnsignedIntSize, NumElements),
2927 Context->UnsignedIntTy, SourceLocation());
2928 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002929
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002930 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002931 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002932 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002933 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002934 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002935 if (const PointerType* PT = T->getAs<PointerType>()) {
2936 QualType PointeeTy = PT->getPointeeType();
2937 convertToUnqualifiedObjCType(PointeeTy);
2938 T = Context->getPointerType(PointeeTy);
2939 }
2940 ArgTypes.push_back(T);
2941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002942
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002943 QualType returnType = Exp->getType();
2944 // Get the type, we will need to reference it in a couple spots.
2945 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002946
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002947 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002948 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2949 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002950
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002951 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2952 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002953
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002954 // Now do the "normal" pointer to function cast.
2955 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002956 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002957 castType = Context->getPointerType(castType);
2958 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2959 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002960
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 // Don't forget the parens to enforce the proper binding.
2962 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002963
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002965 CallExpr *CE = new (Context)
2966 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002967 ReplaceStmt(Exp, CE);
2968 return CE;
2969}
2970
Fangrui Song6907ce22018-07-30 19:24:48 +00002971// struct __rw_objc_super {
2972// struct objc_object *object; struct objc_object *superClass;
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002973// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002974QualType RewriteModernObjC::getSuperStructType() {
2975 if (!SuperStructDecl) {
2976 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2977 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002978 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002979 QualType FieldTypes[2];
2980
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002981 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002982 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002983 // struct objc_object *superClass;
2984 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002985
2986 // Create fields
2987 for (unsigned i = 0; i < 2; ++i) {
2988 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2989 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002990 SourceLocation(), nullptr,
2991 FieldTypes[i], nullptr,
2992 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002993 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002994 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002995 }
2996
2997 SuperStructDecl->completeDefinition();
2998 }
2999 return Context->getTagDeclType(SuperStructDecl);
3000}
3001
3002QualType RewriteModernObjC::getConstantStringStructType() {
3003 if (!ConstantStringDecl) {
3004 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3005 SourceLocation(), SourceLocation(),
3006 &Context->Idents.get("__NSConstantStringImpl"));
3007 QualType FieldTypes[4];
3008
3009 // struct objc_object *receiver;
3010 FieldTypes[0] = Context->getObjCIdType();
3011 // int flags;
3012 FieldTypes[1] = Context->IntTy;
3013 // char *str;
3014 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3015 // long length;
3016 FieldTypes[3] = Context->LongTy;
3017
3018 // Create fields
3019 for (unsigned i = 0; i < 4; ++i) {
3020 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3021 ConstantStringDecl,
3022 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003023 SourceLocation(), nullptr,
3024 FieldTypes[i], nullptr,
3025 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003026 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003027 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003028 }
3029
3030 ConstantStringDecl->completeDefinition();
3031 }
3032 return Context->getTagDeclType(ConstantStringDecl);
3033}
3034
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003035/// getFunctionSourceLocation - returns start location of a function
3036/// definition. Complication arises when function has declared as
3037/// extern "C" or extern "C" {...}
3038static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3039 FunctionDecl *FD) {
3040 if (FD->isExternC() && !FD->isMain()) {
3041 const DeclContext *DC = FD->getDeclContext();
3042 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3043 // if it is extern "C" {...}, return function decl's own location.
3044 if (!LSD->getRBraceLoc().isValid())
3045 return LSD->getExternLoc();
3046 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003047 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003048 R.RewriteBlockLiteralFunctionDecl(FD);
3049 return FD->getTypeSpecStartLoc();
3050}
3051
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003052void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003053
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003054 SourceLocation Location = D->getLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003055
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003056 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003057 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003058 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3059 LineString += utostr(PLoc.getLine());
3060 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003061 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003062 if (isa<ObjCMethodDecl>(D))
3063 LineString += "\"";
3064 else LineString += "\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003065
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003066 Location = D->getBeginLoc();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003067 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3068 if (FD->isExternC() && !FD->isMain()) {
3069 const DeclContext *DC = FD->getDeclContext();
3070 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3071 // if it is extern "C" {...}, return function decl's own location.
3072 if (!LSD->getRBraceLoc().isValid())
3073 Location = LSD->getExternLoc();
3074 }
3075 }
3076 InsertText(Location, LineString);
3077 }
3078}
3079
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003080/// SynthMsgSendStretCallExpr - This routine translates message expression
3081/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3082/// nil check on receiver must be performed before calling objc_msgSend_stret.
3083/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3084/// msgSendType - function type of objc_msgSend_stret(...)
3085/// returnType - Result type of the method being synthesized.
3086/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003087/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003088/// starting with receiver.
3089/// Method - Method being rewritten.
3090Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +00003091 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003092 SmallVectorImpl<QualType> &ArgTypes,
3093 SmallVectorImpl<Expr*> &MsgExprs,
3094 ObjCMethodDecl *Method) {
3095 // Now do the "normal" pointer to function cast.
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003096 QualType FuncType = getSimpleFunctionType(
3097 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3098 QualType castType = Context->getPointerType(FuncType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003099
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003100 // build type for containing the objc_msgSend_stret object.
3101 static unsigned stretCount=0;
3102 std::string name = "__Stret"; name += utostr(stretCount);
Fangrui Song6907ce22018-07-30 19:24:48 +00003103 std::string str =
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003104 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003105 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003106 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003107 str += " {\n\t";
3108 str += name;
3109 str += "(id receiver, SEL sel";
3110 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003111 std::string ArgName = "arg"; ArgName += utostr(i);
3112 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3113 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003114 }
3115 // could be vararg.
3116 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003117 std::string ArgName = "arg"; ArgName += utostr(i);
3118 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3119 Context->getPrintingPolicy());
3120 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003121 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003122
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003123 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003124 str += "\t unsigned size = sizeof(";
3125 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003126
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003127 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003128
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003129 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3130 str += ")(void *)objc_msgSend)(receiver, sel";
3131 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3132 str += ", arg"; str += utostr(i);
3133 }
3134 // could be vararg.
3135 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3136 str += ", arg"; str += utostr(i);
3137 }
3138 str+= ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003139
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003140 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003141 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3142 str += "\t else\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003143
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003144 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3145 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3146 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3147 str += ", arg"; str += utostr(i);
3148 }
3149 // could be vararg.
3150 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3151 str += ", arg"; str += utostr(i);
3152 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003153 str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003154
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003155 str += "\t}\n";
3156 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3157 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003158 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003159 SourceLocation FunLocStart;
3160 if (CurFunctionDef)
3161 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3162 else {
3163 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003164 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003165 }
3166
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003167 InsertText(FunLocStart, str);
3168 ++stretCount;
Fangrui Song6907ce22018-07-30 19:24:48 +00003169
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003170 // AST for __Stretn(receiver, args).s;
3171 IdentifierInfo *ID = &Context->Idents.get(name);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003172 FunctionDecl *FD =
3173 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3174 ID, FuncType, nullptr, SC_Extern, false, false);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003175 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, castType,
3176 VK_RValue, SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003177 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003178 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003179
3180 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003181 SourceLocation(),
3182 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003183 returnType, nullptr,
3184 /*BitWidth=*/nullptr,
3185 /*Mutable=*/true, ICIS_NoInit);
3186 MemberExpr *ME = new (Context)
3187 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3188 FieldD->getType(), VK_LValue, OK_Ordinary);
3189
3190 return ME;
3191}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003192
Fariborz Jahanian11671902012-02-07 17:11:38 +00003193Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3194 SourceLocation StartLoc,
3195 SourceLocation EndLoc) {
3196 if (!SelGetUidFunctionDecl)
3197 SynthSelGetUidFunctionDecl();
3198 if (!MsgSendFunctionDecl)
3199 SynthMsgSendFunctionDecl();
3200 if (!MsgSendSuperFunctionDecl)
3201 SynthMsgSendSuperFunctionDecl();
3202 if (!MsgSendStretFunctionDecl)
3203 SynthMsgSendStretFunctionDecl();
3204 if (!MsgSendSuperStretFunctionDecl)
3205 SynthMsgSendSuperStretFunctionDecl();
3206 if (!MsgSendFpretFunctionDecl)
3207 SynthMsgSendFpretFunctionDecl();
3208 if (!GetClassFunctionDecl)
3209 SynthGetClassFunctionDecl();
3210 if (!GetSuperClassFunctionDecl)
3211 SynthGetSuperClassFunctionDecl();
3212 if (!GetMetaClassFunctionDecl)
3213 SynthGetMetaClassFunctionDecl();
3214
3215 // default to objc_msgSend().
3216 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3217 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003218 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003219 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003220 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003221 if (resultType->isRecordType())
3222 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3223 else if (resultType->isRealFloatingType())
3224 MsgSendFlavor = MsgSendFpretFunctionDecl;
3225 }
3226
3227 // Synthesize a call to objc_msgSend().
3228 SmallVector<Expr*, 8> MsgExprs;
3229 switch (Exp->getReceiverKind()) {
3230 case ObjCMessageExpr::SuperClass: {
3231 MsgSendFlavor = MsgSendSuperFunctionDecl;
3232 if (MsgSendStretFlavor)
3233 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3234 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3235
3236 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3237
3238 SmallVector<Expr*, 4> InitExprs;
3239
3240 // set the receiver to self, the first argument to all methods.
3241 InitExprs.push_back(
3242 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3243 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003244 new (Context) DeclRefExpr(*Context,
3245 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003246 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003247 Context->getObjCIdType(),
3248 VK_RValue,
3249 SourceLocation()))
3250 ); // set the 'receiver'.
3251
3252 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3253 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003254 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003255 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003256 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003257 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003258 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003259 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003260 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003261 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003262
Fariborz Jahanian11671902012-02-07 17:11:38 +00003263 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3264 // To turn off a warning, type-cast to 'id'
3265 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3266 NoTypeInfoCStyleCastExpr(Context,
3267 Context->getObjCIdType(),
3268 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003269 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003270 QualType superType = getSuperStructType();
3271 Expr *SuperRep;
3272
3273 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003274 SynthSuperConstructorFunctionDecl();
3275 // Simulate a constructor call...
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003276 DeclRefExpr *DRE = new (Context)
3277 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3278 VK_LValue, SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003279 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003280 superType, VK_LValue,
3281 SourceLocation());
3282 // The code for super is a little tricky to prevent collision with
3283 // the structure definition in the header. The rewriter has it's own
3284 // internal definition (__rw_objc_super) that is uses. This is why
3285 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003286 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003287 //
3288 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3289 Context->getPointerType(SuperRep->getType()),
3290 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003291 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003292 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3293 Context->getPointerType(superType),
3294 CK_BitCast, SuperRep);
3295 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003296 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003297 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003298 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003299 SourceLocation());
3300 TypeSourceInfo *superTInfo
3301 = Context->getTrivialTypeSourceInfo(superType);
3302 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3303 superType, VK_LValue,
3304 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003305 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003306 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3307 Context->getPointerType(SuperRep->getType()),
3308 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003309 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003310 }
3311 MsgExprs.push_back(SuperRep);
3312 break;
3313 }
3314
3315 case ObjCMessageExpr::Class: {
3316 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003317 ObjCInterfaceDecl *Class
3318 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3319 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003320 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003321 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003322 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003323 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3324 Context->getObjCIdType(),
3325 CK_BitCast, Cls);
3326 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003327 break;
3328 }
3329
3330 case ObjCMessageExpr::SuperInstance:{
3331 MsgSendFlavor = MsgSendSuperFunctionDecl;
3332 if (MsgSendStretFlavor)
3333 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3334 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3335 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3336 SmallVector<Expr*, 4> InitExprs;
3337
3338 InitExprs.push_back(
3339 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3340 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003341 new (Context) DeclRefExpr(*Context,
3342 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003343 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003344 Context->getObjCIdType(),
3345 VK_RValue, SourceLocation()))
3346 ); // set the 'receiver'.
Fangrui Song6907ce22018-07-30 19:24:48 +00003347
Fariborz Jahanian11671902012-02-07 17:11:38 +00003348 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3349 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003350 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003351 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003352 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003354 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003355 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003356 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003357 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003358
Fariborz Jahanian11671902012-02-07 17:11:38 +00003359 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3360 // To turn off a warning, type-cast to 'id'
3361 InitExprs.push_back(
3362 // set 'super class', using class_getSuperclass().
3363 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3364 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003365 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003366 QualType superType = getSuperStructType();
3367 Expr *SuperRep;
3368
3369 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003370 SynthSuperConstructorFunctionDecl();
3371 // Simulate a constructor call...
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003372 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context,
3373 SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003374 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003375 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003376 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003377 superType, VK_LValue, SourceLocation());
3378 // The code for super is a little tricky to prevent collision with
3379 // the structure definition in the header. The rewriter has it's own
3380 // internal definition (__rw_objc_super) that is uses. This is why
3381 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003382 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003383 //
3384 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3385 Context->getPointerType(SuperRep->getType()),
3386 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003387 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003388 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3389 Context->getPointerType(superType),
3390 CK_BitCast, SuperRep);
3391 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003392 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003394 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003395 SourceLocation());
3396 TypeSourceInfo *superTInfo
3397 = Context->getTrivialTypeSourceInfo(superType);
3398 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3399 superType, VK_RValue, ILE,
3400 false);
3401 }
3402 MsgExprs.push_back(SuperRep);
3403 break;
3404 }
3405
3406 case ObjCMessageExpr::Instance: {
3407 // Remove all type-casts because it may contain objc-style types; e.g.
3408 // Foo<Proto> *.
3409 Expr *recExpr = Exp->getInstanceReceiver();
3410 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3411 recExpr = CE->getSubExpr();
3412 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3413 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3414 ? CK_BlockPointerToObjCPointerCast
3415 : CK_CPointerToObjCPointerCast;
3416
3417 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3418 CK, recExpr);
3419 MsgExprs.push_back(recExpr);
3420 break;
3421 }
3422 }
3423
3424 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3425 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003426 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003427 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003428 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003429 MsgExprs.push_back(SelExp);
3430
3431 // Now push any user supplied arguments.
3432 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3433 Expr *userExpr = Exp->getArg(i);
3434 // Make all implicit casts explicit...ICE comes in handy:-)
3435 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3436 // Reuse the ICE type, it is exactly what the doctor ordered.
3437 QualType type = ICE->getType();
3438 if (needToScanForQualifiers(type))
3439 type = Context->getObjCIdType();
3440 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3441 (void)convertBlockPointerToFunctionPointer(type);
3442 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3443 CastKind CK;
Fangrui Song6907ce22018-07-30 19:24:48 +00003444 if (SubExpr->getType()->isIntegralType(*Context) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003445 type->isBooleanType()) {
3446 CK = CK_IntegralToBoolean;
3447 } else if (type->isObjCObjectPointerType()) {
3448 if (SubExpr->getType()->isBlockPointerType()) {
3449 CK = CK_BlockPointerToObjCPointerCast;
3450 } else if (SubExpr->getType()->isPointerType()) {
3451 CK = CK_CPointerToObjCPointerCast;
3452 } else {
3453 CK = CK_BitCast;
3454 }
3455 } else {
3456 CK = CK_BitCast;
3457 }
3458
3459 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3460 }
3461 // Make id<P...> cast into an 'id' cast.
3462 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3463 if (CE->getType()->isObjCQualifiedIdType()) {
3464 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3465 userExpr = CE->getSubExpr();
3466 CastKind CK;
3467 if (userExpr->getType()->isIntegralType(*Context)) {
3468 CK = CK_IntegralToPointer;
3469 } else if (userExpr->getType()->isBlockPointerType()) {
3470 CK = CK_BlockPointerToObjCPointerCast;
3471 } else if (userExpr->getType()->isPointerType()) {
3472 CK = CK_CPointerToObjCPointerCast;
3473 } else {
3474 CK = CK_BitCast;
3475 }
3476 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3477 CK, userExpr);
3478 }
3479 }
3480 MsgExprs.push_back(userExpr);
3481 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3482 // out the argument in the original expression (since we aren't deleting
3483 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3484 //Exp->setArg(i, 0);
3485 }
3486 // Generate the funky cast.
3487 CastExpr *cast;
3488 SmallVector<QualType, 8> ArgTypes;
3489 QualType returnType;
3490
3491 // Push 'id' and 'SEL', the 2 implicit arguments.
3492 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3493 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3494 else
3495 ArgTypes.push_back(Context->getObjCIdType());
3496 ArgTypes.push_back(Context->getObjCSelType());
3497 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3498 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003499 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003500 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003501 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003502 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003503 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3504 (void)convertBlockPointerToFunctionPointer(t);
3505 ArgTypes.push_back(t);
3506 }
3507 returnType = Exp->getType();
3508 convertToUnqualifiedObjCType(returnType);
3509 (void)convertBlockPointerToFunctionPointer(returnType);
3510 } else {
3511 returnType = Context->getObjCIdType();
3512 }
3513 // Get the type, we will need to reference it in a couple spots.
3514 QualType msgSendType = MsgSendFlavor->getType();
3515
3516 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003517 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3518 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003519
3520 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3521 // If we don't do this cast, we get the following bizarre warning/note:
3522 // xx.m:13: warning: function called through a non-compatible type
3523 // xx.m:13: note: if this code is reached, the program will abort
3524 cast = NoTypeInfoCStyleCastExpr(Context,
3525 Context->getPointerType(Context->VoidTy),
3526 CK_BitCast, DRE);
3527
3528 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003529 // If we don't have a method decl, force a variadic cast.
3530 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003531 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003532 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003533 castType = Context->getPointerType(castType);
3534 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3535 cast);
3536
3537 // Don't forget the parens to enforce the proper binding.
3538 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3539
3540 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003541 CallExpr *CE = new (Context)
3542 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003543 Stmt *ReplacingStmt = CE;
3544 if (MsgSendStretFlavor) {
3545 // We have the method which returns a struct/union. Must also generate
3546 // call to objc_msgSend_stret and hang both varieties on a conditional
3547 // expression which dictate which one to envoke depending on size of
3548 // method's return type.
3549
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003550 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3551 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003552 ArgTypes, MsgExprs,
3553 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003554 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003555 }
3556 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3557 return ReplacingStmt;
3558}
3559
3560Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003561 Stmt *ReplacingStmt =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003562 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003563
3564 // Now do the actual rewrite.
3565 ReplaceStmt(Exp, ReplacingStmt);
3566
3567 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3568 return ReplacingStmt;
3569}
3570
3571// typedef struct objc_object Protocol;
3572QualType RewriteModernObjC::getProtocolType() {
3573 if (!ProtocolTypeDecl) {
3574 TypeSourceInfo *TInfo
3575 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3576 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3577 SourceLocation(), SourceLocation(),
3578 &Context->Idents.get("Protocol"),
3579 TInfo);
3580 }
3581 return Context->getTypeDeclType(ProtocolTypeDecl);
3582}
3583
3584/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3585/// a synthesized/forward data reference (to the protocol's metadata).
3586/// The forward references (and metadata) are generated in
3587/// RewriteModernObjC::HandleTranslationUnit().
3588Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003589 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003590 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003591 IdentifierInfo *ID = &Context->Idents.get(Name);
3592 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003593 SourceLocation(), ID, getProtocolType(),
3594 nullptr, SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003595 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3596 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3597 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003598 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003599 ReplaceStmt(Exp, castExpr);
3600 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3601 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3602 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003603}
3604
Fangrui Song6907ce22018-07-30 19:24:48 +00003605/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3606/// is defined inside an objective-c class. If so, it returns true.
3607bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003608 TagDecl *Tag,
3609 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003610 if (!IDecl)
3611 return false;
3612 SourceLocation TagLocation;
3613 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3614 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003615 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003616 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003617 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003618 TagLocation = RD->getLocation();
3619 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003620 IDecl->getLocation(), TagLocation);
3621 }
3622 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3623 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3624 return false;
3625 IsNamedDefinition = true;
3626 TagLocation = ED->getLocation();
3627 return Context->getSourceManager().isBeforeInTranslationUnit(
3628 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003629 }
3630 return false;
3631}
3632
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003633/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003634/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003635bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003636 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003637 if (isa<TypedefType>(Type)) {
3638 Result += "\t";
3639 return false;
3640 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003641
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003642 if (Type->isArrayType()) {
3643 QualType ElemTy = Context->getBaseElementType(Type);
3644 return RewriteObjCFieldDeclType(ElemTy, Result);
3645 }
3646 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003647 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3648 if (RD->isCompleteDefinition()) {
3649 if (RD->isStruct())
3650 Result += "\n\tstruct ";
3651 else if (RD->isUnion())
3652 Result += "\n\tunion ";
3653 else
3654 assert(false && "class not allowed as an ivar type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003655
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003656 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003657 if (GlobalDefinedTags.count(RD)) {
3658 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003659 Result += " ";
3660 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003661 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003662 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003663 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003664 RewriteObjCFieldDecl(FD, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003665 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003666 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003667 }
3668 }
3669 else if (Type->isEnumeralType()) {
3670 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3671 if (ED->isCompleteDefinition()) {
3672 Result += "\n\tenum ";
3673 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003674 if (GlobalDefinedTags.count(ED)) {
3675 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003676 Result += " ";
3677 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003678 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003679
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003680 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003681 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003682 Result += "\t"; Result += EC->getName(); Result += " = ";
3683 llvm::APSInt Val = EC->getInitVal();
3684 Result += Val.toString(10);
3685 Result += ",\n";
3686 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003687 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003688 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003689 }
3690 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003691
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003692 Result += "\t";
3693 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003694 return false;
3695}
3696
3697
3698/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3699/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003700void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003701 std::string &Result) {
3702 QualType Type = fieldDecl->getType();
3703 std::string Name = fieldDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003704
3705 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003706 if (!EleboratedType)
3707 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003708 Result += Name;
3709 if (fieldDecl->isBitField()) {
3710 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3711 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003712 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003713 const ArrayType *AT = Context->getAsArrayType(Type);
3714 do {
3715 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003716 Result += "[";
3717 llvm::APInt Dim = CAT->getSize();
3718 Result += utostr(Dim.getZExtValue());
3719 Result += "]";
3720 }
Eli Friedman07bab732012-12-13 01:43:21 +00003721 AT = Context->getAsArrayType(AT->getElementType());
3722 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003723 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003724
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003725 Result += ";\n";
3726}
3727
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003728/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3729/// named aggregate types into the input buffer.
Fangrui Song6907ce22018-07-30 19:24:48 +00003730void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003731 std::string &Result) {
3732 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003733 if (isa<TypedefType>(Type))
3734 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003735 if (Type->isArrayType())
3736 Type = Context->getBaseElementType(Type);
Fangrui Song6907ce22018-07-30 19:24:48 +00003737 ObjCContainerDecl *IDecl =
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003738 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003739
3740 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003741 if (Type->isRecordType()) {
3742 TD = Type->getAs<RecordType>()->getDecl();
3743 }
3744 else if (Type->isEnumeralType()) {
3745 TD = Type->getAs<EnumType>()->getDecl();
3746 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003747
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003748 if (TD) {
3749 if (GlobalDefinedTags.count(TD))
3750 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003751
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003752 bool IsNamedDefinition = false;
3753 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3754 RewriteObjCFieldDeclType(Type, Result);
3755 Result += ";";
3756 }
3757 if (IsNamedDefinition)
3758 GlobalDefinedTags.insert(TD);
3759 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003760}
3761
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003762unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3763 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3764 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3765 return IvarGroupNumber[IV];
3766 }
3767 unsigned GroupNo = 0;
3768 SmallVector<const ObjCIvarDecl *, 8> IVars;
3769 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3770 IVD; IVD = IVD->getNextIvar())
3771 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003772
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003773 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3774 if (IVars[i]->isBitField()) {
3775 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3776 while (i < e && IVars[i]->isBitField())
3777 IvarGroupNumber[IVars[i++]] = GroupNo;
3778 if (i < e)
3779 --i;
3780 }
3781
3782 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3783 return IvarGroupNumber[IV];
3784}
3785
3786QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3787 ObjCIvarDecl *IV,
3788 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3789 std::string StructTagName;
3790 ObjCIvarBitfieldGroupType(IV, StructTagName);
3791 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3792 Context->getTranslationUnitDecl(),
3793 SourceLocation(), SourceLocation(),
3794 &Context->Idents.get(StructTagName));
3795 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3796 ObjCIvarDecl *Ivar = IVars[i];
3797 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3798 &Context->Idents.get(Ivar->getName()),
3799 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003800 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3801 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003802 }
3803 RD->completeDefinition();
3804 return Context->getTagDeclType(RD);
3805}
3806
3807QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3808 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3809 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3810 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3811 if (GroupRecordType.count(tuple))
3812 return GroupRecordType[tuple];
Fangrui Song6907ce22018-07-30 19:24:48 +00003813
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003814 SmallVector<ObjCIvarDecl *, 8> IVars;
3815 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3816 IVD; IVD = IVD->getNextIvar()) {
3817 if (IVD->isBitField())
3818 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3819 else {
3820 if (!IVars.empty()) {
3821 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3822 // Generate the struct type for this group of bitfield ivars.
3823 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3824 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3825 IVars.clear();
3826 }
3827 }
3828 }
3829 if (!IVars.empty()) {
3830 // Do the last one.
3831 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3832 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3833 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3834 }
3835 QualType RetQT = GroupRecordType[tuple];
3836 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
Fangrui Song6907ce22018-07-30 19:24:48 +00003837
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003838 return RetQT;
3839}
3840
3841/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3842/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3843void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3844 std::string &Result) {
3845 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3846 Result += CDecl->getName();
3847 Result += "__GRBF_";
3848 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3849 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003850}
3851
3852/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3853/// Name of the struct would be: classname__T_n where n is the group number for
3854/// this ivar.
3855void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3856 std::string &Result) {
3857 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3858 Result += CDecl->getName();
3859 Result += "__T_";
3860 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3861 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003862}
3863
3864/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3865/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3866/// this ivar.
3867void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3868 std::string &Result) {
3869 Result += "OBJC_IVAR_$_";
3870 ObjCIvarBitfieldGroupDecl(IV, Result);
3871}
3872
3873#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3874 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3875 ++IX; \
3876 if (IX < ENDIX) \
3877 --IX; \
3878}
3879
Fariborz Jahanian11671902012-02-07 17:11:38 +00003880/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3881/// an objective-c class with ivars.
3882void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3883 std::string &Result) {
3884 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3885 assert(CDecl->getName() != "" &&
3886 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003887 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003888 SmallVector<ObjCIvarDecl *, 8> IVars;
3889 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003890 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003891 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003892
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003893 SourceLocation LocStart = CDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003894 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00003895
Fariborz Jahanian11671902012-02-07 17:11:38 +00003896 const char *startBuf = SM->getCharacterData(LocStart);
3897 const char *endBuf = SM->getCharacterData(LocEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +00003898
Fariborz Jahanian11671902012-02-07 17:11:38 +00003899 // If no ivars and no root or if its root, directly or indirectly,
3900 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003901 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003902 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3903 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3904 ReplaceText(LocStart, endBuf-startBuf, Result);
3905 return;
3906 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003907
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003908 // Insert named struct/union definitions inside class to
3909 // outer scope. This follows semantics of locally defined
3910 // struct/unions in objective-c classes.
3911 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3912 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003913
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003914 // Insert named structs which are syntheized to group ivar bitfields
3915 // to outer scope as well.
3916 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3917 if (IVars[i]->isBitField()) {
3918 ObjCIvarDecl *IV = IVars[i];
3919 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3920 RewriteObjCFieldDeclType(QT, Result);
3921 Result += ";";
3922 // skip over ivar bitfields in this group.
3923 SKIP_BITFIELDS(i , e, IVars);
3924 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003925
Fariborz Jahanian11671902012-02-07 17:11:38 +00003926 Result += "\nstruct ";
3927 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003928 Result += "_IMPL {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003929
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003930 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003931 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3932 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3933 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003934 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003935
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003936 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3937 if (IVars[i]->isBitField()) {
3938 ObjCIvarDecl *IV = IVars[i];
3939 Result += "\tstruct ";
3940 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3941 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3942 // skip over ivar bitfields in this group.
3943 SKIP_BITFIELDS(i , e, IVars);
3944 }
3945 else
3946 RewriteObjCFieldDecl(IVars[i], Result);
3947 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003948
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003949 Result += "};\n";
3950 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3951 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003952 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003953 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003954 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003955}
3956
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003957/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3958/// have been referenced in an ivar access expression.
3959void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3960 std::string &Result) {
3961 // write out ivar offset symbols which have been referenced in an ivar
3962 // access expression.
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003963 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3964
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003965 if (Ivars.empty())
3966 return;
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003967
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003968 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003969 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003970 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3971 unsigned GroupNo = 0;
3972 if (IvarDecl->isBitField()) {
3973 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3974 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3975 continue;
3976 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003977 Result += "\n";
3978 if (LangOpts.MicrosoftExt)
3979 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003980 Result += "extern \"C\" ";
Fangrui Song6907ce22018-07-30 19:24:48 +00003981 if (LangOpts.MicrosoftExt &&
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003982 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003983 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3984 Result += "__declspec(dllimport) ";
3985
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003986 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003987 if (IvarDecl->isBitField()) {
3988 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3989 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3990 }
3991 else
3992 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003993 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003994 }
3995}
3996
Fariborz Jahanian11671902012-02-07 17:11:38 +00003997//===----------------------------------------------------------------------===//
3998// Meta Data Emission
3999//===----------------------------------------------------------------------===//
4000
Fariborz Jahanian11671902012-02-07 17:11:38 +00004001/// RewriteImplementations - This routine rewrites all method implementations
4002/// and emits meta-data.
4003
4004void RewriteModernObjC::RewriteImplementations() {
4005 int ClsDefCount = ClassImplementation.size();
4006 int CatDefCount = CategoryImplementation.size();
4007
4008 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004009 for (int i = 0; i < ClsDefCount; i++) {
4010 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4011 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4012 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004013 assert(false &&
4014 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004015 RewriteImplementationDecl(OIMP);
4016 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004017
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004018 for (int i = 0; i < CatDefCount; i++) {
4019 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4020 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4021 if (CDecl->isImplicitInterfaceDecl())
4022 assert(false &&
4023 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004024 RewriteImplementationDecl(CIMP);
4025 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004026}
4027
Fangrui Song6907ce22018-07-30 19:24:48 +00004028void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004029 const std::string &Name,
4030 ValueDecl *VD, bool def) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004031 assert(BlockByRefDeclNo.count(VD) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004032 "RewriteByRefString: ByRef decl missing");
4033 if (def)
4034 ResultStr += "struct ";
Fangrui Song6907ce22018-07-30 19:24:48 +00004035 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004036 "_" + utostr(BlockByRefDeclNo[VD]) ;
4037}
4038
4039static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4040 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4041 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4042 return false;
4043}
4044
4045std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4046 StringRef funcName,
4047 std::string Tag) {
4048 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004049 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004050 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004051 SourceLocation BlockLoc = CE->getExprLoc();
4052 std::string S;
4053 ConvertSourceLocationToLineDirective(BlockLoc, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00004054
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004055 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4056 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004057
4058 BlockDecl *BD = CE->getBlockDecl();
4059
4060 if (isa<FunctionNoProtoType>(AFT)) {
4061 // No user-supplied arguments. Still need to pass in a pointer to the
4062 // block (to reference imported block decl refs).
4063 S += "(" + StructRef + " *__cself)";
4064 } else if (BD->param_empty()) {
4065 S += "(" + StructRef + " *__cself)";
4066 } else {
4067 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4068 assert(FT && "SynthesizeBlockFunc: No function proto");
4069 S += '(';
4070 // first add the implicit argument.
4071 S += StructRef + " *__cself, ";
4072 std::string ParamStr;
4073 for (BlockDecl::param_iterator AI = BD->param_begin(),
4074 E = BD->param_end(); AI != E; ++AI) {
4075 if (AI != BD->param_begin()) S += ", ";
4076 ParamStr = (*AI)->getNameAsString();
4077 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004078 (void)convertBlockPointerToFunctionPointer(QT);
4079 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004080 S += ParamStr;
4081 }
4082 if (FT->isVariadic()) {
4083 if (!BD->param_empty()) S += ", ";
4084 S += "...";
4085 }
4086 S += ')';
4087 }
4088 S += " {\n";
4089
4090 // Create local declarations to avoid rewriting all closure decl ref exprs.
4091 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004092 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004093 E = BlockByRefDecls.end(); I != E; ++I) {
4094 S += " ";
4095 std::string Name = (*I)->getNameAsString();
4096 std::string TypeString;
4097 RewriteByRefString(TypeString, Name, (*I));
4098 TypeString += " *";
4099 Name = TypeString + Name;
4100 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4101 }
4102 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004103 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004104 E = BlockByCopyDecls.end(); I != E; ++I) {
4105 S += " ";
4106 // Handle nested closure invocation. For example:
4107 //
4108 // void (^myImportedClosure)(void);
4109 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4110 //
4111 // void (^anotherClosure)(void);
4112 // anotherClosure = ^(void) {
4113 // myImportedClosure(); // import and invoke the closure
4114 // };
4115 //
4116 if (isTopLevelBlockPointerType((*I)->getType())) {
4117 RewriteBlockPointerTypeVariable(S, (*I));
4118 S += " = (";
4119 RewriteBlockPointerType(S, (*I)->getType());
4120 S += ")";
4121 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4122 }
4123 else {
4124 std::string Name = (*I)->getNameAsString();
4125 QualType QT = (*I)->getType();
4126 if (HasLocalVariableExternalStorage(*I))
4127 QT = Context->getPointerType(QT);
4128 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00004129 S += Name + " = __cself->" +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004130 (*I)->getNameAsString() + "; // bound by copy\n";
4131 }
4132 }
4133 std::string RewrittenStr = RewrittenBlockExprs[CE];
4134 const char *cstr = RewrittenStr.c_str();
4135 while (*cstr++ != '{') ;
4136 S += cstr;
4137 S += "\n";
4138 return S;
4139}
4140
4141std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4142 StringRef funcName,
4143 std::string Tag) {
4144 std::string StructRef = "struct " + Tag;
4145 std::string S = "static void __";
4146
4147 S += funcName;
4148 S += "_block_copy_" + utostr(i);
4149 S += "(" + StructRef;
4150 S += "*dst, " + StructRef;
4151 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004152 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004153 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004154 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004155 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004156 S += VD->getNameAsString();
4157 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004158 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4159 else if (VD->getType()->isBlockPointerType())
4160 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4161 else
4162 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4163 }
4164 S += "}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004165
Fariborz Jahanian11671902012-02-07 17:11:38 +00004166 S += "\nstatic void __";
4167 S += funcName;
4168 S += "_block_dispose_" + utostr(i);
4169 S += "(" + StructRef;
4170 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004171 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004172 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004173 S += VD->getNameAsString();
4174 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004175 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4176 else if (VD->getType()->isBlockPointerType())
4177 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4178 else
4179 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4180 }
4181 S += "}\n";
4182 return S;
4183}
4184
Fangrui Song6907ce22018-07-30 19:24:48 +00004185std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004186 std::string Desc) {
4187 std::string S = "\nstruct " + Tag;
4188 std::string Constructor = " " + Tag;
4189
4190 S += " {\n struct __block_impl impl;\n";
4191 S += " struct " + Desc;
4192 S += "* Desc;\n";
4193
4194 Constructor += "(void *fp, "; // Invoke function pointer.
4195 Constructor += "struct " + Desc; // Descriptor pointer.
4196 Constructor += " *desc";
4197
4198 if (BlockDeclRefs.size()) {
4199 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004200 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004201 E = BlockByCopyDecls.end(); I != E; ++I) {
4202 S += " ";
4203 std::string FieldName = (*I)->getNameAsString();
4204 std::string ArgName = "_" + FieldName;
4205 // Handle nested closure invocation. For example:
4206 //
4207 // void (^myImportedBlock)(void);
4208 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4209 //
4210 // void (^anotherBlock)(void);
4211 // anotherBlock = ^(void) {
4212 // myImportedBlock(); // import and invoke the closure
4213 // };
4214 //
4215 if (isTopLevelBlockPointerType((*I)->getType())) {
4216 S += "struct __block_impl *";
4217 Constructor += ", void *" + ArgName;
4218 } else {
4219 QualType QT = (*I)->getType();
4220 if (HasLocalVariableExternalStorage(*I))
4221 QT = Context->getPointerType(QT);
4222 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4223 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4224 Constructor += ", " + ArgName;
4225 }
4226 S += FieldName + ";\n";
4227 }
4228 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004229 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004230 E = BlockByRefDecls.end(); I != E; ++I) {
4231 S += " ";
4232 std::string FieldName = (*I)->getNameAsString();
4233 std::string ArgName = "_" + FieldName;
4234 {
4235 std::string TypeString;
4236 RewriteByRefString(TypeString, FieldName, (*I));
4237 TypeString += " *";
4238 FieldName = TypeString + FieldName;
4239 ArgName = TypeString + ArgName;
4240 Constructor += ", " + ArgName;
4241 }
4242 S += FieldName + "; // by ref\n";
4243 }
4244 // Finish writing the constructor.
4245 Constructor += ", int flags=0)";
4246 // Initialize all "by copy" arguments.
4247 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004248 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004249 E = BlockByCopyDecls.end(); I != E; ++I) {
4250 std::string Name = (*I)->getNameAsString();
4251 if (firsTime) {
4252 Constructor += " : ";
4253 firsTime = false;
4254 }
4255 else
4256 Constructor += ", ";
4257 if (isTopLevelBlockPointerType((*I)->getType()))
4258 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4259 else
4260 Constructor += Name + "(_" + Name + ")";
4261 }
4262 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004263 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004264 E = BlockByRefDecls.end(); I != E; ++I) {
4265 std::string Name = (*I)->getNameAsString();
4266 if (firsTime) {
4267 Constructor += " : ";
4268 firsTime = false;
4269 }
4270 else
4271 Constructor += ", ";
4272 Constructor += Name + "(_" + Name + "->__forwarding)";
4273 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004274
Fariborz Jahanian11671902012-02-07 17:11:38 +00004275 Constructor += " {\n";
4276 if (GlobalVarDecl)
4277 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4278 else
4279 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4280 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4281
4282 Constructor += " Desc = desc;\n";
4283 } else {
4284 // Finish writing the constructor.
4285 Constructor += ", int flags=0) {\n";
4286 if (GlobalVarDecl)
4287 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4288 else
4289 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4290 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4291 Constructor += " Desc = desc;\n";
4292 }
4293 Constructor += " ";
4294 Constructor += "}\n";
4295 S += Constructor;
4296 S += "};\n";
4297 return S;
4298}
4299
Fangrui Song6907ce22018-07-30 19:24:48 +00004300std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004301 std::string ImplTag, int i,
4302 StringRef FunName,
4303 unsigned hasCopy) {
4304 std::string S = "\nstatic struct " + DescTag;
Fangrui Song6907ce22018-07-30 19:24:48 +00004305
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004306 S += " {\n size_t reserved;\n";
4307 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004308 if (hasCopy) {
4309 S += " void (*copy)(struct ";
4310 S += ImplTag; S += "*, struct ";
4311 S += ImplTag; S += "*);\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004312
Fariborz Jahanian11671902012-02-07 17:11:38 +00004313 S += " void (*dispose)(struct ";
4314 S += ImplTag; S += "*);\n";
4315 }
4316 S += "} ";
4317
4318 S += DescTag + "_DATA = { 0, sizeof(struct ";
4319 S += ImplTag + ")";
4320 if (hasCopy) {
4321 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4322 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4323 }
4324 S += "};\n";
4325 return S;
4326}
4327
4328void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4329 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004330 bool RewriteSC = (GlobalVarDecl &&
4331 !Blocks.empty() &&
4332 GlobalVarDecl->getStorageClass() == SC_Static &&
4333 GlobalVarDecl->getType().getCVRQualifiers());
4334 if (RewriteSC) {
4335 std::string SC(" void __");
4336 SC += GlobalVarDecl->getNameAsString();
4337 SC += "() {}";
4338 InsertText(FunLocStart, SC);
4339 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004340
Fariborz Jahanian11671902012-02-07 17:11:38 +00004341 // Insert closures that were part of the function.
4342 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4343 CollectBlockDeclRefInfo(Blocks[i]);
4344 // Need to copy-in the inner copied-in variables not actually used in this
4345 // block.
4346 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004347 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004348 ValueDecl *VD = Exp->getDecl();
4349 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004350 if (!VD->hasAttr<BlocksAttr>()) {
4351 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4352 BlockByCopyDeclsPtrSet.insert(VD);
4353 BlockByCopyDecls.push_back(VD);
4354 }
4355 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004356 }
John McCall113bee02012-03-10 09:33:50 +00004357
4358 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004359 BlockByRefDeclsPtrSet.insert(VD);
4360 BlockByRefDecls.push_back(VD);
4361 }
John McCall113bee02012-03-10 09:33:50 +00004362
Fariborz Jahanian11671902012-02-07 17:11:38 +00004363 // imported objects in the inner blocks not used in the outer
4364 // blocks must be copied/disposed in the outer block as well.
Fangrui Song6907ce22018-07-30 19:24:48 +00004365 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004366 VD->getType()->isBlockPointerType())
4367 ImportedBlockDecls.insert(VD);
4368 }
4369
4370 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4371 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4372
4373 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4374
4375 InsertText(FunLocStart, CI);
4376
4377 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4378
4379 InsertText(FunLocStart, CF);
4380
4381 if (ImportedBlockDecls.size()) {
4382 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4383 InsertText(FunLocStart, HF);
4384 }
4385 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4386 ImportedBlockDecls.size() > 0);
4387 InsertText(FunLocStart, BD);
4388
4389 BlockDeclRefs.clear();
4390 BlockByRefDecls.clear();
4391 BlockByRefDeclsPtrSet.clear();
4392 BlockByCopyDecls.clear();
4393 BlockByCopyDeclsPtrSet.clear();
4394 ImportedBlockDecls.clear();
4395 }
4396 if (RewriteSC) {
4397 // Must insert any 'const/volatile/static here. Since it has been
4398 // removed as result of rewriting of block literals.
4399 std::string SC;
4400 if (GlobalVarDecl->getStorageClass() == SC_Static)
4401 SC = "static ";
4402 if (GlobalVarDecl->getType().isConstQualified())
4403 SC += "const ";
4404 if (GlobalVarDecl->getType().isVolatileQualified())
4405 SC += "volatile ";
4406 if (GlobalVarDecl->getType().isRestrictQualified())
4407 SC += "restrict ";
4408 InsertText(FunLocStart, SC);
4409 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004410 if (GlobalConstructionExp) {
4411 // extra fancy dance for global literal expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00004412
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004413 // Always the latest block expression on the block stack.
4414 std::string Tag = "__";
4415 Tag += FunName;
4416 Tag += "_block_impl_";
4417 Tag += utostr(Blocks.size()-1);
4418 std::string globalBuf = "static ";
4419 globalBuf += Tag; globalBuf += " ";
4420 std::string SStr;
Fangrui Song6907ce22018-07-30 19:24:48 +00004421
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004422 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004423 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4424 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004425 globalBuf += constructorExprBuf.str();
4426 globalBuf += ";\n";
4427 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004428 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004429 }
4430
Fariborz Jahanian11671902012-02-07 17:11:38 +00004431 Blocks.clear();
4432 InnerDeclRefsCount.clear();
4433 InnerDeclRefs.clear();
4434 RewrittenBlockExprs.clear();
4435}
4436
4437void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004438 SourceLocation FunLocStart =
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004439 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4440 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004441 StringRef FuncName = FD->getName();
4442
4443 SynthesizeBlockLiterals(FunLocStart, FuncName);
4444}
4445
4446static void BuildUniqueMethodName(std::string &Name,
4447 ObjCMethodDecl *MD) {
4448 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4449 Name = IFace->getName();
4450 Name += "__" + MD->getSelector().getAsString();
4451 // Convert colons to underscores.
4452 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00004453 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004454 Name.replace(loc, 1, "_");
4455}
4456
4457void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004458 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4459 // SourceLocation FunLocStart = MD->getBeginLoc();
4460 SourceLocation FunLocStart = MD->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004461 std::string FuncName;
4462 BuildUniqueMethodName(FuncName, MD);
4463 SynthesizeBlockLiterals(FunLocStart, FuncName);
4464}
4465
4466void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004467 for (Stmt *SubStmt : S->children())
4468 if (SubStmt) {
4469 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004470 GetBlockDeclRefExprs(CBE->getBody());
4471 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004472 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004473 }
4474 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004475 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004476 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004477 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004478 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004479 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004480}
4481
Craig Topper5603df42013-07-05 19:34:19 +00004482void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4483 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004484 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004485 for (Stmt *SubStmt : S->children())
4486 if (SubStmt) {
4487 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004488 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4489 GetInnerBlockDeclRefExprs(CBE->getBody(),
4490 InnerBlockDeclRefs,
4491 InnerContexts);
4492 }
4493 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004494 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004495 }
4496 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004498 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004499 HasLocalVariableExternalStorage(DRE->getDecl())) {
4500 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004501 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004502 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004503 if (Var->isFunctionOrMethodVarDecl())
4504 ImportedLocalExternalDecls.insert(Var);
4505 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004506 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004507}
4508
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004509/// convertObjCTypeToCStyleType - This routine converts such objc types
4510/// as qualified objects, and blocks to their closest c/c++ types that
4511/// it can. It returns true if input type was modified.
4512bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4513 QualType oldT = T;
4514 convertBlockPointerToFunctionPointer(T);
4515 if (T->isFunctionPointerType()) {
4516 QualType PointeeTy;
4517 if (const PointerType* PT = T->getAs<PointerType>()) {
4518 PointeeTy = PT->getPointeeType();
4519 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4520 T = convertFunctionTypeOfBlocks(FT);
4521 T = Context->getPointerType(T);
4522 }
4523 }
4524 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004525
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004526 convertToUnqualifiedObjCType(T);
4527 return T != oldT;
4528}
4529
Fariborz Jahanian11671902012-02-07 17:11:38 +00004530/// convertFunctionTypeOfBlocks - This routine converts a function type
4531/// whose result type may be a block pointer or whose argument type(s)
4532/// might be block pointers to an equivalent function type replacing
4533/// all block pointers to function pointers.
4534QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4535 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4536 // FTP will be null for closures that don't take arguments.
4537 // Generate a funky cast.
4538 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004539 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004540 bool modified = convertObjCTypeToCStyleType(Res);
Fangrui Song6907ce22018-07-30 19:24:48 +00004541
Fariborz Jahanian11671902012-02-07 17:11:38 +00004542 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004543 for (auto &I : FTP->param_types()) {
4544 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004545 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004546 if (convertObjCTypeToCStyleType(t))
4547 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004548 ArgTypes.push_back(t);
4549 }
4550 }
4551 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004552 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004553 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004554 else FuncType = QualType(FT, 0);
4555 return FuncType;
4556}
4557
4558Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4559 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004560 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004561
4562 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4563 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004564 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4565 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004566 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004567 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4568 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4569 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004570 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004571 CPT = IEXPR->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004572 else if (const ConditionalOperator *CEXPR =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004573 dyn_cast<ConditionalOperator>(BlockExp)) {
4574 Expr *LHSExp = CEXPR->getLHS();
4575 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4576 Expr *RHSExp = CEXPR->getRHS();
4577 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4578 Expr *CONDExp = CEXPR->getCond();
4579 ConditionalOperator *CondExpr =
4580 new (Context) ConditionalOperator(CONDExp,
4581 SourceLocation(), cast<Expr>(LHSStmt),
4582 SourceLocation(), cast<Expr>(RHSStmt),
4583 Exp->getType(), VK_RValue, OK_Ordinary);
4584 return CondExpr;
4585 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4586 CPT = IRE->getType()->getAs<BlockPointerType>();
4587 } else if (const PseudoObjectExpr *POE
4588 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4589 CPT = POE->getType()->castAs<BlockPointerType>();
4590 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004591 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004592 }
4593 assert(CPT && "RewriteBlockClass: Bad type");
4594 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4595 assert(FT && "RewriteBlockClass: Bad type");
4596 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4597 // FTP will be null for closures that don't take arguments.
4598
4599 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4600 SourceLocation(), SourceLocation(),
4601 &Context->Idents.get("__block_impl"));
4602 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4603
4604 // Generate a funky cast.
4605 SmallVector<QualType, 8> ArgTypes;
4606
4607 // Push the block argument type.
4608 ArgTypes.push_back(PtrBlock);
4609 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004610 for (auto &I : FTP->param_types()) {
4611 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004612 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4613 if (!convertBlockPointerToFunctionPointer(t))
4614 convertToUnqualifiedObjCType(t);
4615 ArgTypes.push_back(t);
4616 }
4617 }
4618 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004619 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004620
4621 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4622
4623 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4624 CK_BitCast,
4625 const_cast<Expr*>(BlockExp));
4626 // Don't forget the parens to enforce the proper binding.
4627 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4628 BlkCast);
4629 //PE->dump();
4630
Craig Topper8ae12032014-05-07 06:21:57 +00004631 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004632 SourceLocation(),
4633 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004634 Context->VoidPtrTy, nullptr,
4635 /*BitWidth=*/nullptr, /*Mutable=*/true,
4636 ICIS_NoInit);
4637 MemberExpr *ME =
4638 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4639 FD->getType(), VK_LValue, OK_Ordinary);
4640
4641 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4642 CK_BitCast, ME);
4643 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004644
4645 SmallVector<Expr*, 8> BlkExprs;
4646 // Add the implicit argument.
4647 BlkExprs.push_back(BlkCast);
4648 // Add the user arguments.
4649 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4650 E = Exp->arg_end(); I != E; ++I) {
4651 BlkExprs.push_back(*I);
4652 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004653 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004654 Exp->getType(), VK_RValue,
4655 SourceLocation());
4656 return CE;
4657}
4658
4659// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004660// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004661// For example:
4662//
4663// int main() {
4664// __block Foo *f;
4665// __block int i;
4666//
4667// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004668// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004669// i = 77;
4670// };
4671//}
John McCall113bee02012-03-10 09:33:50 +00004672Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004673 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004675 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004676 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004677 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004678
4679 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004680 SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004681 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004682 Context->VoidPtrTy, nullptr,
4683 /*BitWidth=*/nullptr, /*Mutable=*/true,
4684 ICIS_NoInit);
4685 MemberExpr *ME = new (Context)
4686 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4687 FD->getType(), VK_LValue, OK_Ordinary);
4688
4689 StringRef Name = VD->getName();
4690 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004691 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004692 Context->VoidPtrTy, nullptr,
4693 /*BitWidth=*/nullptr, /*Mutable=*/true,
4694 ICIS_NoInit);
4695 ME =
4696 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4697 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4698
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;
4715 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4716 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00004717 DRE->getLocation(), false);
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);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005303 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5304 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5305 VK_LValue, SourceLocation()),
5306 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5307 OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005308 InitExprs.push_back(DescRefExpr);
5309
Fariborz Jahanian11671902012-02-07 17:11:38 +00005310 // Add initializers for any closure decl refs.
5311 if (BlockDeclRefs.size()) {
5312 Expr *Exp;
5313 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005315 E = BlockByCopyDecls.end(); I != E; ++I) {
5316 if (isObjCType((*I)->getType())) {
5317 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5318 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005319 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005320 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005321 if (HasLocalVariableExternalStorage(*I)) {
5322 QualType QT = (*I)->getType();
5323 QT = Context->getPointerType(QT);
5324 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005325 OK_Ordinary, SourceLocation(),
5326 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005327 }
5328 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5329 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005330 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005331 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005332 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5333 CK_BitCast, Arg);
5334 } else {
5335 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005336 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005337 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005338 if (HasLocalVariableExternalStorage(*I)) {
5339 QualType QT = (*I)->getType();
5340 QT = Context->getPointerType(QT);
5341 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005342 OK_Ordinary, SourceLocation(),
5343 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005344 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005345
Fariborz Jahanian11671902012-02-07 17:11:38 +00005346 }
5347 InitExprs.push_back(Exp);
5348 }
5349 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005350 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005351 E = BlockByRefDecls.end(); I != E; ++I) {
5352 ValueDecl *ND = (*I);
5353 std::string Name(ND->getNameAsString());
5354 std::string RecName;
5355 RewriteByRefString(RecName, Name, ND, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005356 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
Fariborz Jahanian11671902012-02-07 17:11:38 +00005357 + sizeof("struct"));
5358 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5359 SourceLocation(), SourceLocation(),
5360 II);
5361 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5362 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00005363
Fariborz Jahanian11671902012-02-07 17:11:38 +00005364 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005365 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5366 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005367 bool isNestedCapturedVar = false;
5368 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005369 for (const auto &CI : block->captures()) {
5370 const VarDecl *variable = CI.getVariable();
5371 if (variable == ND && CI.isNested()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005372 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005373 "SynthBlockInitExpr - captured block variable is not byref");
5374 isNestedCapturedVar = true;
5375 break;
5376 }
5377 }
5378 // captured nested byref variable has its address passed. Do not take
5379 // its address again.
5380 if (!isNestedCapturedVar)
5381 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5382 Context->getPointerType(Exp->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005383 VK_RValue, OK_Ordinary, SourceLocation(),
5384 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005385 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5386 InitExprs.push_back(Exp);
5387 }
5388 }
5389 if (ImportedBlockDecls.size()) {
5390 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5391 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Fangrui Song6907ce22018-07-30 19:24:48 +00005392 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005393 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00005394 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 Context->IntTy, SourceLocation());
5396 InitExprs.push_back(FlagExp);
5397 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005398 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005399 FType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00005400
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005401 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005402 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005403 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5404 GlobalConstructionExp = NewRep;
5405 NewRep = DRE;
5406 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005407
Fariborz Jahanian11671902012-02-07 17:11:38 +00005408 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5409 Context->getPointerType(NewRep->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005410 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005411 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5412 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005413 // Put Paren around the call.
5414 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5415 NewRep);
Fangrui Song6907ce22018-07-30 19:24:48 +00005416
Fariborz Jahanian11671902012-02-07 17:11:38 +00005417 BlockDeclRefs.clear();
5418 BlockByRefDecls.clear();
5419 BlockByRefDeclsPtrSet.clear();
5420 BlockByCopyDecls.clear();
5421 BlockByCopyDeclsPtrSet.clear();
5422 ImportedBlockDecls.clear();
5423 return NewRep;
5424}
5425
5426bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005427 if (const ObjCForCollectionStmt * CS =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005428 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5429 return CS->getElement() == DS;
5430 return false;
5431}
5432
5433//===----------------------------------------------------------------------===//
5434// Function Body / Expression rewriting
5435//===----------------------------------------------------------------------===//
5436
5437Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5438 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5439 isa<DoStmt>(S) || isa<ForStmt>(S))
5440 Stmts.push_back(S);
5441 else if (isa<ObjCForCollectionStmt>(S)) {
5442 Stmts.push_back(S);
5443 ObjCBcLabelNo.push_back(++BcLabelCount);
5444 }
5445
5446 // Pseudo-object operations and ivar references need special
5447 // treatment because we're going to recursively rewrite them.
5448 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5449 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5450 return RewritePropertyOrImplicitSetter(PseudoOp);
5451 } else {
5452 return RewritePropertyOrImplicitGetter(PseudoOp);
5453 }
5454 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5455 return RewriteObjCIvarRefExpr(IvarRefExpr);
5456 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005457 else if (isa<OpaqueValueExpr>(S))
5458 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005459
5460 SourceRange OrigStmtRange = S->getSourceRange();
5461
5462 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005463 for (Stmt *&childStmt : S->children())
5464 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005465 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5466 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005467 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005468 }
5469 }
5470
5471 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005472 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005473 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5474 InnerContexts.insert(BE->getBlockDecl());
5475 ImportedLocalExternalDecls.clear();
5476 GetInnerBlockDeclRefExprs(BE->getBody(),
5477 InnerBlockDeclRefs, InnerContexts);
5478 // Rewrite the block body in place.
5479 Stmt *SaveCurrentBody = CurrentBody;
5480 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005481 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005482 // block literal on rhs of a property-dot-sytax assignment
5483 // must be replaced by its synthesize ast so getRewrittenText
5484 // works as expected. In this case, what actually ends up on RHS
5485 // is the blockTranscribed which is the helper function for the
5486 // block literal; as in: self.c = ^() {[ace ARR];};
5487 bool saveDisableReplaceStmt = DisableReplaceStmt;
5488 DisableReplaceStmt = false;
5489 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5490 DisableReplaceStmt = saveDisableReplaceStmt;
5491 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005492 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005493 ImportedLocalExternalDecls.clear();
5494 // Now we snarf the rewritten text and stash it away for later use.
5495 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5496 RewrittenBlockExprs[BE] = Str;
5497
5498 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
Fangrui Song6907ce22018-07-30 19:24:48 +00005499
Fariborz Jahanian11671902012-02-07 17:11:38 +00005500 //blockTranscribed->dump();
5501 ReplaceStmt(S, blockTranscribed);
5502 return blockTranscribed;
5503 }
5504 // Handle specific things.
5505 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5506 return RewriteAtEncode(AtEncode);
5507
5508 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5509 return RewriteAtSelector(AtSelector);
5510
5511 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5512 return RewriteObjCStringLiteral(AtString);
Fangrui Song6907ce22018-07-30 19:24:48 +00005513
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005514 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5515 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005516
Patrick Beard0caa3942012-04-19 00:25:12 +00005517 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5518 return RewriteObjCBoxedExpr(BoxedExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005519
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005520 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5521 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005522
5523 if (ObjCDictionaryLiteral *DictionaryLitExpr =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005524 dyn_cast<ObjCDictionaryLiteral>(S))
5525 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005526
5527 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5528#if 0
5529 // Before we rewrite it, put the original message expression in a comment.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005530 SourceLocation startLoc = MessExpr->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005531 SourceLocation endLoc = MessExpr->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005532
5533 const char *startBuf = SM->getCharacterData(startLoc);
5534 const char *endBuf = SM->getCharacterData(endLoc);
5535
5536 std::string messString;
5537 messString += "// ";
5538 messString.append(startBuf, endBuf-startBuf+1);
5539 messString += "\n";
5540
5541 // FIXME: Missing definition of
5542 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005543 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005544 // Tried this, but it didn't work either...
5545 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5546#endif
5547 return RewriteMessageExpr(MessExpr);
5548 }
5549
Fangrui Song6907ce22018-07-30 19:24:48 +00005550 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005551 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5552 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5553 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005554
Fariborz Jahanian11671902012-02-07 17:11:38 +00005555 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5556 return RewriteObjCTryStmt(StmtTry);
5557
5558 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5559 return RewriteObjCSynchronizedStmt(StmtTry);
5560
5561 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5562 return RewriteObjCThrowStmt(StmtThrow);
5563
5564 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5565 return RewriteObjCProtocolExpr(ProtocolExp);
5566
5567 if (ObjCForCollectionStmt *StmtForCollection =
5568 dyn_cast<ObjCForCollectionStmt>(S))
5569 return RewriteObjCForCollectionStmt(StmtForCollection,
5570 OrigStmtRange.getEnd());
5571 if (BreakStmt *StmtBreakStmt =
5572 dyn_cast<BreakStmt>(S))
5573 return RewriteBreakStmt(StmtBreakStmt);
5574 if (ContinueStmt *StmtContinueStmt =
5575 dyn_cast<ContinueStmt>(S))
5576 return RewriteContinueStmt(StmtContinueStmt);
5577
5578 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5579 // and cast exprs.
5580 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5581 // FIXME: What we're doing here is modifying the type-specifier that
5582 // precedes the first Decl. In the future the DeclGroup should have
5583 // a separate type-specifier that we can rewrite.
5584 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5585 // the context of an ObjCForCollectionStmt. For example:
5586 // NSArray *someArray;
5587 // for (id <FooProtocol> index in someArray) ;
Fangrui Song6907ce22018-07-30 19:24:48 +00005588 // This is because RewriteObjCForCollectionStmt() does textual rewriting
Fariborz Jahanian11671902012-02-07 17:11:38 +00005589 // and it depends on the original text locations/positions.
5590 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5591 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5592
5593 // Blocks rewrite rules.
5594 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5595 DI != DE; ++DI) {
5596 Decl *SD = *DI;
5597 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5598 if (isTopLevelBlockPointerType(ND->getType()))
5599 RewriteBlockPointerDecl(ND);
5600 else if (ND->getType()->isFunctionPointerType())
5601 CheckFunctionPointerDecl(ND->getType(), ND);
5602 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5603 if (VD->hasAttr<BlocksAttr>()) {
5604 static unsigned uniqueByrefDeclCount = 0;
5605 assert(!BlockByRefDeclNo.count(ND) &&
5606 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5607 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005608 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005609 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005610 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005611 RewriteTypeOfDecl(VD);
5612 }
5613 }
5614 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5615 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5616 RewriteBlockPointerDecl(TD);
5617 else if (TD->getUnderlyingType()->isFunctionPointerType())
5618 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5619 }
5620 }
5621 }
5622
5623 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5624 RewriteObjCQualifiedInterfaceTypes(CE);
5625
5626 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5627 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5628 assert(!Stmts.empty() && "Statement stack is empty");
5629 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5630 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5631 && "Statement stack mismatch");
5632 Stmts.pop_back();
5633 }
5634 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005635 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005636 ValueDecl *VD = DRE->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005637 if (VD->hasAttr<BlocksAttr>())
5638 return RewriteBlockDeclRefExpr(DRE);
5639 if (HasLocalVariableExternalStorage(VD))
5640 return RewriteLocalVariableExternalStorage(DRE);
5641 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005642
Fariborz Jahanian11671902012-02-07 17:11:38 +00005643 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5644 if (CE->getCallee()->getType()->isBlockPointerType()) {
5645 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5646 ReplaceStmt(S, BlockCall);
5647 return BlockCall;
5648 }
5649 }
5650 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5651 RewriteCastExpr(CE);
5652 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005653 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5654 RewriteImplicitCastObjCExpr(ICE);
5655 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005656#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005657
Fariborz Jahanian11671902012-02-07 17:11:38 +00005658 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5659 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5660 ICE->getSubExpr(),
5661 SourceLocation());
5662 // Get the new text.
5663 std::string SStr;
5664 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005665 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005666 const std::string &Str = Buf.str();
5667
5668 printf("CAST = %s\n", &Str[0]);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005669 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005670 delete S;
5671 return Replacement;
5672 }
5673#endif
5674 // Return this stmt unmodified.
5675 return S;
5676}
5677
5678void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005679 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005680 if (isTopLevelBlockPointerType(FD->getType()))
5681 RewriteBlockPointerDecl(FD);
5682 if (FD->getType()->isObjCQualifiedIdType() ||
5683 FD->getType()->isObjCQualifiedInterfaceType())
5684 RewriteObjCQualifiedInterfaceTypes(FD);
5685 }
5686}
5687
5688/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5689/// main file of the input.
5690void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5691 switch (D->getKind()) {
5692 case Decl::Function: {
5693 FunctionDecl *FD = cast<FunctionDecl>(D);
5694 if (FD->isOverloadedOperator())
5695 return;
5696
5697 // Since function prototypes don't have ParmDecl's, we check the function
5698 // prototype. This enables us to rewrite function declarations and
5699 // definitions using the same code.
5700 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5701
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005702 if (!FD->isThisDeclarationADefinition())
5703 break;
5704
Fariborz Jahanian11671902012-02-07 17:11:38 +00005705 // FIXME: If this should support Obj-C++, support CXXTryStmt
5706 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5707 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005708 CurrentBody = Body;
5709 Body =
5710 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5711 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005712 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005713 if (PropParentMap) {
5714 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005715 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005716 }
5717 // This synthesizes and inserts the block "impl" struct, invoke function,
5718 // and any copy/dispose helper functions.
5719 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005720 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005721 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005722 }
5723 break;
5724 }
5725 case Decl::ObjCMethod: {
5726 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5727 if (CompoundStmt *Body = MD->getCompoundBody()) {
5728 CurMethodDef = MD;
5729 CurrentBody = Body;
5730 Body =
5731 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5732 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005733 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005734 if (PropParentMap) {
5735 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005736 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005737 }
5738 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005739 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005740 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005741 }
5742 break;
5743 }
5744 case Decl::ObjCImplementation: {
5745 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5746 ClassImplementation.push_back(CI);
5747 break;
5748 }
5749 case Decl::ObjCCategoryImpl: {
5750 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5751 CategoryImplementation.push_back(CI);
5752 break;
5753 }
5754 case Decl::Var: {
5755 VarDecl *VD = cast<VarDecl>(D);
5756 RewriteObjCQualifiedInterfaceTypes(VD);
5757 if (isTopLevelBlockPointerType(VD->getType()))
5758 RewriteBlockPointerDecl(VD);
5759 else if (VD->getType()->isFunctionPointerType()) {
5760 CheckFunctionPointerDecl(VD->getType(), VD);
5761 if (VD->getInit()) {
5762 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5763 RewriteCastExpr(CE);
5764 }
5765 }
5766 } else if (VD->getType()->isRecordType()) {
5767 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5768 if (RD->isCompleteDefinition())
5769 RewriteRecordBody(RD);
5770 }
5771 if (VD->getInit()) {
5772 GlobalVarDecl = VD;
5773 CurrentBody = VD->getInit();
5774 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005775 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005776 if (PropParentMap) {
5777 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005778 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005779 }
5780 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005781 GlobalVarDecl = nullptr;
5782
Fariborz Jahanian11671902012-02-07 17:11:38 +00005783 // This is needed for blocks.
5784 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5785 RewriteCastExpr(CE);
5786 }
5787 }
5788 break;
5789 }
5790 case Decl::TypeAlias:
5791 case Decl::Typedef: {
5792 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5793 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5794 RewriteBlockPointerDecl(TD);
5795 else if (TD->getUnderlyingType()->isFunctionPointerType())
5796 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005797 else
5798 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005799 }
5800 break;
5801 }
5802 case Decl::CXXRecord:
5803 case Decl::Record: {
5804 RecordDecl *RD = cast<RecordDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00005805 if (RD->isCompleteDefinition())
Fariborz Jahanian11671902012-02-07 17:11:38 +00005806 RewriteRecordBody(RD);
5807 break;
5808 }
5809 default:
5810 break;
5811 }
5812 // Nothing yet.
5813}
5814
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005815/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5816/// protocol reference symbols in the for of:
5817/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Fangrui Song6907ce22018-07-30 19:24:48 +00005818static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005819 ObjCProtocolDecl *PDecl,
5820 std::string &Result) {
5821 // Also output .objc_protorefs$B section and its meta-data.
5822 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005823 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005824 Result += "struct _protocol_t *";
5825 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5826 Result += PDecl->getNameAsString();
5827 Result += " = &";
5828 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5829 Result += ";\n";
5830}
5831
Fariborz Jahanian11671902012-02-07 17:11:38 +00005832void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5833 if (Diags.hasErrorOccurred())
5834 return;
5835
5836 RewriteInclude();
5837
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005838 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005839 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005840 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005841 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005842 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5843 HandleTopLevelSingleDecl(FDecl);
5844 }
5845
Fariborz Jahanian11671902012-02-07 17:11:38 +00005846 // Here's a great place to add any extra declarations that may be needed.
5847 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005848 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5849 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5850 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005851 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005852
5853 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005854
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005855 if (ClassImplementation.size() || CategoryImplementation.size())
5856 RewriteImplementations();
Fangrui Song6907ce22018-07-30 19:24:48 +00005857
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005858 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5859 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5860 // Write struct declaration for the class matching its ivar declarations.
5861 // Note that for modern abi, this is postponed until the end of TU
5862 // because class extensions and the implementation might declare their own
5863 // private ivars.
5864 RewriteInterfaceDecl(CDecl);
5865 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005866
Fariborz Jahanian11671902012-02-07 17:11:38 +00005867 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5868 // we are done.
5869 if (const RewriteBuffer *RewriteBuf =
5870 Rewrite.getRewriteBufferFor(MainFileID)) {
5871 //printf("Changed:\n");
5872 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5873 } else {
5874 llvm::errs() << "No changes\n";
5875 }
5876
5877 if (ClassImplementation.size() || CategoryImplementation.size() ||
5878 ProtocolExprDecls.size()) {
5879 // Rewrite Objective-c meta data*
5880 std::string ResultStr;
5881 RewriteMetaDataIntoBuffer(ResultStr);
5882 // Emit metadata.
5883 *OutFile << ResultStr;
5884 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005885 // Emit ImageInfo;
5886 {
5887 std::string ResultStr;
5888 WriteImageInfo(ResultStr);
5889 *OutFile << ResultStr;
5890 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005891 OutFile->flush();
5892}
5893
5894void RewriteModernObjC::Initialize(ASTContext &context) {
5895 InitializeCommon(context);
Fangrui Song6907ce22018-07-30 19:24:48 +00005896
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005897 Preamble += "#ifndef __OBJC2__\n";
5898 Preamble += "#define __OBJC2__\n";
5899 Preamble += "#endif\n";
5900
Fariborz Jahanian11671902012-02-07 17:11:38 +00005901 // declaring objc_selector outside the parameter list removes a silly
5902 // scope related warning...
5903 if (IsHeader)
5904 Preamble = "#pragma once\n";
5905 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005906 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5907 Preamble += "\n\tstruct objc_object *superClass; ";
5908 // Add a constructor for creating temporary objects.
5909 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5910 Preamble += ": object(o), superClass(s) {} ";
5911 Preamble += "\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005912
Fariborz Jahanian11671902012-02-07 17:11:38 +00005913 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005914 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005915 // These are currently generated.
5916 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005917 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005918 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005919 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5920 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005921 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005922 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005923 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005925 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005926
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005927 // These need be generated for performance. Currently they are not,
5928 // using API calls instead.
5929 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5930 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5931 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005932
Fariborz Jahanian11671902012-02-07 17:11:38 +00005933 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005934 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5935 Preamble += "typedef struct objc_object Protocol;\n";
5936 Preamble += "#define _REWRITER_typedef_Protocol\n";
5937 Preamble += "#endif\n";
5938 if (LangOpts.MicrosoftExt) {
5939 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5940 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005941 }
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005942 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005943 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005944
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005945 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5946 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5950
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005951 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005952 Preamble += "(const char *);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5954 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005956 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005957 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005958 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005959 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5960 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005961 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005962 Preamble += "#ifdef _WIN64\n";
5963 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5964 Preamble += "#else\n";
5965 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5966 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005967 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5968 Preamble += "struct __objcFastEnumerationState {\n\t";
5969 Preamble += "unsigned long state;\n\t";
5970 Preamble += "void **itemsPtr;\n\t";
5971 Preamble += "unsigned long *mutationsPtr;\n\t";
5972 Preamble += "unsigned long extra[5];\n};\n";
5973 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5974 Preamble += "#define __FASTENUMERATIONSTATE\n";
5975 Preamble += "#endif\n";
5976 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5977 Preamble += "struct __NSConstantStringImpl {\n";
5978 Preamble += " int *isa;\n";
5979 Preamble += " int flags;\n";
5980 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005981 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005982 Preamble += " long long length;\n";
5983 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005984 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005985 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005986 Preamble += "};\n";
5987 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5988 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5989 Preamble += "#else\n";
5990 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5991 Preamble += "#endif\n";
5992 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5993 Preamble += "#endif\n";
5994 // Blocks preamble.
5995 Preamble += "#ifndef BLOCK_IMPL\n";
5996 Preamble += "#define BLOCK_IMPL\n";
5997 Preamble += "struct __block_impl {\n";
5998 Preamble += " void *isa;\n";
5999 Preamble += " int Flags;\n";
6000 Preamble += " int Reserved;\n";
6001 Preamble += " void *FuncPtr;\n";
6002 Preamble += "};\n";
6003 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6004 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6005 Preamble += "extern \"C\" __declspec(dllexport) "
6006 "void _Block_object_assign(void *, const void *, const int);\n";
6007 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6008 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6009 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6010 Preamble += "#else\n";
6011 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6012 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6013 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6014 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6015 Preamble += "#endif\n";
6016 Preamble += "#endif\n";
6017 if (LangOpts.MicrosoftExt) {
6018 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6019 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6020 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6021 Preamble += "#define __attribute__(X)\n";
6022 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006023 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006024 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006025 Preamble += "#endif\n";
6026 Preamble += "#ifndef __block\n";
6027 Preamble += "#define __block\n";
6028 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006029 }
6030 else {
6031 Preamble += "#define __block\n";
6032 Preamble += "#define __weak\n";
6033 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006034
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006035 // Declarations required for modern objective-c array and dictionary literals.
6036 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006037 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006038 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006039 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006040 Preamble += "\tva_list marker;\n";
6041 Preamble += "\tva_start(marker, count);\n";
6042 Preamble += "\tarr = new void *[count];\n";
6043 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6044 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6045 Preamble += "\tva_end( marker );\n";
6046 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006047 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006048 Preamble += "\tdelete[] arr;\n";
6049 Preamble += " }\n";
6050 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006051
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006052 // Declaration required for implementation of @autoreleasepool statement.
6053 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6054 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6055 Preamble += "struct __AtAutoreleasePool {\n";
6056 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6057 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6058 Preamble += " void * atautoreleasepoolobj;\n";
6059 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006060
Fariborz Jahanian11671902012-02-07 17:11:38 +00006061 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6062 // as this avoids warning in any 64bit/32bit compilation model.
6063 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6064}
6065
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00006066/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian11671902012-02-07 17:11:38 +00006067/// ivar offset.
6068void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6069 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006070 Result += "__OFFSETOFIVAR__(struct ";
6071 Result += ivar->getContainingInterface()->getNameAsString();
6072 if (LangOpts.MicrosoftExt)
6073 Result += "_IMPL";
6074 Result += ", ";
6075 if (ivar->isBitField())
6076 ObjCIvarBitfieldGroupDecl(ivar, Result);
6077 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006078 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006079 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006080}
6081
6082/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6083/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006084/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006085/// char *attributes;
6086/// }
6087
6088/// struct _prop_list_t {
6089/// uint32_t entsize; // sizeof(struct _prop_t)
6090/// uint32_t count_of_properties;
6091/// struct _prop_t prop_list[count_of_properties];
6092/// }
6093
6094/// struct _protocol_t;
6095
6096/// struct _protocol_list_t {
6097/// long protocol_count; // Note, this is 32/64 bit
6098/// struct _protocol_t * protocol_list[protocol_count];
6099/// }
6100
6101/// struct _objc_method {
6102/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006103/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006104/// char *_imp;
6105/// }
6106
6107/// struct _method_list_t {
6108/// uint32_t entsize; // sizeof(struct _objc_method)
6109/// uint32_t method_count;
6110/// struct _objc_method method_list[method_count];
6111/// }
6112
6113/// struct _protocol_t {
6114/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006115/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006116/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006117/// const struct method_list_t *instance_methods;
6118/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006119/// const struct method_list_t *optionalInstanceMethods;
6120/// const struct method_list_t *optionalClassMethods;
6121/// const struct _prop_list_t * properties;
6122/// const uint32_t size; // sizeof(struct _protocol_t)
6123/// const uint32_t flags; // = 0
6124/// const char ** extendedMethodTypes;
6125/// }
6126
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006127/// struct _ivar_t {
6128/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006129/// const char *name;
6130/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006131/// uint32_t alignment;
6132/// uint32_t size;
6133/// }
6134
6135/// struct _ivar_list_t {
6136/// uint32 entsize; // sizeof(struct _ivar_t)
6137/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006138/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006139/// }
6140
6141/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006142/// uint32_t flags;
6143/// uint32_t instanceStart;
6144/// uint32_t instanceSize;
6145/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006146/// const uint8_t *ivarLayout;
6147/// const char *name;
6148/// const struct _method_list_t *baseMethods;
6149/// const struct _protocol_list_t *baseProtocols;
6150/// const struct _ivar_list_t *ivars;
6151/// const uint8_t *weakIvarLayout;
6152/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006153/// }
6154
6155/// struct _class_t {
6156/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006157/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006158/// void *cache;
6159/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006160/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006161/// }
6162
6163/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006164/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006165/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006166/// const struct _method_list_t *instance_methods;
6167/// const struct _method_list_t *class_methods;
6168/// const struct _protocol_list_t *protocols;
6169/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006170/// }
6171
6172/// MessageRefTy - LLVM for:
6173/// struct _message_ref_t {
6174/// IMP messenger;
6175/// SEL name;
6176/// };
6177
6178/// SuperMessageRefTy - LLVM for:
6179/// struct _super_message_ref_t {
6180/// SUPER_IMP messenger;
6181/// SEL name;
6182/// };
6183
Fariborz Jahanian45489622012-03-14 18:09:23 +00006184static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006185 static bool meta_data_declared = false;
6186 if (meta_data_declared)
6187 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006188
Fariborz Jahanian11671902012-02-07 17:11:38 +00006189 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006190 Result += "\tconst char *name;\n";
6191 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006192 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006193
Fariborz Jahanian11671902012-02-07 17:11:38 +00006194 Result += "\nstruct _protocol_t;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006195
Fariborz Jahanian11671902012-02-07 17:11:38 +00006196 Result += "\nstruct _objc_method {\n";
6197 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006198 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006199 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006200 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006201
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 Result += "\nstruct _protocol_t {\n";
6203 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006204 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006205 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006206 Result += "\tconst struct method_list_t *instance_methods;\n";
6207 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006208 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6209 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6210 Result += "\tconst struct _prop_list_t * properties;\n";
6211 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6212 Result += "\tconst unsigned int flags; // = 0\n";
6213 Result += "\tconst char ** extendedMethodTypes;\n";
6214 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006215
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006216 Result += "\nstruct _ivar_t {\n";
6217 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006218 Result += "\tconst char *name;\n";
6219 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006220 Result += "\tunsigned int alignment;\n";
6221 Result += "\tunsigned int size;\n";
6222 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006223
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006224 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006225 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006226 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006227 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006228 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6229 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006230 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006231 Result += "\tconst unsigned char *ivarLayout;\n";
6232 Result += "\tconst char *name;\n";
6233 Result += "\tconst struct _method_list_t *baseMethods;\n";
6234 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6235 Result += "\tconst struct _ivar_list_t *ivars;\n";
6236 Result += "\tconst unsigned char *weakIvarLayout;\n";
6237 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006238 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006239
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006240 Result += "\nstruct _class_t {\n";
6241 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006242 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006243 Result += "\tvoid *cache;\n";
6244 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006245 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006246 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006247
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006248 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006249 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006250 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006251 Result += "\tconst struct _method_list_t *instance_methods;\n";
6252 Result += "\tconst struct _method_list_t *class_methods;\n";
6253 Result += "\tconst struct _protocol_list_t *protocols;\n";
6254 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006255 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006256
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006257 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006258 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006259 meta_data_declared = true;
6260}
6261
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006262static void Write_protocol_list_t_TypeDecl(std::string &Result,
6263 long super_protocol_count) {
6264 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6265 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6266 Result += "\tstruct _protocol_t *super_protocols[";
6267 Result += utostr(super_protocol_count); Result += "];\n";
6268 Result += "}";
6269}
6270
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006271static void Write_method_list_t_TypeDecl(std::string &Result,
6272 unsigned int method_count) {
6273 Result += "struct /*_method_list_t*/"; Result += " {\n";
6274 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6275 Result += "\tunsigned int method_count;\n";
6276 Result += "\tstruct _objc_method method_list[";
6277 Result += utostr(method_count); Result += "];\n";
6278 Result += "}";
6279}
6280
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006281static void Write__prop_list_t_TypeDecl(std::string &Result,
6282 unsigned int property_count) {
6283 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6284 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6285 Result += "\tunsigned int count_of_properties;\n";
6286 Result += "\tstruct _prop_t prop_list[";
6287 Result += utostr(property_count); Result += "];\n";
6288 Result += "}";
6289}
6290
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006291static void Write__ivar_list_t_TypeDecl(std::string &Result,
6292 unsigned int ivar_count) {
6293 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6294 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6295 Result += "\tunsigned int count;\n";
6296 Result += "\tstruct _ivar_t ivar_list[";
6297 Result += utostr(ivar_count); Result += "];\n";
6298 Result += "}";
6299}
6300
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006301static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6302 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6303 StringRef VarName,
6304 StringRef ProtocolName) {
6305 if (SuperProtocols.size() > 0) {
6306 Result += "\nstatic ";
6307 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6308 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006309 Result += ProtocolName;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006310 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6311 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6312 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6313 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00006314 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006315 Result += SuperPD->getNameAsString();
6316 if (i == e-1)
6317 Result += "\n};\n";
6318 else
6319 Result += ",\n";
6320 }
6321 }
6322}
6323
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006324static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6325 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006326 ArrayRef<ObjCMethodDecl *> Methods,
6327 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006328 StringRef TopLevelDeclName,
6329 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006330 if (Methods.size() > 0) {
6331 Result += "\nstatic ";
6332 Write_method_list_t_TypeDecl(Result, Methods.size());
6333 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006334 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006335 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6336 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6337 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6338 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6339 ObjCMethodDecl *MD = Methods[i];
6340 if (i == 0)
6341 Result += "\t{{(struct objc_selector *)\"";
6342 else
6343 Result += "\t{(struct objc_selector *)\"";
6344 Result += (MD)->getSelector().getAsString(); Result += "\"";
6345 Result += ", ";
John McCall843dfcc2016-11-29 21:57:00 +00006346 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006347 Result += "\""; Result += MethodTypeString; Result += "\"";
6348 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006349 if (!MethodImpl)
6350 Result += "0";
6351 else {
6352 Result += "(void *)";
6353 Result += RewriteObj.MethodInternalNames[MD];
6354 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006355 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006356 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006357 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006358 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006359 }
6360 Result += "};\n";
6361 }
6362}
6363
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006364static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006365 ASTContext *Context, std::string &Result,
6366 ArrayRef<ObjCPropertyDecl *> Properties,
6367 const Decl *Container,
6368 StringRef VarName,
6369 StringRef ProtocolName) {
6370 if (Properties.size() > 0) {
6371 Result += "\nstatic ";
6372 Write__prop_list_t_TypeDecl(Result, Properties.size());
6373 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006374 Result += ProtocolName;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006375 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6376 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6377 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6378 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6379 ObjCPropertyDecl *PropDecl = Properties[i];
6380 if (i == 0)
6381 Result += "\t{{\"";
6382 else
6383 Result += "\t{\"";
6384 Result += PropDecl->getName(); Result += "\",";
John McCall843dfcc2016-11-29 21:57:00 +00006385 std::string PropertyTypeString =
6386 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6387 std::string QuotePropertyTypeString;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006388 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6389 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6390 if (i == e-1)
6391 Result += "}}\n";
6392 else
6393 Result += "},\n";
6394 }
6395 Result += "};\n";
6396 }
6397}
6398
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006399// Metadata flags
6400enum MetaDataDlags {
6401 CLS = 0x0,
6402 CLS_META = 0x1,
6403 CLS_ROOT = 0x2,
6404 OBJC2_CLS_HIDDEN = 0x10,
6405 CLS_EXCEPTION = 0x20,
Fangrui Song6907ce22018-07-30 19:24:48 +00006406
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006407 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6408 CLS_HAS_IVAR_RELEASER = 0x40,
6409 /// class was compiled with -fobjc-arr
6410 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6411};
6412
Fangrui Song6907ce22018-07-30 19:24:48 +00006413static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6414 unsigned int flags,
6415 const std::string &InstanceStart,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006416 const std::string &InstanceSize,
6417 ArrayRef<ObjCMethodDecl *>baseMethods,
6418 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6419 ArrayRef<ObjCIvarDecl *>ivars,
6420 ArrayRef<ObjCPropertyDecl *>Properties,
6421 StringRef VarName,
6422 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006423 Result += "\nstatic struct _class_ro_t ";
6424 Result += VarName; Result += ClassName;
6425 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006426 Result += "\t";
6427 Result += llvm::utostr(flags); Result += ", ";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006428 Result += InstanceStart; Result += ", ";
6429 Result += InstanceSize; Result += ", \n";
6430 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006431 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6432 if (Triple.getArch() == llvm::Triple::x86_64)
6433 // uint32_t const reserved; // only when building for 64bit targets
6434 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006435 // const uint8_t * const ivarLayout;
6436 Result += "0, \n\t";
6437 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006438 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006439 if (baseMethods.size() > 0) {
6440 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006441 if (metaclass)
6442 Result += "_OBJC_$_CLASS_METHODS_";
6443 else
6444 Result += "_OBJC_$_INSTANCE_METHODS_";
6445 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006446 Result += ",\n\t";
6447 }
6448 else
6449 Result += "0, \n\t";
6450
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006451 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006452 Result += "(const struct _objc_protocol_list *)&";
6453 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6454 Result += ",\n\t";
6455 }
6456 else
6457 Result += "0, \n\t";
6458
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006459 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006460 Result += "(const struct _ivar_list_t *)&";
6461 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6462 Result += ",\n\t";
6463 }
6464 else
6465 Result += "0, \n\t";
6466
6467 // weakIvarLayout
6468 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006469 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006470 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006471 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006472 Result += ",\n";
6473 }
6474 else
6475 Result += "0, \n";
6476
6477 Result += "};\n";
6478}
6479
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006480static void Write_class_t(ASTContext *Context, std::string &Result,
6481 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006482 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6483 bool rootClass = (!CDecl->getSuperClass());
6484 const ObjCInterfaceDecl *RootClass = CDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +00006485
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006486 if (!rootClass) {
6487 // Find the Root class
6488 RootClass = CDecl->getSuperClass();
6489 while (RootClass->getSuperClass()) {
6490 RootClass = RootClass->getSuperClass();
6491 }
6492 }
6493
6494 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006495 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006496 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006497 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006498 if (CDecl->getImplementation())
6499 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006500 else
6501 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006502
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006503 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006504 Result += CDecl->getNameAsString();
6505 Result += ";\n";
6506 }
6507 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006508 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006509 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006510 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006511 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006512 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006513 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006514 else
6515 Result += "__declspec(dllimport) ";
6516
Fangrui Song6907ce22018-07-30 19:24:48 +00006517 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006518 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006519 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006520 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006521
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006522 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006523 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006524 if (RootClass->getImplementation())
6525 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006526 else
6527 Result += "__declspec(dllimport) ";
6528
Fangrui Song6907ce22018-07-30 19:24:48 +00006529 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006530 Result += VarName;
6531 Result += RootClass->getNameAsString();
6532 Result += ";\n";
6533 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006534 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006535
6536 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006537 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006538 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6539 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006540 if (metaclass) {
6541 if (!rootClass) {
6542 Result += "0, // &"; Result += VarName;
6543 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006544 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006545 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006546 Result += CDecl->getSuperClass()->getNameAsString();
6547 Result += ",\n\t";
6548 }
6549 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006550 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006551 Result += CDecl->getNameAsString();
6552 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006553 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006554 Result += ",\n\t";
6555 }
6556 }
6557 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006558 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006559 Result += CDecl->getNameAsString();
6560 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006561 if (!rootClass) {
6562 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006563 Result += CDecl->getSuperClass()->getNameAsString();
6564 Result += ",\n\t";
6565 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006566 else
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006567 Result += "0,\n\t";
6568 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006569 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6570 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6571 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006572 Result += "&_OBJC_METACLASS_RO_$_";
6573 else
6574 Result += "&_OBJC_CLASS_RO_$_";
6575 Result += CDecl->getNameAsString();
6576 Result += ",\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006577
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006578 // Add static function to initialize some of the meta-data fields.
6579 // avoid doing it twice.
6580 if (metaclass)
6581 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006582
6583 const ObjCInterfaceDecl *SuperClass =
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006584 rootClass ? CDecl : CDecl->getSuperClass();
Fangrui Song6907ce22018-07-30 19:24:48 +00006585
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006586 Result += "static void OBJC_CLASS_SETUP_$_";
6587 Result += CDecl->getNameAsString();
6588 Result += "(void ) {\n";
6589 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6590 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006591 Result += RootClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006592
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006593 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006594 Result += ".superclass = ";
6595 if (rootClass)
6596 Result += "&OBJC_CLASS_$_";
6597 else
6598 Result += "&OBJC_METACLASS_$_";
6599
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006600 Result += SuperClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006601
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006602 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6603 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006604
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006605 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6606 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6607 Result += CDecl->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006608
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006609 if (!rootClass) {
6610 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6611 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6612 Result += SuperClass->getNameAsString(); Result += ";\n";
6613 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006614
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006615 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6616 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6617 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006618}
6619
Fangrui Song6907ce22018-07-30 19:24:48 +00006620static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006621 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006622 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006623 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006624 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6625 ArrayRef<ObjCMethodDecl *> ClassMethods,
6626 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6627 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006628 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006629 StringRef ClassName = ClassDecl->getName();
Fangrui Song6907ce22018-07-30 19:24:48 +00006630 // must declare an extern class object in case this class is not implemented
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006631 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006632 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006633 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006634 if (ClassDecl->getImplementation())
6635 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006636 else
6637 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006638
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006639 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006640 Result += "OBJC_CLASS_$_"; Result += ClassName;
6641 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006642
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006643 Result += "\nstatic struct _category_t ";
6644 Result += "_OBJC_$_CATEGORY_";
6645 Result += ClassName; Result += "_$_"; Result += CatName;
6646 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6647 Result += "{\n";
6648 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006649 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006650 Result += ",\n";
6651 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006652 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006653 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6654 Result += ClassName; Result += "_$_"; Result += CatName;
6655 Result += ",\n";
6656 }
6657 else
6658 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006659
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006660 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006661 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006662 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6663 Result += ClassName; Result += "_$_"; Result += CatName;
6664 Result += ",\n";
6665 }
6666 else
6667 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006668
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006669 if (RefedProtocols.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006670 Result += "\t(const struct _protocol_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006671 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6672 Result += ClassName; Result += "_$_"; Result += CatName;
6673 Result += ",\n";
6674 }
6675 else
6676 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006677
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006678 if (ClassProperties.size() > 0) {
6679 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6680 Result += ClassName; Result += "_$_"; Result += CatName;
6681 Result += ",\n";
6682 }
6683 else
6684 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006685
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006686 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006687
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006688 // Add static function to initialize the class pointer in the category structure.
6689 Result += "static void OBJC_CATEGORY_SETUP_$_";
6690 Result += ClassDecl->getNameAsString();
6691 Result += "_$_";
6692 Result += CatName;
6693 Result += "(void ) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006694 Result += "\t_OBJC_$_CATEGORY_";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006695 Result += ClassDecl->getNameAsString();
6696 Result += "_$_";
6697 Result += CatName;
6698 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6699 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006700}
6701
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006702static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6703 ASTContext *Context, std::string &Result,
6704 ArrayRef<ObjCMethodDecl *> Methods,
6705 StringRef VarName,
6706 StringRef ProtocolName) {
6707 if (Methods.size() == 0)
6708 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006709
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006710 Result += "\nstatic const char *";
6711 Result += VarName; Result += ProtocolName;
6712 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6713 Result += "{\n";
6714 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6715 ObjCMethodDecl *MD = Methods[i];
John McCall843dfcc2016-11-29 21:57:00 +00006716 std::string MethodTypeString =
6717 Context->getObjCEncodingForMethodDecl(MD, true);
6718 std::string QuoteMethodTypeString;
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006719 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6720 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6721 if (i == e-1)
6722 Result += "\n};\n";
6723 else {
6724 Result += ",\n";
6725 }
6726 }
6727}
6728
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006729static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6730 ASTContext *Context,
Fangrui Song6907ce22018-07-30 19:24:48 +00006731 std::string &Result,
6732 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006733 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006734 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6735 // this is what happens:
6736 /**
6737 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6738 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6739 Class->getVisibility() == HiddenVisibility)
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006740 Visibility should be: HiddenVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006741 else
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006742 Visibility should be: DefaultVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006743 */
Fangrui Song6907ce22018-07-30 19:24:48 +00006744
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006745 Result += "\n";
6746 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6747 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006748 if (Context->getLangOpts().MicrosoftExt)
6749 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006750
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006751 if (!Context->getLangOpts().MicrosoftExt ||
6752 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006753 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fangrui Song6907ce22018-07-30 19:24:48 +00006754 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006755 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006756 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006757 if (Ivars[i]->isBitField())
6758 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6759 else
6760 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006761 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6762 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006763 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6764 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006765 if (Ivars[i]->isBitField()) {
6766 // skip over rest of the ivar bitfields.
6767 SKIP_BITFIELDS(i , e, Ivars);
6768 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006769 }
6770}
6771
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006772static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6773 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006774 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006775 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006776 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006777 if (OriginalIvars.size() > 0) {
6778 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6779 SmallVector<ObjCIvarDecl *, 8> Ivars;
6780 // strip off all but the first ivar bitfield from each group of ivars.
6781 // Such ivars in the ivar list table will be replaced by their grouping struct
6782 // 'ivar'.
6783 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6784 if (OriginalIvars[i]->isBitField()) {
6785 Ivars.push_back(OriginalIvars[i]);
6786 // skip over rest of the ivar bitfields.
6787 SKIP_BITFIELDS(i , e, OriginalIvars);
6788 }
6789 else
6790 Ivars.push_back(OriginalIvars[i]);
6791 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006792
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006793 Result += "\nstatic ";
6794 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6795 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006796 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006797 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6798 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6799 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6800 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6801 ObjCIvarDecl *IvarDecl = Ivars[i];
6802 if (i == 0)
6803 Result += "\t{{";
6804 else
6805 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006806 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006807 if (Ivars[i]->isBitField())
6808 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6809 else
6810 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006811 Result += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006812
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006813 Result += "\"";
6814 if (Ivars[i]->isBitField())
6815 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6816 else
6817 Result += IvarDecl->getName();
6818 Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006819
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006820 QualType IVQT = IvarDecl->getType();
6821 if (IvarDecl->isBitField())
6822 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00006823
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006824 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006825 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006826 IvarDecl);
6827 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6828 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006829
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006830 // FIXME. this alignment represents the host alignment and need be changed to
6831 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006832 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006833 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006834 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006835 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006836 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006837 if (i == e-1)
6838 Result += "}}\n";
6839 else
6840 Result += "},\n";
6841 }
6842 Result += "};\n";
6843 }
6844}
6845
Fariborz Jahanian11671902012-02-07 17:11:38 +00006846/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fangrui Song6907ce22018-07-30 19:24:48 +00006847void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006848 std::string &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006849
Fariborz Jahanian11671902012-02-07 17:11:38 +00006850 // Do not synthesize the protocol more than once.
6851 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6852 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006853 WriteModernMetadataDeclarations(Context, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006854
Fariborz Jahanian11671902012-02-07 17:11:38 +00006855 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6856 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006857 // Must write out all protocol definitions in current qualifier list,
6858 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006859 for (auto *I : PDecl->protocols())
6860 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006861
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006862 // Construct method lists.
6863 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6864 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006865 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006866 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6867 OptInstanceMethods.push_back(MD);
6868 } else {
6869 InstanceMethods.push_back(MD);
6870 }
6871 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006872
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006873 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006874 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6875 OptClassMethods.push_back(MD);
6876 } else {
6877 ClassMethods.push_back(MD);
6878 }
6879 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006880 std::vector<ObjCMethodDecl *> AllMethods;
6881 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6882 AllMethods.push_back(InstanceMethods[i]);
6883 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6884 AllMethods.push_back(ClassMethods[i]);
6885 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6886 AllMethods.push_back(OptInstanceMethods[i]);
6887 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6888 AllMethods.push_back(OptClassMethods[i]);
6889
6890 Write__extendedMethodTypes_initializer(*this, Context, Result,
6891 AllMethods,
6892 "_OBJC_PROTOCOL_METHOD_TYPES_",
6893 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006894 // Protocol's super protocol list
Fangrui Song6907ce22018-07-30 19:24:48 +00006895 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006896 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6897 "_OBJC_PROTOCOL_REFS_",
6898 PDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00006899
6900 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006901 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006902 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006903
6904 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006905 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006906 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006907
Fangrui Song6907ce22018-07-30 19:24:48 +00006908 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006909 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006910 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006911
6912 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006913 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006914 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006915
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006916 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006917 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6918 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006919 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006920 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006921 "_OBJC_PROTOCOL_PROPERTIES_",
6922 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006923
Fariborz Jahanian48985802012-02-08 00:50:52 +00006924 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006925 Result += "\n";
6926 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006927 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006928 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006929 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006930 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006931 Result += "\t0,\n"; // id is; is null
6932 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006933 if (SuperProtocols.size() > 0) {
6934 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6935 Result += PDecl->getNameAsString(); Result += ",\n";
6936 }
6937 else
6938 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006939 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006940 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006941 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006942 }
6943 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006944 Result += "\t0,\n";
6945
6946 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006947 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006948 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006949 }
6950 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006951 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006952
Fariborz Jahanian48985802012-02-08 00:50:52 +00006953 if (OptInstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006954 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006955 Result += PDecl->getNameAsString(); Result += ",\n";
6956 }
6957 else
6958 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006959
Fariborz Jahanian48985802012-02-08 00:50:52 +00006960 if (OptClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006961 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006962 Result += PDecl->getNameAsString(); Result += ",\n";
6963 }
6964 else
6965 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006966
Fariborz Jahanian48985802012-02-08 00:50:52 +00006967 if (ProtocolProperties.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006968 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006969 Result += PDecl->getNameAsString(); Result += ",\n";
6970 }
6971 else
6972 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006973
Fariborz Jahanian48985802012-02-08 00:50:52 +00006974 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6975 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006976
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006977 if (AllMethods.size() > 0) {
6978 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6979 Result += PDecl->getNameAsString();
6980 Result += "\n};\n";
6981 }
6982 else
6983 Result += "\t0\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006984
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006985 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006986 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006987 Result += "struct _protocol_t *";
6988 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6989 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6990 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006991
Fariborz Jahanian11671902012-02-07 17:11:38 +00006992 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00006993 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00006994 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00006995}
6996
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006997/// hasObjCExceptionAttribute - Return true if this class or any super
6998/// class has the __objc_exception__ attribute.
6999/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7000static bool hasObjCExceptionAttribute(ASTContext &Context,
7001 const ObjCInterfaceDecl *OID) {
7002 if (OID->hasAttr<ObjCExceptionAttr>())
7003 return true;
7004 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7005 return hasObjCExceptionAttribute(Context, Super);
7006 return false;
7007}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007008
Fariborz Jahanian11671902012-02-07 17:11:38 +00007009void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7010 std::string &Result) {
7011 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00007012
Fariborz Jahanian11671902012-02-07 17:11:38 +00007013 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007014 if (CDecl->isImplicitInterfaceDecl())
Fangrui Song6907ce22018-07-30 19:24:48 +00007015 assert(false &&
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007016 "Legacy implicit interface rewriting not supported in moder abi");
Fangrui Song6907ce22018-07-30 19:24:48 +00007017
Fariborz Jahanian45489622012-03-14 18:09:23 +00007018 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007019 SmallVector<ObjCIvarDecl *, 8> IVars;
Fangrui Song6907ce22018-07-30 19:24:48 +00007020
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007021 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7022 IVD; IVD = IVD->getNextIvar()) {
7023 // Ignore unnamed bit-fields.
7024 if (!IVD->getDeclName())
7025 continue;
7026 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007027 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007028
7029 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007030 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007031 CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00007032
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007033 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007034 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007035
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007036 // If any of our property implementations have associated getters or
7037 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007038 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007039 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007040 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007041 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007043 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007044 if (!PD)
7045 continue;
7046 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007047 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007048 InstanceMethods.push_back(Getter);
7049 if (PD->isReadOnly())
7050 continue;
7051 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007052 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007053 InstanceMethods.push_back(Setter);
7054 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007055
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007056 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7057 "_OBJC_$_INSTANCE_METHODS_",
7058 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007059
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007060 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007061
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007062 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7063 "_OBJC_$_CLASS_METHODS_",
7064 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007065
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007066 // Protocols referenced in class declaration?
7067 // Protocol's super protocol list
7068 std::vector<ObjCProtocolDecl *> RefedProtocols;
7069 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7070 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7071 E = Protocols.end();
7072 I != E; ++I) {
7073 RefedProtocols.push_back(*I);
7074 // Must write out all protocol definitions in current qualifier list,
7075 // and in their nested qualifiers before writing out current definition.
7076 RewriteObjCProtocolMetaData(*I, Result);
7077 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007078
7079 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007080 RefedProtocols,
7081 "_OBJC_CLASS_PROTOCOLS_$_",
7082 IDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007083
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007084 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007085 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7086 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007087 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007088 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007089 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007090 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007091
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007092 // Data for initializing _class_ro_t metaclass meta-data
7093 uint32_t flags = CLS_META;
7094 std::string InstanceSize;
7095 std::string InstanceStart;
Fangrui Song6907ce22018-07-30 19:24:48 +00007096
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007097 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7098 if (classIsHidden)
7099 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007100
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007101 if (!CDecl->getSuperClass())
7102 // class is root
7103 flags |= CLS_ROOT;
7104 InstanceSize = "sizeof(struct _class_t)";
7105 InstanceStart = InstanceSize;
Fangrui Song6907ce22018-07-30 19:24:48 +00007106 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007107 InstanceStart, InstanceSize,
7108 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007109 nullptr,
7110 nullptr,
7111 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007112 "_OBJC_METACLASS_RO_$_",
7113 CDecl->getNameAsString());
7114
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007115 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007116 flags = CLS;
7117 if (classIsHidden)
7118 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007119
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007120 if (hasObjCExceptionAttribute(*Context, CDecl))
7121 flags |= CLS_EXCEPTION;
7122
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007123 if (!CDecl->getSuperClass())
7124 // class is root
7125 flags |= CLS_ROOT;
Fangrui Song6907ce22018-07-30 19:24:48 +00007126
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007127 InstanceSize.clear();
7128 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007129 if (!ObjCSynthesizedStructs.count(CDecl)) {
7130 InstanceSize = "0";
7131 InstanceStart = "0";
7132 }
7133 else {
7134 InstanceSize = "sizeof(struct ";
7135 InstanceSize += CDecl->getNameAsString();
7136 InstanceSize += "_IMPL)";
Fangrui Song6907ce22018-07-30 19:24:48 +00007137
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007138 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7139 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007140 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007141 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007142 else
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007143 InstanceStart = InstanceSize;
7144 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007145 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007146 InstanceStart, InstanceSize,
7147 InstanceMethods,
7148 RefedProtocols,
7149 IVars,
7150 ClassProperties,
7151 "_OBJC_CLASS_RO_$_",
7152 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007153
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007154 Write_class_t(Context, Result,
7155 "OBJC_METACLASS_$_",
7156 CDecl, /*metaclass*/true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007157
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007158 Write_class_t(Context, Result,
7159 "OBJC_CLASS_$_",
7160 CDecl, /*metaclass*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00007161
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007162 if (ImplementationIsNonLazy(IDecl))
7163 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007164}
7165
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007166void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7167 int ClsDefCount = ClassImplementation.size();
7168 if (!ClsDefCount)
7169 return;
7170 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7171 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7172 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7173 for (int i = 0; i < ClsDefCount; i++) {
7174 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7175 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7176 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7177 Result += CDecl->getName(); Result += ",\n";
7178 }
7179 Result += "};\n";
7180}
7181
Fariborz Jahanian11671902012-02-07 17:11:38 +00007182void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7183 int ClsDefCount = ClassImplementation.size();
7184 int CatDefCount = CategoryImplementation.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00007185
Fariborz Jahanian11671902012-02-07 17:11:38 +00007186 // For each implemented class, write out all its meta data.
7187 for (int i = 0; i < ClsDefCount; i++)
7188 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007189
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007190 RewriteClassSetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007191
Fariborz Jahanian11671902012-02-07 17:11:38 +00007192 // For each implemented category, write out all its meta data.
7193 for (int i = 0; i < CatDefCount; i++)
7194 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007195
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007196 RewriteCategorySetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007197
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007198 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007199 if (LangOpts.MicrosoftExt)
7200 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007201 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7202 Result += llvm::utostr(ClsDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007203 Result +=
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007204 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7205 "regular,no_dead_strip\")))= {\n";
7206 for (int i = 0; i < ClsDefCount; i++) {
7207 Result += "\t&OBJC_CLASS_$_";
7208 Result += ClassImplementation[i]->getNameAsString();
7209 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007210 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007211 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007212
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007213 if (!DefinedNonLazyClasses.empty()) {
7214 if (LangOpts.MicrosoftExt)
7215 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7216 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7217 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7218 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7219 Result += ",\n";
7220 }
7221 Result += "};\n";
7222 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007223 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007224
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007225 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007226 if (LangOpts.MicrosoftExt)
7227 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007228 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7229 Result += llvm::utostr(CatDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007230 Result +=
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007231 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7232 "regular,no_dead_strip\")))= {\n";
7233 for (int i = 0; i < CatDefCount; i++) {
7234 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007235 Result +=
7236 CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007237 Result += "_$_";
7238 Result += CategoryImplementation[i]->getNameAsString();
7239 Result += ",\n";
7240 }
7241 Result += "};\n";
7242 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007243
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007244 if (!DefinedNonLazyCategories.empty()) {
7245 if (LangOpts.MicrosoftExt)
7246 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7247 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7248 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7249 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007250 Result +=
7251 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007252 Result += "_$_";
7253 Result += DefinedNonLazyCategories[i]->getNameAsString();
7254 Result += ",\n";
7255 }
7256 Result += "};\n";
7257 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007258}
7259
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007260void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7261 if (LangOpts.MicrosoftExt)
7262 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007263
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007264 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7265 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007266 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007267}
7268
Fariborz Jahanian11671902012-02-07 17:11:38 +00007269/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7270/// implementation.
7271void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7272 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007273 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007274 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7275 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007276 ObjCCategoryDecl *CDecl
7277 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fangrui Song6907ce22018-07-30 19:24:48 +00007278
Fariborz Jahanian11671902012-02-07 17:11:38 +00007279 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007280 FullCategoryName += "_$_";
7281 FullCategoryName += CDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00007282
Fariborz Jahanian11671902012-02-07 17:11:38 +00007283 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007284 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007285
Fariborz Jahanian11671902012-02-07 17:11:38 +00007286 // If any of our property implementations have associated getters or
7287 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007288 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007289 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007290 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007291 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007292 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007293 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007294 if (!PD)
7295 continue;
7296 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7297 InstanceMethods.push_back(Getter);
7298 if (PD->isReadOnly())
7299 continue;
7300 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7301 InstanceMethods.push_back(Setter);
7302 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007303
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007304 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7305 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7306 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007307
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007308 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007309
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007310 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7311 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7312 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007313
Fariborz Jahanian11671902012-02-07 17:11:38 +00007314 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007315 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007316 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7317 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007318 // Must write out all protocol definitions in current qualifier list,
7319 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007320 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007321
7322 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007323 RefedProtocols,
7324 "_OBJC_CATEGORY_PROTOCOLS_$_",
7325 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007326
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007327 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007328 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7329 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007330 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007331 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007332 "_OBJC_$_PROP_LIST_",
7333 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007334
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007335 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007336 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007337 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007338 InstanceMethods,
7339 ClassMethods,
7340 RefedProtocols,
7341 ClassProperties);
Fangrui Song6907ce22018-07-30 19:24:48 +00007342
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007343 // Determine if this category is also "non-lazy".
7344 if (ImplementationIsNonLazy(IDecl))
7345 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007346}
7347
7348void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7349 int CatDefCount = CategoryImplementation.size();
7350 if (!CatDefCount)
7351 return;
7352 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7353 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7354 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7355 for (int i = 0; i < CatDefCount; i++) {
7356 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7357 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7358 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7359 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7360 Result += ClassDecl->getName();
7361 Result += "_$_";
7362 Result += CatDecl->getName();
7363 Result += ",\n";
7364 }
7365 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007366}
7367
7368// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7369/// class methods.
7370template<typename MethodIterator>
7371void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7372 MethodIterator MethodEnd,
7373 bool IsInstanceMethod,
7374 StringRef prefix,
7375 StringRef ClassName,
7376 std::string &Result) {
7377 if (MethodBegin == MethodEnd) return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007378
Fariborz Jahanian11671902012-02-07 17:11:38 +00007379 if (!objc_impl_method) {
7380 /* struct _objc_method {
7381 SEL _cmd;
7382 char *method_types;
7383 void *_imp;
7384 }
7385 */
7386 Result += "\nstruct _objc_method {\n";
7387 Result += "\tSEL _cmd;\n";
7388 Result += "\tchar *method_types;\n";
7389 Result += "\tvoid *_imp;\n";
7390 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007391
Fariborz Jahanian11671902012-02-07 17:11:38 +00007392 objc_impl_method = true;
7393 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007394
Fariborz Jahanian11671902012-02-07 17:11:38 +00007395 // Build _objc_method_list for class's methods if needed
Fangrui Song6907ce22018-07-30 19:24:48 +00007396
Fariborz Jahanian11671902012-02-07 17:11:38 +00007397 /* struct {
7398 struct _objc_method_list *next_method;
7399 int method_count;
7400 struct _objc_method method_list[];
7401 }
7402 */
7403 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007404 Result += "\n";
7405 if (LangOpts.MicrosoftExt) {
7406 if (IsInstanceMethod)
7407 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7408 else
7409 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7410 }
7411 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007412 Result += "\tstruct _objc_method_list *next_method;\n";
7413 Result += "\tint method_count;\n";
7414 Result += "\tstruct _objc_method method_list[";
7415 Result += utostr(NumMethods);
7416 Result += "];\n} _OBJC_";
7417 Result += prefix;
7418 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7419 Result += "_METHODS_";
7420 Result += ClassName;
7421 Result += " __attribute__ ((used, section (\"__OBJC, __";
7422 Result += IsInstanceMethod ? "inst" : "cls";
7423 Result += "_meth\")))= ";
7424 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007425
Fariborz Jahanian11671902012-02-07 17:11:38 +00007426 Result += "\t,{{(SEL)\"";
7427 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7428 std::string MethodTypeString;
7429 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7430 Result += "\", \"";
7431 Result += MethodTypeString;
7432 Result += "\", (void *)";
7433 Result += MethodInternalNames[*MethodBegin];
7434 Result += "}\n";
7435 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7436 Result += "\t ,{(SEL)\"";
7437 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7438 std::string MethodTypeString;
7439 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7440 Result += "\", \"";
7441 Result += MethodTypeString;
7442 Result += "\", (void *)";
7443 Result += MethodInternalNames[*MethodBegin];
7444 Result += "}\n";
7445 }
7446 Result += "\t }\n};\n";
7447}
7448
7449Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7450 SourceRange OldRange = IV->getSourceRange();
7451 Expr *BaseExpr = IV->getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00007452
Fariborz Jahanian11671902012-02-07 17:11:38 +00007453 // Rewrite the base, but without actually doing replaces.
7454 {
7455 DisableReplaceStmtScope S(*this);
7456 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7457 IV->setBase(BaseExpr);
7458 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007459
Fariborz Jahanian11671902012-02-07 17:11:38 +00007460 ObjCIvarDecl *D = IV->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00007461
Fariborz Jahanian11671902012-02-07 17:11:38 +00007462 Expr *Replacement = IV;
Fangrui Song6907ce22018-07-30 19:24:48 +00007463
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7465 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007466 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007467 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7468 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007469 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007470 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7471 clsDeclared);
7472 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Fangrui Song6907ce22018-07-30 19:24:48 +00007473
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007474 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007475 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007476 if (D->isBitField())
7477 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7478 else
7479 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007480
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007481 ReferencedIvars[clsDeclared].insert(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00007482
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007483 // cast offset to "char *".
Fangrui Song6907ce22018-07-30 19:24:48 +00007484 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007485 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007486 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007487 BaseExpr);
7488 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7489 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007490 Context->UnsignedLongTy, nullptr,
7491 SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00007492 DeclRefExpr *DRE = new (Context)
7493 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7494 VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00007495 BinaryOperator *addExpr =
7496 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007497 Context->getPointerType(Context->CharTy),
Adam Nemet484aa452017-03-27 19:17:25 +00007498 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007499 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007500 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7501 SourceLocation(),
7502 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007503 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007504 if (D->isBitField())
7505 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007506
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007507 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007508 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007509 RD = RD->getDefinition();
7510 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007511 // decltype(((Foo_IMPL*)0)->bar) *
Fangrui Song6907ce22018-07-30 19:24:48 +00007512 ObjCContainerDecl *CDecl =
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007513 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7514 // ivar in class extensions requires special treatment.
7515 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7516 CDecl = CatDecl->getClassInterface();
7517 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007518 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007519 RecordDecl *RD = RecordDecl::Create(
7520 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7521 &Context->Idents.get(RecName));
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007522 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00007523 unsigned UnsignedIntSize =
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007524 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7525 Expr *Zero = IntegerLiteral::Create(*Context,
7526 llvm::APInt(UnsignedIntSize, 0),
7527 Context->UnsignedIntTy, SourceLocation());
7528 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7529 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7530 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007531 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007532 SourceLocation(),
7533 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007534 IvarT, nullptr,
7535 /*BitWidth=*/nullptr,
7536 /*Mutable=*/true, ICIS_NoInit);
7537 MemberExpr *ME = new (Context)
7538 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7539 FD->getType(), VK_LValue, OK_Ordinary);
7540 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
7551
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007552 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007553 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00007554 SourceLocation(), false);
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007555 PE = new (Context) ParenExpr(OldRange.getBegin(),
7556 OldRange.getEnd(),
7557 Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00007558
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007559 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007560 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007561 SourceLocation(),
7562 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007563 D->getType(), nullptr,
7564 /*BitWidth=*/D->getBitWidth(),
7565 /*Mutable=*/true, ICIS_NoInit);
7566 MemberExpr *ME = new (Context)
7567 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7568 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7569 Replacement = ME;
7570
7571 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007572 else
7573 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007574 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007575
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007576 ReplaceStmtWithRange(IV, Replacement, OldRange);
Fangrui Song6907ce22018-07-30 19:24:48 +00007577 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007578}
Alp Toker0621cb22014-07-16 16:48:33 +00007579
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007580#endif // CLANG_ENABLE_OBJC_REWRITER