blob: 55f81c2860836637e845c426261150cd945bbb50 [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:
42
43 enum {
44 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
45 block, ... */
46 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
47 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
48 __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 };
55
56 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 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000064
65 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;
78
79 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;
91
92 unsigned TryFinallyContainsReturnDiag;
93 // Needed for super.
94 ObjCMethodDecl *CurMethodDef;
95 RecordDecl *SuperStructDecl;
96 RecordDecl *ConstantStringDecl;
97
98 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;
121
122 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000123 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +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;
129
130 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;
Fariborz Jahanian11671902012-02-07 17:11:38 +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;
147
148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000149 llvm::DenseMap<ObjCInterfaceDecl *,
Mandeep Singh Granga2baff02017-07-06 18:49:57 +0000150 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +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;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +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;
170
171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
174 bool SavedValue;
175
176 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 }
240
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) {
268 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
269 << Old->getSourceRange();
270 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;
285 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
286 << Old->getSourceRange();
287 }
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);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318 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);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000344
345 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346
347 // 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);
Fariborz Jahanian11671902012-02-07 17:11:38 +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);
384
Fariborz Jahanian11671902012-02-07 17:11:38 +0000385 // Block rewriting.
386 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
387
388 // 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);
394
395 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396 std::string &Result);
397
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);
401 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
402 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000403
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000404 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
405
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());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000417
418 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000419 QualType returnType,
420 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());
427
428 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();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000439
440 // 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);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +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);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000459
460 // 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
465
466 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);
471 std::string SynthesizeBlockImpl(BlockExpr *CE,
472 std::string Tag, std::string Desc);
473 std::string SynthesizeBlockDescriptor(std::string DescTag,
474 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 }
515
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000516 bool convertObjCTypeToCStyleType(QualType &T);
517
Fariborz Jahanian11671902012-02-07 17:11:38 +0000518 bool needToScanForQualifiers(QualType T);
519 QualType getSuperStructType();
520 QualType getConstantStringStructType();
521 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000522
523 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000524 if (T->isObjCQualifiedIdType()) {
525 bool isConst = T.isConstQualified();
526 T = isConst ? Context->getObjCIdType().withConst()
527 : 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 }
541
542 // FIXME: This predicate seems like it would be useful to add to ASTContext.
543 bool isObjCType(QualType T) {
544 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
545 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);
565
566 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 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000592
593 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");
656
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;
751 SourceLocation StartLoc = IFace->getLocStart();
752 do {
753 if (isa<ObjCInterfaceDecl>(*DI) &&
754 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
755 StartLoc == (*DI)->getLocStart())
756 DG.push_back(*DI);
757 else
758 break;
759
760 ++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;
776 SourceLocation StartLoc = Proto->getLocStart();
777 do {
778 if (isa<ObjCProtocolDecl>(*DI) &&
779 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
780 StartLoc == (*DI)->getLocStart())
781 DG.push_back(*DI);
782 else
783 break;
784
785 ++DI;
786 } while (DI != DIEnd);
787 RewriteForwardProtocolDecl(DG);
788 continue;
789 }
790 }
791
792 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
839std::string
840RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
841 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
842
843 // 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);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +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);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000854
855 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) *
860 ObjCContainerDecl *CDecl =
861 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));
871 unsigned UnsignedIntSize =
872 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 += ")";
896
897 // ((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());
916
917}
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;
925
926 if (PID->getLocStart().isValid()) {
927 SourceLocation startLoc = PID->getLocStart();
928 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);
934 }
935 else
936 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000937
938 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
939 return; // FIXME: is this correct?
940
941 // Generate the 'getter' function.
942 ObjCPropertyDecl *PD = PID->getPropertyDecl();
943 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000944 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000945
Bill Wendling44426052012-12-20 19:22:21 +0000946 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000947 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000948 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
949 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000950 ObjCPropertyDecl::OBJC_PR_copy));
951 std::string Getr;
952 if (GenGetProperty && !objcGetPropertyDefined) {
953 objcGetPropertyDefined = true;
954 // FIXME. Is this attribute correct in all cases?
955 Getr = "\nextern \"C\" __declspec(dllimport) "
956 "id objc_getProperty(id, SEL, long, bool);\n";
957 }
958 RewriteObjCMethodDecl(OID->getContainingInterface(),
959 PD->getGetterMethodDecl(), Getr);
960 Getr += "{ ";
961 // Synthesize an explicit cast to gain access to the ivar.
962 // See objc-act.c:objc_synthesize_new_getter() for details.
963 if (GenGetProperty) {
964 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
965 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000966 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000967 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000968 FPRetType);
969 Getr += " _TYPE";
970 if (FPRetType) {
971 Getr += ")"; // close the precedence "scope" for "*".
972
973 // Now, emit the argument types (if any).
974 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
975 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000976 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000977 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000978 std::string ParamStr =
979 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000980 Getr += ParamStr;
981 }
982 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000983 if (FT->getNumParams())
984 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000985 Getr += "...";
986 }
987 Getr += ")";
988 } else
989 Getr += "()";
990 }
991 Getr += ";\n";
992 Getr += "return (_TYPE)";
993 Getr += "objc_getProperty(self, _cmd, ";
994 RewriteIvarOffsetComputation(OID, Getr);
995 Getr += ", 1)";
996 }
997 else
998 Getr += "return " + getIvarAccessString(OID);
999 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001000 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001001 }
1002
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001003 if (PD->isReadOnly() ||
1004 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001005 return;
1006
1007 // Generate the 'setter' function.
1008 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001009 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001010 ObjCPropertyDecl::OBJC_PR_copy);
1011 if (GenSetProperty && !objcSetPropertyDefined) {
1012 objcSetPropertyDefined = true;
1013 // FIXME. Is this attribute correct in all cases?
1014 Setr = "\nextern \"C\" __declspec(dllimport) "
1015 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1016 }
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00001017
Fariborz Jahanian11671902012-02-07 17:11:38 +00001018 RewriteObjCMethodDecl(OID->getContainingInterface(),
1019 PD->getSetterMethodDecl(), Setr);
1020 Setr += "{ ";
1021 // Synthesize an explicit cast to initialize the ivar.
1022 // See objc-act.c:objc_synthesize_new_setter() for details.
1023 if (GenSetProperty) {
1024 Setr += "objc_setProperty (self, _cmd, ";
1025 RewriteIvarOffsetComputation(OID, Setr);
1026 Setr += ", (id)";
1027 Setr += PD->getName();
1028 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001029 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 Setr += "0, ";
1031 else
1032 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001033 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001034 Setr += "1)";
1035 else
1036 Setr += "0)";
1037 }
1038 else {
1039 Setr += getIvarAccessString(OID) + " = ";
1040 Setr += PD->getName();
1041 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001042 Setr += "; }\n";
1043 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001044}
1045
1046static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1047 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001048 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001049 typedefString += ForwardDecl->getNameAsString();
1050 typedefString += "\n";
1051 typedefString += "#define _REWRITER_typedef_";
1052 typedefString += ForwardDecl->getNameAsString();
1053 typedefString += "\n";
1054 typedefString += "typedef struct objc_object ";
1055 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001056 // typedef struct { } _objc_exc_Classname;
1057 typedefString += ";\ntypedef struct {} _objc_exc_";
1058 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001059 typedefString += ";\n#endif\n";
1060}
1061
1062void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1063 const std::string &typedefString) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001064 SourceLocation startLoc = ClassDecl->getLocStart();
1065 const char *startBuf = SM->getCharacterData(startLoc);
1066 const char *semiPtr = strchr(startBuf, ';');
1067 // Replace the @class with typedefs corresponding to the classes.
1068 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069}
1070
1071void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1072 std::string typedefString;
1073 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001074 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1075 if (I == D.begin()) {
1076 // Translate to typedef's that forward reference structs with the same name
1077 // as the class. As a convenience, we include the original declaration
1078 // as a comment.
1079 typedefString += "// @class ";
1080 typedefString += ForwardDecl->getNameAsString();
1081 typedefString += ";";
1082 }
1083 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001084 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001085 else
1086 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001087 }
1088 DeclGroupRef::iterator I = D.begin();
1089 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1090}
1091
1092void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001093 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001094 std::string typedefString;
1095 for (unsigned i = 0; i < D.size(); i++) {
1096 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1097 if (i == 0) {
1098 typedefString += "// @class ";
1099 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001100 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001101 }
1102 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1103 }
1104 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1105}
1106
1107void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1108 // When method is a synthesized one, such as a getter/setter there is
1109 // nothing to rewrite.
1110 if (Method->isImplicit())
1111 return;
1112 SourceLocation LocStart = Method->getLocStart();
1113 SourceLocation LocEnd = Method->getLocEnd();
1114
1115 if (SM->getExpansionLineNumber(LocEnd) >
1116 SM->getExpansionLineNumber(LocStart)) {
1117 InsertText(LocStart, "#if 0\n");
1118 ReplaceText(LocEnd, 1, ";\n#endif\n");
1119 } else {
1120 InsertText(LocStart, "// ");
1121 }
1122}
1123
1124void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1125 SourceLocation Loc = prop->getAtLoc();
1126
1127 ReplaceText(Loc, 0, "// ");
1128 // FIXME: handle properties that are declared across multiple lines.
1129}
1130
1131void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1132 SourceLocation LocStart = CatDecl->getLocStart();
1133
1134 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001135 if (CatDecl->getIvarRBraceLoc().isValid()) {
1136 ReplaceText(LocStart, 1, "/** ");
1137 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1138 }
1139 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001140 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001141 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001142
Manman Rena7a8b1f2016-01-26 18:05:23 +00001143 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001144 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001145
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001146 for (auto *I : CatDecl->instance_methods())
1147 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001148 for (auto *I : CatDecl->class_methods())
1149 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001150
1151 // Lastly, comment out the @end.
1152 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001153 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001154}
1155
1156void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1157 SourceLocation LocStart = PDecl->getLocStart();
1158 assert(PDecl->isThisDeclarationADefinition());
1159
1160 // FIXME: handle protocol headers that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1162
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001163 for (auto *I : PDecl->instance_methods())
1164 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001165 for (auto *I : PDecl->class_methods())
1166 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001167 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001168 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001169
1170 // Lastly, comment out the @end.
1171 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001172 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001173
1174 // Must comment out @optional/@required
1175 const char *startBuf = SM->getCharacterData(LocStart);
1176 const char *endBuf = SM->getCharacterData(LocEnd);
1177 for (const char *p = startBuf; p < endBuf; p++) {
1178 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1179 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1180 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1181
1182 }
1183 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1184 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1185 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1186
1187 }
1188 }
1189}
1190
1191void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1192 SourceLocation LocStart = (*D.begin())->getLocStart();
1193 if (LocStart.isInvalid())
1194 llvm_unreachable("Invalid SourceLocation");
1195 // FIXME: handle forward protocol that are declared across multiple lines.
1196 ReplaceText(LocStart, 0, "// ");
1197}
1198
1199void
Craig Topper5603df42013-07-05 19:34:19 +00001200RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001201 SourceLocation LocStart = DG[0]->getLocStart();
1202 if (LocStart.isInvalid())
1203 llvm_unreachable("Invalid SourceLocation");
1204 // FIXME: handle forward protocol that are declared across multiple lines.
1205 ReplaceText(LocStart, 0, "// ");
1206}
1207
1208void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1209 const FunctionType *&FPRetType) {
1210 if (T->isObjCQualifiedIdType())
1211 ResultStr += "id";
1212 else if (T->isFunctionPointerType() ||
1213 T->isBlockPointerType()) {
1214 // needs special handling, since pointer-to-functions have special
1215 // syntax (where a decaration models use).
1216 QualType retType = T;
1217 QualType PointeeTy;
1218 if (const PointerType* PT = retType->getAs<PointerType>())
1219 PointeeTy = PT->getPointeeType();
1220 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1221 PointeeTy = BPT->getPointeeType();
1222 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001223 ResultStr +=
1224 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001225 ResultStr += "(*";
1226 }
1227 } else
1228 ResultStr += T.getAsString(Context->getPrintingPolicy());
1229}
1230
1231void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1232 ObjCMethodDecl *OMD,
1233 std::string &ResultStr) {
1234 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001235 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001236 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001237 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001238 ResultStr += " ";
1239
1240 // Unique method name
1241 std::string NameStr;
1242
1243 if (OMD->isInstanceMethod())
1244 NameStr += "_I_";
1245 else
1246 NameStr += "_C_";
1247
1248 NameStr += IDecl->getNameAsString();
1249 NameStr += "_";
1250
1251 if (ObjCCategoryImplDecl *CID =
1252 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1253 NameStr += CID->getNameAsString();
1254 NameStr += "_";
1255 }
1256 // Append selector names, replacing ':' with '_'
1257 {
1258 std::string selString = OMD->getSelector().getAsString();
1259 int len = selString.size();
1260 for (int i = 0; i < len; i++)
1261 if (selString[i] == ':')
1262 selString[i] = '_';
1263 NameStr += selString;
1264 }
1265 // Remember this name for metadata emission
1266 MethodInternalNames[OMD] = NameStr;
1267 ResultStr += NameStr;
1268
1269 // Rewrite arguments
1270 ResultStr += "(";
1271
1272 // invisible arguments
1273 if (OMD->isInstanceMethod()) {
1274 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1275 selfTy = Context->getPointerType(selfTy);
1276 if (!LangOpts.MicrosoftExt) {
1277 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1278 ResultStr += "struct ";
1279 }
1280 // When rewriting for Microsoft, explicitly omit the structure name.
1281 ResultStr += IDecl->getNameAsString();
1282 ResultStr += " *";
1283 }
1284 else
1285 ResultStr += Context->getObjCClassType().getAsString(
1286 Context->getPrintingPolicy());
1287
1288 ResultStr += " self, ";
1289 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1290 ResultStr += " _cmd";
1291
1292 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001293 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001294 ResultStr += ", ";
1295 if (PDecl->getType()->isObjCQualifiedIdType()) {
1296 ResultStr += "id ";
1297 ResultStr += PDecl->getNameAsString();
1298 } else {
1299 std::string Name = PDecl->getNameAsString();
1300 QualType QT = PDecl->getType();
1301 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001302 (void)convertBlockPointerToFunctionPointer(QT);
1303 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001304 ResultStr += Name;
1305 }
1306 }
1307 if (OMD->isVariadic())
1308 ResultStr += ", ...";
1309 ResultStr += ") ";
1310
1311 if (FPRetType) {
1312 ResultStr += ")"; // close the precedence "scope" for "*".
1313
1314 // Now, emit the argument types (if any).
1315 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1316 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001317 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001318 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001319 std::string ParamStr =
1320 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001321 ResultStr += ParamStr;
1322 }
1323 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001324 if (FT->getNumParams())
1325 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001326 ResultStr += "...";
1327 }
1328 ResultStr += ")";
1329 } else {
1330 ResultStr += "()";
1331 }
1332 }
1333}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001334
Fariborz Jahanian11671902012-02-07 17:11:38 +00001335void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1336 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1337 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1338
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001339 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001340 if (IMD->getIvarRBraceLoc().isValid()) {
1341 ReplaceText(IMD->getLocStart(), 1, "/** ");
1342 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001343 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001344 else {
1345 InsertText(IMD->getLocStart(), "// ");
1346 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001347 }
1348 else
1349 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001350
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001351 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001352 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001353 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1354 SourceLocation LocStart = OMD->getLocStart();
1355 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1356
1357 const char *startBuf = SM->getCharacterData(LocStart);
1358 const char *endBuf = SM->getCharacterData(LocEnd);
1359 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1360 }
1361
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001362 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001363 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001364 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1365 SourceLocation LocStart = OMD->getLocStart();
1366 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1367
1368 const char *startBuf = SM->getCharacterData(LocStart);
1369 const char *endBuf = SM->getCharacterData(LocEnd);
1370 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1371 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001372 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1373 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001374
1375 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1376}
1377
1378void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001379 // Do not synthesize more than once.
1380 if (ObjCSynthesizedStructs.count(ClassDecl))
1381 return;
1382 // Make sure super class's are written before current class is written.
1383 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1384 while (SuperClass) {
1385 RewriteInterfaceDecl(SuperClass);
1386 SuperClass = SuperClass->getSuperClass();
1387 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001388 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001389 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001390 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001391 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001392 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1393
Fariborz Jahanianff513382012-02-15 22:01:47 +00001394 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001395 // Mark this typedef as having been written into its c++ equivalent.
1396 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001397
Manman Rena7a8b1f2016-01-26 18:05:23 +00001398 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001399 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001400 for (auto *I : ClassDecl->instance_methods())
1401 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001402 for (auto *I : ClassDecl->class_methods())
1403 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001404
Fariborz Jahanianff513382012-02-15 22:01:47 +00001405 // Lastly, comment out the @end.
1406 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001407 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001408 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001409}
1410
1411Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1412 SourceRange OldRange = PseudoOp->getSourceRange();
1413
1414 // We just magically know some things about the structure of this
1415 // expression.
1416 ObjCMessageExpr *OldMsg =
1417 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1418 PseudoOp->getNumSemanticExprs() - 1));
1419
1420 // Because the rewriter doesn't allow us to rewrite rewritten code,
1421 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001422 Expr *Base;
1423 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001424 {
1425 DisableReplaceStmtScope S(*this);
1426
1427 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001428 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001429 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1430 Base = OldMsg->getInstanceReceiver();
1431 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1432 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1433 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001434
1435 unsigned numArgs = OldMsg->getNumArgs();
1436 for (unsigned i = 0; i < numArgs; i++) {
1437 Expr *Arg = OldMsg->getArg(i);
1438 if (isa<OpaqueValueExpr>(Arg))
1439 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1440 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1441 Args.push_back(Arg);
1442 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001443 }
1444
1445 // TODO: avoid this copy.
1446 SmallVector<SourceLocation, 1> SelLocs;
1447 OldMsg->getSelectorLocs(SelLocs);
1448
Craig Topper8ae12032014-05-07 06:21:57 +00001449 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001450 switch (OldMsg->getReceiverKind()) {
1451 case ObjCMessageExpr::Class:
1452 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1453 OldMsg->getValueKind(),
1454 OldMsg->getLeftLoc(),
1455 OldMsg->getClassReceiverTypeInfo(),
1456 OldMsg->getSelector(),
1457 SelLocs,
1458 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001459 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001460 OldMsg->getRightLoc(),
1461 OldMsg->isImplicit());
1462 break;
1463
1464 case ObjCMessageExpr::Instance:
1465 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1466 OldMsg->getValueKind(),
1467 OldMsg->getLeftLoc(),
1468 Base,
1469 OldMsg->getSelector(),
1470 SelLocs,
1471 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001472 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001473 OldMsg->getRightLoc(),
1474 OldMsg->isImplicit());
1475 break;
1476
1477 case ObjCMessageExpr::SuperClass:
1478 case ObjCMessageExpr::SuperInstance:
1479 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1480 OldMsg->getValueKind(),
1481 OldMsg->getLeftLoc(),
1482 OldMsg->getSuperLoc(),
1483 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1484 OldMsg->getSuperType(),
1485 OldMsg->getSelector(),
1486 SelLocs,
1487 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001488 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001489 OldMsg->getRightLoc(),
1490 OldMsg->isImplicit());
1491 break;
1492 }
1493
1494 Stmt *Replacement = SynthMessageExpr(NewMsg);
1495 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1496 return Replacement;
1497}
1498
1499Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1500 SourceRange OldRange = PseudoOp->getSourceRange();
1501
1502 // We just magically know some things about the structure of this
1503 // expression.
1504 ObjCMessageExpr *OldMsg =
1505 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1506
1507 // Because the rewriter doesn't allow us to rewrite rewritten code,
1508 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001509 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001510 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001511 {
1512 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001513 // Rebuild the base expression if we have one.
1514 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1515 Base = OldMsg->getInstanceReceiver();
1516 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1517 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1518 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001519 unsigned numArgs = OldMsg->getNumArgs();
1520 for (unsigned i = 0; i < numArgs; i++) {
1521 Expr *Arg = OldMsg->getArg(i);
1522 if (isa<OpaqueValueExpr>(Arg))
1523 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1524 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1525 Args.push_back(Arg);
1526 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001527 }
1528
1529 // Intentionally empty.
1530 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001531
Craig Topper8ae12032014-05-07 06:21:57 +00001532 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001533 switch (OldMsg->getReceiverKind()) {
1534 case ObjCMessageExpr::Class:
1535 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1536 OldMsg->getValueKind(),
1537 OldMsg->getLeftLoc(),
1538 OldMsg->getClassReceiverTypeInfo(),
1539 OldMsg->getSelector(),
1540 SelLocs,
1541 OldMsg->getMethodDecl(),
1542 Args,
1543 OldMsg->getRightLoc(),
1544 OldMsg->isImplicit());
1545 break;
1546
1547 case ObjCMessageExpr::Instance:
1548 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1549 OldMsg->getValueKind(),
1550 OldMsg->getLeftLoc(),
1551 Base,
1552 OldMsg->getSelector(),
1553 SelLocs,
1554 OldMsg->getMethodDecl(),
1555 Args,
1556 OldMsg->getRightLoc(),
1557 OldMsg->isImplicit());
1558 break;
1559
1560 case ObjCMessageExpr::SuperClass:
1561 case ObjCMessageExpr::SuperInstance:
1562 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1563 OldMsg->getValueKind(),
1564 OldMsg->getLeftLoc(),
1565 OldMsg->getSuperLoc(),
1566 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1567 OldMsg->getSuperType(),
1568 OldMsg->getSelector(),
1569 SelLocs,
1570 OldMsg->getMethodDecl(),
1571 Args,
1572 OldMsg->getRightLoc(),
1573 OldMsg->isImplicit());
1574 break;
1575 }
1576
1577 Stmt *Replacement = SynthMessageExpr(NewMsg);
1578 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1579 return Replacement;
1580}
1581
1582/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001583/// ((NSUInteger (*)
1584/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001585/// (void *)objc_msgSend)((id)l_collection,
1586/// sel_registerName(
1587/// "countByEnumeratingWithState:objects:count:"),
1588/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001589/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001590///
1591void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001592 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1593 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001594 buf += "\n\t\t";
1595 buf += "((id)l_collection,\n\t\t";
1596 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1597 buf += "\n\t\t";
1598 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001599 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001600}
1601
1602/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1603/// statement to exit to its outer synthesized loop.
1604///
1605Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1606 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1607 return S;
1608 // replace break with goto __break_label
1609 std::string buf;
1610
1611 SourceLocation startLoc = S->getLocStart();
1612 buf = "goto __break_label_";
1613 buf += utostr(ObjCBcLabelNo.back());
1614 ReplaceText(startLoc, strlen("break"), buf);
1615
Craig Topper8ae12032014-05-07 06:21:57 +00001616 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001617}
1618
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001619void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1620 SourceLocation Loc,
1621 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001622 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001623 LineString += "\n#line ";
1624 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1625 LineString += utostr(PLoc.getLine());
1626 LineString += " \"";
1627 LineString += Lexer::Stringify(PLoc.getFilename());
1628 LineString += "\"\n";
1629 }
1630}
1631
Fariborz Jahanian11671902012-02-07 17:11:38 +00001632/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1633/// statement to continue with its inner synthesized loop.
1634///
1635Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1636 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1637 return S;
1638 // replace continue with goto __continue_label
1639 std::string buf;
1640
1641 SourceLocation startLoc = S->getLocStart();
1642 buf = "goto __continue_label_";
1643 buf += utostr(ObjCBcLabelNo.back());
1644 ReplaceText(startLoc, strlen("continue"), buf);
1645
Craig Topper8ae12032014-05-07 06:21:57 +00001646 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001647}
1648
1649/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1650/// It rewrites:
1651/// for ( type elem in collection) { stmts; }
1652
1653/// Into:
1654/// {
1655/// type elem;
1656/// struct __objcFastEnumerationState enumState = { 0 };
1657/// id __rw_items[16];
1658/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001659/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001660/// objects:__rw_items count:16];
1661/// if (limit) {
1662/// unsigned long startMutations = *enumState.mutationsPtr;
1663/// do {
1664/// unsigned long counter = 0;
1665/// do {
1666/// if (startMutations != *enumState.mutationsPtr)
1667/// objc_enumerationMutation(l_collection);
1668/// elem = (type)enumState.itemsPtr[counter++];
1669/// stmts;
1670/// __continue_label: ;
1671/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001672/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1673/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001674/// elem = nil;
1675/// __break_label: ;
1676/// }
1677/// else
1678/// elem = nil;
1679/// }
1680///
1681Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1682 SourceLocation OrigEnd) {
1683 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1684 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1685 "ObjCForCollectionStmt Statement stack mismatch");
1686 assert(!ObjCBcLabelNo.empty() &&
1687 "ObjCForCollectionStmt - Label No stack empty");
1688
1689 SourceLocation startLoc = S->getLocStart();
1690 const char *startBuf = SM->getCharacterData(startLoc);
1691 StringRef elementName;
1692 std::string elementTypeAsString;
1693 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001694 // line directive first.
1695 SourceLocation ForEachLoc = S->getForLoc();
1696 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1697 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001698 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1699 // type elem;
1700 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1701 QualType ElementType = cast<ValueDecl>(D)->getType();
1702 if (ElementType->isObjCQualifiedIdType() ||
1703 ElementType->isObjCQualifiedInterfaceType())
1704 // Simply use 'id' for all qualified types.
1705 elementTypeAsString = "id";
1706 else
1707 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1708 buf += elementTypeAsString;
1709 buf += " ";
1710 elementName = D->getName();
1711 buf += elementName;
1712 buf += ";\n\t";
1713 }
1714 else {
1715 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1716 elementName = DR->getDecl()->getName();
1717 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1718 if (VD->getType()->isObjCQualifiedIdType() ||
1719 VD->getType()->isObjCQualifiedInterfaceType())
1720 // Simply use 'id' for all qualified types.
1721 elementTypeAsString = "id";
1722 else
1723 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1724 }
1725
1726 // struct __objcFastEnumerationState enumState = { 0 };
1727 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1728 // id __rw_items[16];
1729 buf += "id __rw_items[16];\n\t";
1730 // id l_collection = (id)
1731 buf += "id l_collection = (id)";
1732 // Find start location of 'collection' the hard way!
1733 const char *startCollectionBuf = startBuf;
1734 startCollectionBuf += 3; // skip 'for'
1735 startCollectionBuf = strchr(startCollectionBuf, '(');
1736 startCollectionBuf++; // skip '('
1737 // find 'in' and skip it.
1738 while (*startCollectionBuf != ' ' ||
1739 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1740 (*(startCollectionBuf+3) != ' ' &&
1741 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1742 startCollectionBuf++;
1743 startCollectionBuf += 3;
1744
1745 // Replace: "for (type element in" with string constructed thus far.
1746 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1747 // Replace ')' in for '(' type elem in collection ')' with ';'
1748 SourceLocation rightParenLoc = S->getRParenLoc();
1749 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1750 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1751 buf = ";\n\t";
1752
1753 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1754 // objects:__rw_items count:16];
1755 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001756 // NSUInteger limit =
1757 // ((NSUInteger (*)
1758 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001759 // (void *)objc_msgSend)((id)l_collection,
1760 // sel_registerName(
1761 // "countByEnumeratingWithState:objects:count:"),
1762 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001763 // (id *)__rw_items, (NSUInteger)16);
1764 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001765 SynthCountByEnumWithState(buf);
1766 buf += ";\n\t";
1767 /// if (limit) {
1768 /// unsigned long startMutations = *enumState.mutationsPtr;
1769 /// do {
1770 /// unsigned long counter = 0;
1771 /// do {
1772 /// if (startMutations != *enumState.mutationsPtr)
1773 /// objc_enumerationMutation(l_collection);
1774 /// elem = (type)enumState.itemsPtr[counter++];
1775 buf += "if (limit) {\n\t";
1776 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1777 buf += "do {\n\t\t";
1778 buf += "unsigned long counter = 0;\n\t\t";
1779 buf += "do {\n\t\t\t";
1780 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1781 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1782 buf += elementName;
1783 buf += " = (";
1784 buf += elementTypeAsString;
1785 buf += ")enumState.itemsPtr[counter++];";
1786 // Replace ')' in for '(' type elem in collection ')' with all of these.
1787 ReplaceText(lparenLoc, 1, buf);
1788
1789 /// __continue_label: ;
1790 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001791 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1792 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001793 /// elem = nil;
1794 /// __break_label: ;
1795 /// }
1796 /// else
1797 /// elem = nil;
1798 /// }
1799 ///
1800 buf = ";\n\t";
1801 buf += "__continue_label_";
1802 buf += utostr(ObjCBcLabelNo.back());
1803 buf += ": ;";
1804 buf += "\n\t\t";
1805 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001806 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001807 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001808 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001809 buf += elementName;
1810 buf += " = ((";
1811 buf += elementTypeAsString;
1812 buf += ")0);\n\t";
1813 buf += "__break_label_";
1814 buf += utostr(ObjCBcLabelNo.back());
1815 buf += ": ;\n\t";
1816 buf += "}\n\t";
1817 buf += "else\n\t\t";
1818 buf += elementName;
1819 buf += " = ((";
1820 buf += elementTypeAsString;
1821 buf += ")0);\n\t";
1822 buf += "}\n";
1823
1824 // Insert all these *after* the statement body.
1825 // FIXME: If this should support Obj-C++, support CXXTryStmt
1826 if (isa<CompoundStmt>(S->getBody())) {
1827 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1828 InsertText(endBodyLoc, buf);
1829 } else {
1830 /* Need to treat single statements specially. For example:
1831 *
1832 * for (A *a in b) if (stuff()) break;
1833 * for (A *a in b) xxxyy;
1834 *
1835 * The following code simply scans ahead to the semi to find the actual end.
1836 */
1837 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1838 const char *semiBuf = strchr(stmtBuf, ';');
1839 assert(semiBuf && "Can't find ';'");
1840 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1841 InsertText(endBodyLoc, buf);
1842 }
1843 Stmts.pop_back();
1844 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001845 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001846}
1847
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001848static void Write_RethrowObject(std::string &buf) {
1849 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1850 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1851 buf += "\tid rethrow;\n";
1852 buf += "\t} _fin_force_rethow(_rethrow);";
1853}
1854
Fariborz Jahanian11671902012-02-07 17:11:38 +00001855/// RewriteObjCSynchronizedStmt -
1856/// This routine rewrites @synchronized(expr) stmt;
1857/// into:
1858/// objc_sync_enter(expr);
1859/// @try stmt @finally { objc_sync_exit(expr); }
1860///
1861Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1862 // Get the start location and compute the semi location.
1863 SourceLocation startLoc = S->getLocStart();
1864 const char *startBuf = SM->getCharacterData(startLoc);
1865
1866 assert((*startBuf == '@') && "bogus @synchronized location");
1867
1868 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001869 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1870 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001871 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001872
Fariborz Jahanian11671902012-02-07 17:11:38 +00001873 const char *lparenBuf = startBuf;
1874 while (*lparenBuf != '(') lparenBuf++;
1875 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001876
1877 buf = "; objc_sync_enter(_sync_obj);\n";
1878 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1879 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1880 buf += "\n\tid sync_exit;";
1881 buf += "\n\t} _sync_exit(_sync_obj);\n";
1882
1883 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1884 // the sync expression is typically a message expression that's already
1885 // been rewritten! (which implies the SourceLocation's are invalid).
1886 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1887 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1888 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1889 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1890
1891 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1892 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1893 assert (*LBraceLocBuf == '{');
1894 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001895
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001896 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001897 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1898 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001899
1900 buf = "} catch (id e) {_rethrow = e;}\n";
1901 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001902 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001903 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001904
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001905 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001906
Craig Topper8ae12032014-05-07 06:21:57 +00001907 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001908}
1909
1910void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1911{
1912 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001913 for (Stmt *SubStmt : S->children())
1914 if (SubStmt)
1915 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001916
1917 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1918 Diags.Report(Context->getFullLoc(S->getLocStart()),
1919 TryFinallyContainsReturnDiag);
1920 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001921}
1922
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001923Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1924 SourceLocation startLoc = S->getAtLoc();
1925 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001926 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1927 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001928
1929 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001930}
1931
Fariborz Jahanian11671902012-02-07 17:11:38 +00001932Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001933 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001934 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001935 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001936 SourceLocation TryLocation = S->getAtTryLoc();
1937 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001938
1939 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001940 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001941 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001942 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001943 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001944 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001945 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001946 // Get the start location and compute the semi location.
1947 SourceLocation startLoc = S->getLocStart();
1948 const char *startBuf = SM->getCharacterData(startLoc);
1949
1950 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001951 if (finalStmt)
1952 ReplaceText(startLoc, 1, buf);
1953 else
1954 // @try -> try
1955 ReplaceText(startLoc, 1, "");
1956
Fariborz Jahanian11671902012-02-07 17:11:38 +00001957 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1958 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001959 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001960
Fariborz Jahanian11671902012-02-07 17:11:38 +00001961 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001962 bool AtRemoved = false;
1963 if (catchDecl) {
1964 QualType t = catchDecl->getType();
1965 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1966 // Should be a pointer to a class.
1967 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1968 if (IDecl) {
1969 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001970 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1971
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001972 startBuf = SM->getCharacterData(startLoc);
1973 assert((*startBuf == '@') && "bogus @catch location");
1974 SourceLocation rParenLoc = Catch->getRParenLoc();
1975 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1976
1977 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001978 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001979 Result += " *_"; Result += catchDecl->getNameAsString();
1980 Result += ")";
1981 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1982 // Foo *e = (Foo *)_e;
1983 Result.clear();
1984 Result = "{ ";
1985 Result += IDecl->getNameAsString();
1986 Result += " *"; Result += catchDecl->getNameAsString();
1987 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1988 Result += "_"; Result += catchDecl->getNameAsString();
1989
1990 Result += "; ";
1991 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1992 ReplaceText(lBraceLoc, 1, Result);
1993 AtRemoved = true;
1994 }
1995 }
1996 }
1997 if (!AtRemoved)
1998 // @catch -> catch
1999 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002000
Fariborz Jahanian11671902012-02-07 17:11:38 +00002001 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002002 if (finalStmt) {
2003 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002004 SourceLocation FinallyLoc = finalStmt->getLocStart();
2005
2006 if (noCatch) {
2007 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2008 buf += "catch (id e) {_rethrow = e;}\n";
2009 }
2010 else {
2011 buf += "}\n";
2012 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2013 buf += "catch (id e) {_rethrow = e;}\n";
2014 }
2015
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002016 SourceLocation startFinalLoc = finalStmt->getLocStart();
2017 ReplaceText(startFinalLoc, 8, buf);
2018 Stmt *body = finalStmt->getFinallyBody();
2019 SourceLocation startFinalBodyLoc = body->getLocStart();
2020 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002021 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002022 ReplaceText(startFinalBodyLoc, 1, buf);
2023
2024 SourceLocation endFinalBodyLoc = body->getLocEnd();
2025 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002026 // Now check for any return/continue/go statements within the @try.
2027 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002028 }
2029
Craig Topper8ae12032014-05-07 06:21:57 +00002030 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002031}
2032
2033// This can't be done with ReplaceStmt(S, ThrowExpr), since
2034// the throw expression is typically a message expression that's already
2035// been rewritten! (which implies the SourceLocation's are invalid).
2036Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2037 // Get the start location and compute the semi location.
2038 SourceLocation startLoc = S->getLocStart();
2039 const char *startBuf = SM->getCharacterData(startLoc);
2040
2041 assert((*startBuf == '@') && "bogus @throw location");
2042
2043 std::string buf;
2044 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2045 if (S->getThrowExpr())
2046 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002047 else
2048 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002049
2050 // handle "@ throw" correctly.
2051 const char *wBuf = strchr(startBuf, 'w');
2052 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2053 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2054
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002055 SourceLocation endLoc = S->getLocEnd();
2056 const char *endBuf = SM->getCharacterData(endLoc);
2057 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002058 assert((*semiBuf == ';') && "@throw: can't find ';'");
2059 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002060 if (S->getThrowExpr())
2061 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002062 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002063}
2064
2065Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2066 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002067 std::string StrEncoding;
2068 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002069 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002070 ReplaceStmt(Exp, Replacement);
2071
2072 // Replace this subexpr in the parent.
2073 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2074 return Replacement;
2075}
2076
2077Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2078 if (!SelGetUidFunctionDecl)
2079 SynthSelGetUidFunctionDecl();
2080 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2081 // Create a call to sel_registerName("selName").
2082 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002083 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002084 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002085 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002086 ReplaceStmt(Exp, SelExp);
2087 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2088 return SelExp;
2089}
2090
Craig Toppercf2126e2015-10-22 03:13:07 +00002091CallExpr *
2092RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2093 ArrayRef<Expr *> Args,
2094 SourceLocation StartLoc,
2095 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002096 // Get the type, we will need to reference it in a couple spots.
2097 QualType msgSendType = FD->getType();
2098
2099 // Create a reference to the objc_msgSend() declaration.
2100 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002101 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002102
2103 // Now, we cast the reference to a pointer to the objc_msgSend type.
2104 QualType pToFunc = Context->getPointerType(msgSendType);
2105 ImplicitCastExpr *ICE =
2106 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002107 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002108
2109 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2110
Craig Toppercf2126e2015-10-22 03:13:07 +00002111 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2112 FT->getCallResultType(*Context),
2113 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002114 return Exp;
2115}
2116
2117static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2118 const char *&startRef, const char *&endRef) {
2119 while (startBuf < endBuf) {
2120 if (*startBuf == '<')
2121 startRef = startBuf; // mark the start.
2122 if (*startBuf == '>') {
2123 if (startRef && *startRef == '<') {
2124 endRef = startBuf; // mark the end.
2125 return true;
2126 }
2127 return false;
2128 }
2129 startBuf++;
2130 }
2131 return false;
2132}
2133
2134static void scanToNextArgument(const char *&argRef) {
2135 int angle = 0;
2136 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2137 if (*argRef == '<')
2138 angle++;
2139 else if (*argRef == '>')
2140 angle--;
2141 argRef++;
2142 }
2143 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2144}
2145
2146bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2147 if (T->isObjCQualifiedIdType())
2148 return true;
2149 if (const PointerType *PT = T->getAs<PointerType>()) {
2150 if (PT->getPointeeType()->isObjCQualifiedIdType())
2151 return true;
2152 }
2153 if (T->isObjCObjectPointerType()) {
2154 T = T->getPointeeType();
2155 return T->isObjCQualifiedInterfaceType();
2156 }
2157 if (T->isArrayType()) {
2158 QualType ElemTy = Context->getBaseElementType(T);
2159 return needToScanForQualifiers(ElemTy);
2160 }
2161 return false;
2162}
2163
2164void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2165 QualType Type = E->getType();
2166 if (needToScanForQualifiers(Type)) {
2167 SourceLocation Loc, EndLoc;
2168
2169 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2170 Loc = ECE->getLParenLoc();
2171 EndLoc = ECE->getRParenLoc();
2172 } else {
2173 Loc = E->getLocStart();
2174 EndLoc = E->getLocEnd();
2175 }
2176 // This will defend against trying to rewrite synthesized expressions.
2177 if (Loc.isInvalid() || EndLoc.isInvalid())
2178 return;
2179
2180 const char *startBuf = SM->getCharacterData(Loc);
2181 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002182 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2186 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2187 // Comment out the protocol references.
2188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
2190 }
2191 }
2192}
2193
2194void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2195 SourceLocation Loc;
2196 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002197 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002198 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2199 Loc = VD->getLocation();
2200 Type = VD->getType();
2201 }
2202 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2203 Loc = FD->getLocation();
2204 // Check for ObjC 'id' and class types that have been adorned with protocol
2205 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2206 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2207 assert(funcType && "missing function type");
2208 proto = dyn_cast<FunctionProtoType>(funcType);
2209 if (!proto)
2210 return;
Alp Toker314cc812014-01-25 16:55:45 +00002211 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002212 }
2213 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2214 Loc = FD->getLocation();
2215 Type = FD->getType();
2216 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002217 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2218 Loc = TD->getLocation();
2219 Type = TD->getUnderlyingType();
2220 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002221 else
2222 return;
2223
2224 if (needToScanForQualifiers(Type)) {
2225 // Since types are unique, we need to scan the buffer.
2226
2227 const char *endBuf = SM->getCharacterData(Loc);
2228 const char *startBuf = endBuf;
2229 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2230 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002231 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002232 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233 // Get the locations of the startRef, endRef.
2234 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2235 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2236 // Comment out the protocol references.
2237 InsertText(LessLoc, "/*");
2238 InsertText(GreaterLoc, "*/");
2239 }
2240 }
2241 if (!proto)
2242 return; // most likely, was a variable
2243 // Now check arguments.
2244 const char *startBuf = SM->getCharacterData(Loc);
2245 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002246 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2247 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002248 // Since types are unique, we need to scan the buffer.
2249
2250 const char *endBuf = startBuf;
2251 // scan forward (from the decl location) for argument types.
2252 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002253 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255 // Get the locations of the startRef, endRef.
2256 SourceLocation LessLoc =
2257 Loc.getLocWithOffset(startRef-startFuncBuf);
2258 SourceLocation GreaterLoc =
2259 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2260 // Comment out the protocol references.
2261 InsertText(LessLoc, "/*");
2262 InsertText(GreaterLoc, "*/");
2263 }
2264 startBuf = ++endBuf;
2265 }
2266 else {
2267 // If the function name is derived from a macro expansion, then the
2268 // argument buffer will not follow the name. Need to speak with Chris.
2269 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2270 startBuf++; // scan forward (from the decl location) for argument types.
2271 startBuf++;
2272 }
2273 }
2274}
2275
2276void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2277 QualType QT = ND->getType();
2278 const Type* TypePtr = QT->getAs<Type>();
2279 if (!isa<TypeOfExprType>(TypePtr))
2280 return;
2281 while (isa<TypeOfExprType>(TypePtr)) {
2282 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2283 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2284 TypePtr = QT->getAs<Type>();
2285 }
2286 // FIXME. This will not work for multiple declarators; as in:
2287 // __typeof__(a) b,c,d;
2288 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2289 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2290 const char *startBuf = SM->getCharacterData(DeclLoc);
2291 if (ND->getInit()) {
2292 std::string Name(ND->getNameAsString());
2293 TypeAsString += " " + Name + " = ";
2294 Expr *E = ND->getInit();
2295 SourceLocation startLoc;
2296 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2297 startLoc = ECE->getLParenLoc();
2298 else
2299 startLoc = E->getLocStart();
2300 startLoc = SM->getExpansionLoc(startLoc);
2301 const char *endBuf = SM->getCharacterData(startLoc);
2302 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2303 }
2304 else {
2305 SourceLocation X = ND->getLocEnd();
2306 X = SM->getExpansionLoc(X);
2307 const char *endBuf = SM->getCharacterData(X);
2308 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2309 }
2310}
2311
2312// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2313void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2314 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2315 SmallVector<QualType, 16> ArgTys;
2316 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2317 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002318 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002319 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002320 SourceLocation(),
2321 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002322 SelGetUidIdent, getFuncType,
2323 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002324}
2325
2326void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2327 // declared in <objc/objc.h>
2328 if (FD->getIdentifier() &&
2329 FD->getName() == "sel_registerName") {
2330 SelGetUidFunctionDecl = FD;
2331 return;
2332 }
2333 RewriteObjCQualifiedInterfaceTypes(FD);
2334}
2335
2336void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2337 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2338 const char *argPtr = TypeString.c_str();
2339 if (!strchr(argPtr, '^')) {
2340 Str += TypeString;
2341 return;
2342 }
2343 while (*argPtr) {
2344 Str += (*argPtr == '^' ? '*' : *argPtr);
2345 argPtr++;
2346 }
2347}
2348
2349// FIXME. Consolidate this routine with RewriteBlockPointerType.
2350void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2351 ValueDecl *VD) {
2352 QualType Type = VD->getType();
2353 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2354 const char *argPtr = TypeString.c_str();
2355 int paren = 0;
2356 while (*argPtr) {
2357 switch (*argPtr) {
2358 case '(':
2359 Str += *argPtr;
2360 paren++;
2361 break;
2362 case ')':
2363 Str += *argPtr;
2364 paren--;
2365 break;
2366 case '^':
2367 Str += '*';
2368 if (paren == 1)
2369 Str += VD->getNameAsString();
2370 break;
2371 default:
2372 Str += *argPtr;
2373 break;
2374 }
2375 argPtr++;
2376 }
2377}
2378
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002379void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2380 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2381 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2382 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2383 if (!proto)
2384 return;
Alp Toker314cc812014-01-25 16:55:45 +00002385 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002386 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2387 FdStr += " ";
2388 FdStr += FD->getName();
2389 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002390 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002391 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002392 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002393 RewriteBlockPointerType(FdStr, ArgType);
2394 if (i+1 < numArgs)
2395 FdStr += ", ";
2396 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002397 if (FD->isVariadic()) {
2398 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2399 }
2400 else
2401 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002402 InsertText(FunLocStart, FdStr);
2403}
2404
Benjamin Kramer60509af2013-09-09 14:48:42 +00002405// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2406void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2407 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002408 return;
2409 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2410 SmallVector<QualType, 16> ArgTys;
2411 QualType argT = Context->getObjCIdType();
2412 assert(!argT.isNull() && "Can't find 'id' type");
2413 ArgTys.push_back(argT);
2414 ArgTys.push_back(argT);
2415 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002416 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002417 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002418 SourceLocation(),
2419 SourceLocation(),
2420 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002421 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002422}
2423
2424// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2425void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2427 SmallVector<QualType, 16> ArgTys;
2428 QualType argT = Context->getObjCIdType();
2429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
2431 argT = Context->getObjCSelType();
2432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
2434 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002435 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002436 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002437 SourceLocation(),
2438 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002439 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002440 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002441}
2442
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002443// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002444void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2445 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002446 SmallVector<QualType, 2> ArgTys;
2447 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002449 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002450 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002451 SourceLocation(),
2452 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002453 msgSendIdent, msgSendType,
2454 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002455}
2456
2457// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002469 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002472 msgSendIdent, msgSendType,
2473 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002474}
2475
2476// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002477// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002478void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2479 IdentifierInfo *msgSendIdent =
2480 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002481 SmallVector<QualType, 2> ArgTys;
2482 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002484 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002485 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2486 SourceLocation(),
2487 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002488 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002489 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002490 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002491}
2492
2493// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2494void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2496 SmallVector<QualType, 16> ArgTys;
2497 QualType argT = Context->getObjCIdType();
2498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
2500 argT = Context->getObjCSelType();
2501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
2503 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002504 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002506 SourceLocation(),
2507 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002508 msgSendIdent, msgSendType,
2509 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002510}
2511
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002512// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513void RewriteModernObjC::SynthGetClassFunctionDecl() {
2514 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2515 SmallVector<QualType, 16> ArgTys;
2516 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002517 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002518 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002519 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002520 SourceLocation(),
2521 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002522 getClassIdent, getClassType,
2523 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002524}
2525
2526// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2527void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2528 IdentifierInfo *getSuperClassIdent =
2529 &Context->Idents.get("class_getSuperclass");
2530 SmallVector<QualType, 16> ArgTys;
2531 ArgTys.push_back(Context->getObjCClassType());
2532 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002533 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002534 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2535 SourceLocation(),
2536 SourceLocation(),
2537 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002538 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002539 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002540}
2541
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002542// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002543void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2544 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2545 SmallVector<QualType, 16> ArgTys;
2546 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002547 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002548 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002549 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002550 SourceLocation(),
2551 SourceLocation(),
2552 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002553 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554}
2555
2556Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002557 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002558 QualType strType = getConstantStringStructType();
2559
2560 std::string S = "__NSConstantStringImpl_";
2561
2562 std::string tmpName = InFileName;
2563 unsigned i;
2564 for (i=0; i < tmpName.length(); i++) {
2565 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002566 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002567 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002568 tmpName[i] = '_';
2569 }
2570 S += tmpName;
2571 S += "_";
2572 S += utostr(NumObjCStringLiterals++);
2573
2574 Preamble += "static __NSConstantStringImpl " + S;
2575 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2576 Preamble += "0x000007c8,"; // utf8_str
2577 // The pretty printer for StringLiteral handles escape characters properly.
2578 std::string prettyBufS;
2579 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002580 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002581 Preamble += prettyBuf.str();
2582 Preamble += ",";
2583 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2584
2585 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2586 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002587 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002588 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002589 SourceLocation());
2590 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2591 Context->getPointerType(DRE->getType()),
2592 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002593 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002594 // cast to NSConstantString *
2595 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2596 CK_CPointerToObjCPointerCast, Unop);
2597 ReplaceStmt(Exp, cast);
2598 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2599 return cast;
2600}
2601
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002602Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2603 unsigned IntSize =
2604 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2605
2606 Expr *FlagExp = IntegerLiteral::Create(*Context,
2607 llvm::APInt(IntSize, Exp->getValue()),
2608 Context->IntTy, Exp->getLocation());
2609 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2610 CK_BitCast, FlagExp);
2611 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2612 cast);
2613 ReplaceStmt(Exp, PE);
2614 return PE;
2615}
2616
Patrick Beard0caa3942012-04-19 00:25:12 +00002617Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002618 // synthesize declaration of helper functions needed in this routine.
2619 if (!SelGetUidFunctionDecl)
2620 SynthSelGetUidFunctionDecl();
2621 // use objc_msgSend() for all.
2622 if (!MsgSendFunctionDecl)
2623 SynthMsgSendFunctionDecl();
2624 if (!GetClassFunctionDecl)
2625 SynthGetClassFunctionDecl();
2626
2627 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2628 SourceLocation StartLoc = Exp->getLocStart();
2629 SourceLocation EndLoc = Exp->getLocEnd();
2630
2631 // Synthesize a call to objc_msgSend().
2632 SmallVector<Expr*, 4> MsgExprs;
2633 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002634
Patrick Beard0caa3942012-04-19 00:25:12 +00002635 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2636 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2637 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002638
Patrick Beard0caa3942012-04-19 00:25:12 +00002639 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002640 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002641 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002642 StartLoc, EndLoc);
2643 MsgExprs.push_back(Cls);
2644
Patrick Beard0caa3942012-04-19 00:25:12 +00002645 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002646 // it will be the 2nd argument.
2647 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002648 SelExprs.push_back(
2649 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002650 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002651 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002652 MsgExprs.push_back(SelExp);
2653
Patrick Beard0caa3942012-04-19 00:25:12 +00002654 // User provided sub-expression is the 3rd, and last, argument.
2655 Expr *subExpr = Exp->getSubExpr();
2656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002657 QualType type = ICE->getType();
2658 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2659 CastKind CK = CK_BitCast;
2660 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2661 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002662 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002663 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002664 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002665
2666 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002667 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002668 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002669 for (const auto PI : BoxingMethod->parameters())
2670 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002671
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002672 QualType returnType = Exp->getType();
2673 // Get the type, we will need to reference it in a couple spots.
2674 QualType msgSendType = MsgSendFlavor->getType();
2675
2676 // Create a reference to the objc_msgSend() declaration.
2677 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2678 VK_LValue, SourceLocation());
2679
2680 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002681 Context->getPointerType(Context->VoidTy),
2682 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002683
2684 // Now do the "normal" pointer to function cast.
2685 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002686 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002687 castType = Context->getPointerType(castType);
2688 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2689 cast);
2690
2691 // Don't forget the parens to enforce the proper binding.
2692 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2693
2694 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002695 CallExpr *CE = new (Context)
2696 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002697 ReplaceStmt(Exp, CE);
2698 return CE;
2699}
2700
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002701Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2702 // synthesize declaration of helper functions needed in this routine.
2703 if (!SelGetUidFunctionDecl)
2704 SynthSelGetUidFunctionDecl();
2705 // use objc_msgSend() for all.
2706 if (!MsgSendFunctionDecl)
2707 SynthMsgSendFunctionDecl();
2708 if (!GetClassFunctionDecl)
2709 SynthGetClassFunctionDecl();
2710
2711 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2712 SourceLocation StartLoc = Exp->getLocStart();
2713 SourceLocation EndLoc = Exp->getLocEnd();
2714
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002715 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002716 QualType IntQT = Context->IntTy;
2717 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002718 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002719 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002720 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2721 DeclRefExpr *NSArrayDRE =
2722 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2723 SourceLocation());
2724
2725 SmallVector<Expr*, 16> InitExprs;
2726 unsigned NumElements = Exp->getNumElements();
2727 unsigned UnsignedIntSize =
2728 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2729 Expr *count = IntegerLiteral::Create(*Context,
2730 llvm::APInt(UnsignedIntSize, NumElements),
2731 Context->UnsignedIntTy, SourceLocation());
2732 InitExprs.push_back(count);
2733 for (unsigned i = 0; i < NumElements; i++)
2734 InitExprs.push_back(Exp->getElement(i));
2735 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002736 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002737 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002738
2739 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002740 SourceLocation(),
2741 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002742 Context->getPointerType(Context->VoidPtrTy),
2743 nullptr, /*BitWidth=*/nullptr,
2744 /*Mutable=*/true, ICIS_NoInit);
2745 MemberExpr *ArrayLiteralME = new (Context)
2746 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2747 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2748 QualType ConstIdT = Context->getObjCIdType().withConst();
2749 CStyleCastExpr * ArrayLiteralObjects =
2750 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002751 Context->getPointerType(ConstIdT),
2752 CK_BitCast,
2753 ArrayLiteralME);
2754
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002755 // Synthesize a call to objc_msgSend().
2756 SmallVector<Expr*, 32> MsgExprs;
2757 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002758 QualType expType = Exp->getType();
2759
2760 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2761 ObjCInterfaceDecl *Class =
2762 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2763
2764 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002765 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002766 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002767 StartLoc, EndLoc);
2768 MsgExprs.push_back(Cls);
2769
2770 // Create a call to sel_registerName("arrayWithObjects:count:").
2771 // it will be the 2nd argument.
2772 SmallVector<Expr*, 4> SelExprs;
2773 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002774 SelExprs.push_back(
2775 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002776 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002777 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002778 MsgExprs.push_back(SelExp);
2779
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002780 // (const id [])objects
2781 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002782
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002783 // (NSUInteger)cnt
2784 Expr *cnt = IntegerLiteral::Create(*Context,
2785 llvm::APInt(UnsignedIntSize, NumElements),
2786 Context->UnsignedIntTy, SourceLocation());
2787 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002788
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002789 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002790 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002791 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002792 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002793 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002794
2795 QualType returnType = Exp->getType();
2796 // Get the type, we will need to reference it in a couple spots.
2797 QualType msgSendType = MsgSendFlavor->getType();
2798
2799 // Create a reference to the objc_msgSend() declaration.
2800 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2801 VK_LValue, SourceLocation());
2802
2803 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2804 Context->getPointerType(Context->VoidTy),
2805 CK_BitCast, DRE);
2806
2807 // Now do the "normal" pointer to function cast.
2808 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002809 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002810 castType = Context->getPointerType(castType);
2811 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2812 cast);
2813
2814 // Don't forget the parens to enforce the proper binding.
2815 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2816
2817 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002818 CallExpr *CE = new (Context)
2819 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002820 ReplaceStmt(Exp, CE);
2821 return CE;
2822}
2823
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002824Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2825 // synthesize declaration of helper functions needed in this routine.
2826 if (!SelGetUidFunctionDecl)
2827 SynthSelGetUidFunctionDecl();
2828 // use objc_msgSend() for all.
2829 if (!MsgSendFunctionDecl)
2830 SynthMsgSendFunctionDecl();
2831 if (!GetClassFunctionDecl)
2832 SynthGetClassFunctionDecl();
2833
2834 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2835 SourceLocation StartLoc = Exp->getLocStart();
2836 SourceLocation EndLoc = Exp->getLocEnd();
2837
2838 // Build the expression: __NSContainer_literal(int, ...).arr
2839 QualType IntQT = Context->IntTy;
2840 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002841 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002842 std::string NSDictFName("__NSContainer_literal");
2843 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2844 DeclRefExpr *NSDictDRE =
2845 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2846 SourceLocation());
2847
2848 SmallVector<Expr*, 16> KeyExprs;
2849 SmallVector<Expr*, 16> ValueExprs;
2850
2851 unsigned NumElements = Exp->getNumElements();
2852 unsigned UnsignedIntSize =
2853 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2854 Expr *count = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 KeyExprs.push_back(count);
2858 ValueExprs.push_back(count);
2859 for (unsigned i = 0; i < NumElements; i++) {
2860 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2861 KeyExprs.push_back(Element.Key);
2862 ValueExprs.push_back(Element.Value);
2863 }
2864
2865 // (const id [])objects
2866 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002867 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002868 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002869
2870 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002871 SourceLocation(),
2872 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002873 Context->getPointerType(Context->VoidPtrTy),
2874 nullptr, /*BitWidth=*/nullptr,
2875 /*Mutable=*/true, ICIS_NoInit);
2876 MemberExpr *DictLiteralValueME = new (Context)
2877 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2878 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2879 QualType ConstIdT = Context->getObjCIdType().withConst();
2880 CStyleCastExpr * DictValueObjects =
2881 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002882 Context->getPointerType(ConstIdT),
2883 CK_BitCast,
2884 DictLiteralValueME);
2885 // (const id <NSCopying> [])keys
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002886 Expr *NSKeyCallExpr =
2887 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2888 NSDictFType, VK_LValue, SourceLocation());
2889
2890 MemberExpr *DictLiteralKeyME = new (Context)
2891 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2892 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2893
2894 CStyleCastExpr * DictKeyObjects =
2895 NoTypeInfoCStyleCastExpr(Context,
2896 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002897 CK_BitCast,
2898 DictLiteralKeyME);
2899
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002900 // Synthesize a call to objc_msgSend().
2901 SmallVector<Expr*, 32> MsgExprs;
2902 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002903 QualType expType = Exp->getType();
2904
2905 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2906 ObjCInterfaceDecl *Class =
2907 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2908
2909 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002910 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002911 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002912 StartLoc, EndLoc);
2913 MsgExprs.push_back(Cls);
2914
2915 // Create a call to sel_registerName("arrayWithObjects:count:").
2916 // it will be the 2nd argument.
2917 SmallVector<Expr*, 4> SelExprs;
2918 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002919 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002920 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002921 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002922 MsgExprs.push_back(SelExp);
2923
2924 // (const id [])objects
2925 MsgExprs.push_back(DictValueObjects);
2926
2927 // (const id <NSCopying> [])keys
2928 MsgExprs.push_back(DictKeyObjects);
2929
2930 // (NSUInteger)cnt
2931 Expr *cnt = IntegerLiteral::Create(*Context,
2932 llvm::APInt(UnsignedIntSize, NumElements),
2933 Context->UnsignedIntTy, SourceLocation());
2934 MsgExprs.push_back(cnt);
2935
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002936 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002937 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002938 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002939 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002940 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002941 if (const PointerType* PT = T->getAs<PointerType>()) {
2942 QualType PointeeTy = PT->getPointeeType();
2943 convertToUnqualifiedObjCType(PointeeTy);
2944 T = Context->getPointerType(PointeeTy);
2945 }
2946 ArgTypes.push_back(T);
2947 }
2948
2949 QualType returnType = Exp->getType();
2950 // Get the type, we will need to reference it in a couple spots.
2951 QualType msgSendType = MsgSendFlavor->getType();
2952
2953 // Create a reference to the objc_msgSend() declaration.
2954 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2955 VK_LValue, SourceLocation());
2956
2957 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2958 Context->getPointerType(Context->VoidTy),
2959 CK_BitCast, DRE);
2960
2961 // Now do the "normal" pointer to function cast.
2962 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002963 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 castType = Context->getPointerType(castType);
2965 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2966 cast);
2967
2968 // Don't forget the parens to enforce the proper binding.
2969 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2970
2971 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002972 CallExpr *CE = new (Context)
2973 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002974 ReplaceStmt(Exp, CE);
2975 return CE;
2976}
2977
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002978// struct __rw_objc_super {
2979// struct objc_object *object; struct objc_object *superClass;
2980// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002981QualType RewriteModernObjC::getSuperStructType() {
2982 if (!SuperStructDecl) {
2983 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2984 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002985 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002986 QualType FieldTypes[2];
2987
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002988 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002989 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002990 // struct objc_object *superClass;
2991 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002992
2993 // Create fields
2994 for (unsigned i = 0; i < 2; ++i) {
2995 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2996 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002997 SourceLocation(), nullptr,
2998 FieldTypes[i], nullptr,
2999 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003000 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003001 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003002 }
3003
3004 SuperStructDecl->completeDefinition();
3005 }
3006 return Context->getTagDeclType(SuperStructDecl);
3007}
3008
3009QualType RewriteModernObjC::getConstantStringStructType() {
3010 if (!ConstantStringDecl) {
3011 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3012 SourceLocation(), SourceLocation(),
3013 &Context->Idents.get("__NSConstantStringImpl"));
3014 QualType FieldTypes[4];
3015
3016 // struct objc_object *receiver;
3017 FieldTypes[0] = Context->getObjCIdType();
3018 // int flags;
3019 FieldTypes[1] = Context->IntTy;
3020 // char *str;
3021 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3022 // long length;
3023 FieldTypes[3] = Context->LongTy;
3024
3025 // Create fields
3026 for (unsigned i = 0; i < 4; ++i) {
3027 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3028 ConstantStringDecl,
3029 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003030 SourceLocation(), nullptr,
3031 FieldTypes[i], nullptr,
3032 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003033 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003034 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003035 }
3036
3037 ConstantStringDecl->completeDefinition();
3038 }
3039 return Context->getTagDeclType(ConstantStringDecl);
3040}
3041
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003042/// getFunctionSourceLocation - returns start location of a function
3043/// definition. Complication arises when function has declared as
3044/// extern "C" or extern "C" {...}
3045static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3046 FunctionDecl *FD) {
3047 if (FD->isExternC() && !FD->isMain()) {
3048 const DeclContext *DC = FD->getDeclContext();
3049 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3050 // if it is extern "C" {...}, return function decl's own location.
3051 if (!LSD->getRBraceLoc().isValid())
3052 return LSD->getExternLoc();
3053 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003054 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003055 R.RewriteBlockLiteralFunctionDecl(FD);
3056 return FD->getTypeSpecStartLoc();
3057}
3058
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003059void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3060
3061 SourceLocation Location = D->getLocation();
3062
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003063 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003064 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003065 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3066 LineString += utostr(PLoc.getLine());
3067 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003068 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003069 if (isa<ObjCMethodDecl>(D))
3070 LineString += "\"";
3071 else LineString += "\"\n";
3072
3073 Location = D->getLocStart();
3074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3075 if (FD->isExternC() && !FD->isMain()) {
3076 const DeclContext *DC = FD->getDeclContext();
3077 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3078 // if it is extern "C" {...}, return function decl's own location.
3079 if (!LSD->getRBraceLoc().isValid())
3080 Location = LSD->getExternLoc();
3081 }
3082 }
3083 InsertText(Location, LineString);
3084 }
3085}
3086
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003087/// SynthMsgSendStretCallExpr - This routine translates message expression
3088/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3089/// nil check on receiver must be performed before calling objc_msgSend_stret.
3090/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3091/// msgSendType - function type of objc_msgSend_stret(...)
3092/// returnType - Result type of the method being synthesized.
3093/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3094/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3095/// starting with receiver.
3096/// Method - Method being rewritten.
3097Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003098 QualType returnType,
3099 SmallVectorImpl<QualType> &ArgTypes,
3100 SmallVectorImpl<Expr*> &MsgExprs,
3101 ObjCMethodDecl *Method) {
3102 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003103 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3104 Method ? Method->isVariadic()
3105 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003106 castType = Context->getPointerType(castType);
3107
3108 // build type for containing the objc_msgSend_stret object.
3109 static unsigned stretCount=0;
3110 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003111 std::string str =
3112 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003113 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003114 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003115 str += " {\n\t";
3116 str += name;
3117 str += "(id receiver, SEL sel";
3118 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003119 std::string ArgName = "arg"; ArgName += utostr(i);
3120 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3121 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003122 }
3123 // could be vararg.
3124 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003125 std::string ArgName = "arg"; ArgName += utostr(i);
3126 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3127 Context->getPrintingPolicy());
3128 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003129 }
3130
3131 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003132 str += "\t unsigned size = sizeof(";
3133 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3134
3135 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3136
3137 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3138 str += ")(void *)objc_msgSend)(receiver, sel";
3139 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3140 str += ", arg"; str += utostr(i);
3141 }
3142 // could be vararg.
3143 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3144 str += ", arg"; str += utostr(i);
3145 }
3146 str+= ");\n";
3147
3148 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003149 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3150 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003151
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003152 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3153 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3154 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3155 str += ", arg"; str += utostr(i);
3156 }
3157 // could be vararg.
3158 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3159 str += ", arg"; str += utostr(i);
3160 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003161 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003162
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003163 str += "\t}\n";
3164 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3165 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003166 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003167 SourceLocation FunLocStart;
3168 if (CurFunctionDef)
3169 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3170 else {
3171 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3172 FunLocStart = CurMethodDef->getLocStart();
3173 }
3174
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003175 InsertText(FunLocStart, str);
3176 ++stretCount;
3177
3178 // AST for __Stretn(receiver, args).s;
3179 IdentifierInfo *ID = &Context->Idents.get(name);
3180 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003181 SourceLocation(), ID, castType,
3182 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003183 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3184 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003185 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003186 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003187
3188 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003189 SourceLocation(),
3190 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003191 returnType, nullptr,
3192 /*BitWidth=*/nullptr,
3193 /*Mutable=*/true, ICIS_NoInit);
3194 MemberExpr *ME = new (Context)
3195 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3196 FieldD->getType(), VK_LValue, OK_Ordinary);
3197
3198 return ME;
3199}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003200
Fariborz Jahanian11671902012-02-07 17:11:38 +00003201Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3202 SourceLocation StartLoc,
3203 SourceLocation EndLoc) {
3204 if (!SelGetUidFunctionDecl)
3205 SynthSelGetUidFunctionDecl();
3206 if (!MsgSendFunctionDecl)
3207 SynthMsgSendFunctionDecl();
3208 if (!MsgSendSuperFunctionDecl)
3209 SynthMsgSendSuperFunctionDecl();
3210 if (!MsgSendStretFunctionDecl)
3211 SynthMsgSendStretFunctionDecl();
3212 if (!MsgSendSuperStretFunctionDecl)
3213 SynthMsgSendSuperStretFunctionDecl();
3214 if (!MsgSendFpretFunctionDecl)
3215 SynthMsgSendFpretFunctionDecl();
3216 if (!GetClassFunctionDecl)
3217 SynthGetClassFunctionDecl();
3218 if (!GetSuperClassFunctionDecl)
3219 SynthGetSuperClassFunctionDecl();
3220 if (!GetMetaClassFunctionDecl)
3221 SynthGetMetaClassFunctionDecl();
3222
3223 // default to objc_msgSend().
3224 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3225 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003226 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003227 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003228 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003229 if (resultType->isRecordType())
3230 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3231 else if (resultType->isRealFloatingType())
3232 MsgSendFlavor = MsgSendFpretFunctionDecl;
3233 }
3234
3235 // Synthesize a call to objc_msgSend().
3236 SmallVector<Expr*, 8> MsgExprs;
3237 switch (Exp->getReceiverKind()) {
3238 case ObjCMessageExpr::SuperClass: {
3239 MsgSendFlavor = MsgSendSuperFunctionDecl;
3240 if (MsgSendStretFlavor)
3241 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3242 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3243
3244 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3245
3246 SmallVector<Expr*, 4> InitExprs;
3247
3248 // set the receiver to self, the first argument to all methods.
3249 InitExprs.push_back(
3250 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3251 CK_BitCast,
3252 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003253 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003254 Context->getObjCIdType(),
3255 VK_RValue,
3256 SourceLocation()))
3257 ); // set the 'receiver'.
3258
3259 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3260 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003261 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003262 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003263 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003264 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003265 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003266 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003267 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003268 StartLoc, EndLoc);
3269
3270 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3271 // To turn off a warning, type-cast to 'id'
3272 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3273 NoTypeInfoCStyleCastExpr(Context,
3274 Context->getObjCIdType(),
3275 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003276 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003277 QualType superType = getSuperStructType();
3278 Expr *SuperRep;
3279
3280 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003281 SynthSuperConstructorFunctionDecl();
3282 // Simulate a constructor call...
3283 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003284 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003285 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003286 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003287 superType, VK_LValue,
3288 SourceLocation());
3289 // The code for super is a little tricky to prevent collision with
3290 // the structure definition in the header. The rewriter has it's own
3291 // internal definition (__rw_objc_super) that is uses. This is why
3292 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003293 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003294 //
3295 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3296 Context->getPointerType(SuperRep->getType()),
3297 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003298 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003299 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3300 Context->getPointerType(superType),
3301 CK_BitCast, SuperRep);
3302 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003303 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003304 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003305 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003306 SourceLocation());
3307 TypeSourceInfo *superTInfo
3308 = Context->getTrivialTypeSourceInfo(superType);
3309 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3310 superType, VK_LValue,
3311 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003312 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003313 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3314 Context->getPointerType(SuperRep->getType()),
3315 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003316 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003317 }
3318 MsgExprs.push_back(SuperRep);
3319 break;
3320 }
3321
3322 case ObjCMessageExpr::Class: {
3323 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003324 ObjCInterfaceDecl *Class
3325 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3326 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003327 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003328 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003329 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003330 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3331 Context->getObjCIdType(),
3332 CK_BitCast, Cls);
3333 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003334 break;
3335 }
3336
3337 case ObjCMessageExpr::SuperInstance:{
3338 MsgSendFlavor = MsgSendSuperFunctionDecl;
3339 if (MsgSendStretFlavor)
3340 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3341 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3342 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3343 SmallVector<Expr*, 4> InitExprs;
3344
3345 InitExprs.push_back(
3346 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3347 CK_BitCast,
3348 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003349 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003350 Context->getObjCIdType(),
3351 VK_RValue, SourceLocation()))
3352 ); // set the 'receiver'.
3353
3354 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3355 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003356 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003357 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003358 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003359 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003360 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003361 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003362 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003363 StartLoc, EndLoc);
3364
3365 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3366 // To turn off a warning, type-cast to 'id'
3367 InitExprs.push_back(
3368 // set 'super class', using class_getSuperclass().
3369 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3370 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003371 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003372 QualType superType = getSuperStructType();
3373 Expr *SuperRep;
3374
3375 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003376 SynthSuperConstructorFunctionDecl();
3377 // Simulate a constructor call...
3378 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003379 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003381 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003382 superType, VK_LValue, SourceLocation());
3383 // The code for super is a little tricky to prevent collision with
3384 // the structure definition in the header. The rewriter has it's own
3385 // internal definition (__rw_objc_super) that is uses. This is why
3386 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003387 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003388 //
3389 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3390 Context->getPointerType(SuperRep->getType()),
3391 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003392 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3394 Context->getPointerType(superType),
3395 CK_BitCast, SuperRep);
3396 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003397 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003398 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003399 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003400 SourceLocation());
3401 TypeSourceInfo *superTInfo
3402 = Context->getTrivialTypeSourceInfo(superType);
3403 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3404 superType, VK_RValue, ILE,
3405 false);
3406 }
3407 MsgExprs.push_back(SuperRep);
3408 break;
3409 }
3410
3411 case ObjCMessageExpr::Instance: {
3412 // Remove all type-casts because it may contain objc-style types; e.g.
3413 // Foo<Proto> *.
3414 Expr *recExpr = Exp->getInstanceReceiver();
3415 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3416 recExpr = CE->getSubExpr();
3417 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3418 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3419 ? CK_BlockPointerToObjCPointerCast
3420 : CK_CPointerToObjCPointerCast;
3421
3422 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3423 CK, recExpr);
3424 MsgExprs.push_back(recExpr);
3425 break;
3426 }
3427 }
3428
3429 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3430 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003431 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003432 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003433 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003434 MsgExprs.push_back(SelExp);
3435
3436 // Now push any user supplied arguments.
3437 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3438 Expr *userExpr = Exp->getArg(i);
3439 // Make all implicit casts explicit...ICE comes in handy:-)
3440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3441 // Reuse the ICE type, it is exactly what the doctor ordered.
3442 QualType type = ICE->getType();
3443 if (needToScanForQualifiers(type))
3444 type = Context->getObjCIdType();
3445 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3446 (void)convertBlockPointerToFunctionPointer(type);
3447 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3448 CastKind CK;
3449 if (SubExpr->getType()->isIntegralType(*Context) &&
3450 type->isBooleanType()) {
3451 CK = CK_IntegralToBoolean;
3452 } else if (type->isObjCObjectPointerType()) {
3453 if (SubExpr->getType()->isBlockPointerType()) {
3454 CK = CK_BlockPointerToObjCPointerCast;
3455 } else if (SubExpr->getType()->isPointerType()) {
3456 CK = CK_CPointerToObjCPointerCast;
3457 } else {
3458 CK = CK_BitCast;
3459 }
3460 } else {
3461 CK = CK_BitCast;
3462 }
3463
3464 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3465 }
3466 // Make id<P...> cast into an 'id' cast.
3467 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3468 if (CE->getType()->isObjCQualifiedIdType()) {
3469 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3470 userExpr = CE->getSubExpr();
3471 CastKind CK;
3472 if (userExpr->getType()->isIntegralType(*Context)) {
3473 CK = CK_IntegralToPointer;
3474 } else if (userExpr->getType()->isBlockPointerType()) {
3475 CK = CK_BlockPointerToObjCPointerCast;
3476 } else if (userExpr->getType()->isPointerType()) {
3477 CK = CK_CPointerToObjCPointerCast;
3478 } else {
3479 CK = CK_BitCast;
3480 }
3481 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3482 CK, userExpr);
3483 }
3484 }
3485 MsgExprs.push_back(userExpr);
3486 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3487 // out the argument in the original expression (since we aren't deleting
3488 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3489 //Exp->setArg(i, 0);
3490 }
3491 // Generate the funky cast.
3492 CastExpr *cast;
3493 SmallVector<QualType, 8> ArgTypes;
3494 QualType returnType;
3495
3496 // Push 'id' and 'SEL', the 2 implicit arguments.
3497 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3498 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3499 else
3500 ArgTypes.push_back(Context->getObjCIdType());
3501 ArgTypes.push_back(Context->getObjCSelType());
3502 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3503 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003504 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003505 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003506 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003507 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003508 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3509 (void)convertBlockPointerToFunctionPointer(t);
3510 ArgTypes.push_back(t);
3511 }
3512 returnType = Exp->getType();
3513 convertToUnqualifiedObjCType(returnType);
3514 (void)convertBlockPointerToFunctionPointer(returnType);
3515 } else {
3516 returnType = Context->getObjCIdType();
3517 }
3518 // Get the type, we will need to reference it in a couple spots.
3519 QualType msgSendType = MsgSendFlavor->getType();
3520
3521 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003522 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003523 VK_LValue, SourceLocation());
3524
3525 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3526 // If we don't do this cast, we get the following bizarre warning/note:
3527 // xx.m:13: warning: function called through a non-compatible type
3528 // xx.m:13: note: if this code is reached, the program will abort
3529 cast = NoTypeInfoCStyleCastExpr(Context,
3530 Context->getPointerType(Context->VoidTy),
3531 CK_BitCast, DRE);
3532
3533 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003534 // If we don't have a method decl, force a variadic cast.
3535 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003536 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003537 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003538 castType = Context->getPointerType(castType);
3539 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3540 cast);
3541
3542 // Don't forget the parens to enforce the proper binding.
3543 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3544
3545 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003546 CallExpr *CE = new (Context)
3547 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003548 Stmt *ReplacingStmt = CE;
3549 if (MsgSendStretFlavor) {
3550 // We have the method which returns a struct/union. Must also generate
3551 // call to objc_msgSend_stret and hang both varieties on a conditional
3552 // expression which dictate which one to envoke depending on size of
3553 // method's return type.
3554
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003555 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3556 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003557 ArgTypes, MsgExprs,
3558 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003559 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003560 }
3561 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3562 return ReplacingStmt;
3563}
3564
3565Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3566 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3567 Exp->getLocEnd());
3568
3569 // Now do the actual rewrite.
3570 ReplaceStmt(Exp, ReplacingStmt);
3571
3572 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3573 return ReplacingStmt;
3574}
3575
3576// typedef struct objc_object Protocol;
3577QualType RewriteModernObjC::getProtocolType() {
3578 if (!ProtocolTypeDecl) {
3579 TypeSourceInfo *TInfo
3580 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3581 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3582 SourceLocation(), SourceLocation(),
3583 &Context->Idents.get("Protocol"),
3584 TInfo);
3585 }
3586 return Context->getTypeDeclType(ProtocolTypeDecl);
3587}
3588
3589/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3590/// a synthesized/forward data reference (to the protocol's metadata).
3591/// The forward references (and metadata) are generated in
3592/// RewriteModernObjC::HandleTranslationUnit().
3593Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003594 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3595 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003596 IdentifierInfo *ID = &Context->Idents.get(Name);
3597 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003598 SourceLocation(), ID, getProtocolType(),
3599 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003600 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3601 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003602 CastExpr *castExpr =
3603 NoTypeInfoCStyleCastExpr(
3604 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003605 ReplaceStmt(Exp, castExpr);
3606 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3607 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3608 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003609}
3610
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003611/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3612/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003613bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003614 TagDecl *Tag,
3615 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003616 if (!IDecl)
3617 return false;
3618 SourceLocation TagLocation;
3619 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3620 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003621 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003622 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003623 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003624 TagLocation = RD->getLocation();
3625 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003626 IDecl->getLocation(), TagLocation);
3627 }
3628 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3629 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3630 return false;
3631 IsNamedDefinition = true;
3632 TagLocation = ED->getLocation();
3633 return Context->getSourceManager().isBeforeInTranslationUnit(
3634 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003635 }
3636 return false;
3637}
3638
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003639/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003640/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003641bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3642 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003643 if (isa<TypedefType>(Type)) {
3644 Result += "\t";
3645 return false;
3646 }
3647
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003648 if (Type->isArrayType()) {
3649 QualType ElemTy = Context->getBaseElementType(Type);
3650 return RewriteObjCFieldDeclType(ElemTy, Result);
3651 }
3652 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003653 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3654 if (RD->isCompleteDefinition()) {
3655 if (RD->isStruct())
3656 Result += "\n\tstruct ";
3657 else if (RD->isUnion())
3658 Result += "\n\tunion ";
3659 else
3660 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003661
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003662 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003663 if (GlobalDefinedTags.count(RD)) {
3664 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003665 Result += " ";
3666 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003667 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003668 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003669 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003670 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003671 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003672 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003673 }
3674 }
3675 else if (Type->isEnumeralType()) {
3676 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3677 if (ED->isCompleteDefinition()) {
3678 Result += "\n\tenum ";
3679 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003680 if (GlobalDefinedTags.count(ED)) {
3681 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003682 Result += " ";
3683 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003684 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003685
3686 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003687 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003688 Result += "\t"; Result += EC->getName(); Result += " = ";
3689 llvm::APSInt Val = EC->getInitVal();
3690 Result += Val.toString(10);
3691 Result += ",\n";
3692 }
3693 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003694 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003695 }
3696 }
3697
3698 Result += "\t";
3699 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003700 return false;
3701}
3702
3703
3704/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3705/// It handles elaborated types, as well as enum types in the process.
3706void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3707 std::string &Result) {
3708 QualType Type = fieldDecl->getType();
3709 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003710
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003711 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3712 if (!EleboratedType)
3713 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003714 Result += Name;
3715 if (fieldDecl->isBitField()) {
3716 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3717 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003718 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003719 const ArrayType *AT = Context->getAsArrayType(Type);
3720 do {
3721 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003722 Result += "[";
3723 llvm::APInt Dim = CAT->getSize();
3724 Result += utostr(Dim.getZExtValue());
3725 Result += "]";
3726 }
Eli Friedman07bab732012-12-13 01:43:21 +00003727 AT = Context->getAsArrayType(AT->getElementType());
3728 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003729 }
3730
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003731 Result += ";\n";
3732}
3733
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003734/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3735/// named aggregate types into the input buffer.
3736void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3737 std::string &Result) {
3738 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003739 if (isa<TypedefType>(Type))
3740 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003741 if (Type->isArrayType())
3742 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003743 ObjCContainerDecl *IDecl =
3744 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003745
3746 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003747 if (Type->isRecordType()) {
3748 TD = Type->getAs<RecordType>()->getDecl();
3749 }
3750 else if (Type->isEnumeralType()) {
3751 TD = Type->getAs<EnumType>()->getDecl();
3752 }
3753
3754 if (TD) {
3755 if (GlobalDefinedTags.count(TD))
3756 return;
3757
3758 bool IsNamedDefinition = false;
3759 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3760 RewriteObjCFieldDeclType(Type, Result);
3761 Result += ";";
3762 }
3763 if (IsNamedDefinition)
3764 GlobalDefinedTags.insert(TD);
3765 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003766}
3767
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003768unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3769 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3770 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3771 return IvarGroupNumber[IV];
3772 }
3773 unsigned GroupNo = 0;
3774 SmallVector<const ObjCIvarDecl *, 8> IVars;
3775 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3776 IVD; IVD = IVD->getNextIvar())
3777 IVars.push_back(IVD);
3778
3779 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3780 if (IVars[i]->isBitField()) {
3781 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3782 while (i < e && IVars[i]->isBitField())
3783 IvarGroupNumber[IVars[i++]] = GroupNo;
3784 if (i < e)
3785 --i;
3786 }
3787
3788 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3789 return IvarGroupNumber[IV];
3790}
3791
3792QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3793 ObjCIvarDecl *IV,
3794 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3795 std::string StructTagName;
3796 ObjCIvarBitfieldGroupType(IV, StructTagName);
3797 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3798 Context->getTranslationUnitDecl(),
3799 SourceLocation(), SourceLocation(),
3800 &Context->Idents.get(StructTagName));
3801 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3802 ObjCIvarDecl *Ivar = IVars[i];
3803 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3804 &Context->Idents.get(Ivar->getName()),
3805 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003806 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3807 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003808 }
3809 RD->completeDefinition();
3810 return Context->getTagDeclType(RD);
3811}
3812
3813QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3814 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3815 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3816 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3817 if (GroupRecordType.count(tuple))
3818 return GroupRecordType[tuple];
3819
3820 SmallVector<ObjCIvarDecl *, 8> IVars;
3821 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3822 IVD; IVD = IVD->getNextIvar()) {
3823 if (IVD->isBitField())
3824 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3825 else {
3826 if (!IVars.empty()) {
3827 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828 // Generate the struct type for this group of bitfield ivars.
3829 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3830 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3831 IVars.clear();
3832 }
3833 }
3834 }
3835 if (!IVars.empty()) {
3836 // Do the last one.
3837 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3838 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3839 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3840 }
3841 QualType RetQT = GroupRecordType[tuple];
3842 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3843
3844 return RetQT;
3845}
3846
3847/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3848/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3849void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3850 std::string &Result) {
3851 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3852 Result += CDecl->getName();
3853 Result += "__GRBF_";
3854 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3855 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003856}
3857
3858/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3859/// Name of the struct would be: classname__T_n where n is the group number for
3860/// this ivar.
3861void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3862 std::string &Result) {
3863 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3864 Result += CDecl->getName();
3865 Result += "__T_";
3866 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3867 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003868}
3869
3870/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3871/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3872/// this ivar.
3873void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3874 std::string &Result) {
3875 Result += "OBJC_IVAR_$_";
3876 ObjCIvarBitfieldGroupDecl(IV, Result);
3877}
3878
3879#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3880 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3881 ++IX; \
3882 if (IX < ENDIX) \
3883 --IX; \
3884}
3885
Fariborz Jahanian11671902012-02-07 17:11:38 +00003886/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3887/// an objective-c class with ivars.
3888void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3889 std::string &Result) {
3890 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3891 assert(CDecl->getName() != "" &&
3892 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003893 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003894 SmallVector<ObjCIvarDecl *, 8> IVars;
3895 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003896 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003897 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003898
Fariborz Jahanian11671902012-02-07 17:11:38 +00003899 SourceLocation LocStart = CDecl->getLocStart();
3900 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003901
Fariborz Jahanian11671902012-02-07 17:11:38 +00003902 const char *startBuf = SM->getCharacterData(LocStart);
3903 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003904
Fariborz Jahanian11671902012-02-07 17:11:38 +00003905 // If no ivars and no root or if its root, directly or indirectly,
3906 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003907 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003908 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3909 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3910 ReplaceText(LocStart, endBuf-startBuf, Result);
3911 return;
3912 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003913
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003914 // Insert named struct/union definitions inside class to
3915 // outer scope. This follows semantics of locally defined
3916 // struct/unions in objective-c classes.
3917 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3918 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003919
3920 // Insert named structs which are syntheized to group ivar bitfields
3921 // to outer scope as well.
3922 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3923 if (IVars[i]->isBitField()) {
3924 ObjCIvarDecl *IV = IVars[i];
3925 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3926 RewriteObjCFieldDeclType(QT, Result);
3927 Result += ";";
3928 // skip over ivar bitfields in this group.
3929 SKIP_BITFIELDS(i , e, IVars);
3930 }
3931
Fariborz Jahanian11671902012-02-07 17:11:38 +00003932 Result += "\nstruct ";
3933 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003934 Result += "_IMPL {\n";
3935
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003936 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003937 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3938 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3939 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003940 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003941
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003942 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3943 if (IVars[i]->isBitField()) {
3944 ObjCIvarDecl *IV = IVars[i];
3945 Result += "\tstruct ";
3946 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3947 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3948 // skip over ivar bitfields in this group.
3949 SKIP_BITFIELDS(i , e, IVars);
3950 }
3951 else
3952 RewriteObjCFieldDecl(IVars[i], Result);
3953 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003954
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003955 Result += "};\n";
3956 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3957 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003958 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003959 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003960 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003961}
3962
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003963/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3964/// have been referenced in an ivar access expression.
3965void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3966 std::string &Result) {
3967 // write out ivar offset symbols which have been referenced in an ivar
3968 // access expression.
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003969 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3970
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003971 if (Ivars.empty())
3972 return;
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003973
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003974 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003975 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003976 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3977 unsigned GroupNo = 0;
3978 if (IvarDecl->isBitField()) {
3979 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3980 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3981 continue;
3982 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003983 Result += "\n";
3984 if (LangOpts.MicrosoftExt)
3985 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003986 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003987 if (LangOpts.MicrosoftExt &&
3988 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003989 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3990 Result += "__declspec(dllimport) ";
3991
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003992 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003993 if (IvarDecl->isBitField()) {
3994 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3995 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3996 }
3997 else
3998 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003999 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004000 }
4001}
4002
Fariborz Jahanian11671902012-02-07 17:11:38 +00004003//===----------------------------------------------------------------------===//
4004// Meta Data Emission
4005//===----------------------------------------------------------------------===//
4006
Fariborz Jahanian11671902012-02-07 17:11:38 +00004007/// RewriteImplementations - This routine rewrites all method implementations
4008/// and emits meta-data.
4009
4010void RewriteModernObjC::RewriteImplementations() {
4011 int ClsDefCount = ClassImplementation.size();
4012 int CatDefCount = CategoryImplementation.size();
4013
4014 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004015 for (int i = 0; i < ClsDefCount; i++) {
4016 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4017 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4018 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004019 assert(false &&
4020 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004021 RewriteImplementationDecl(OIMP);
4022 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004023
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004024 for (int i = 0; i < CatDefCount; i++) {
4025 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4026 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4027 if (CDecl->isImplicitInterfaceDecl())
4028 assert(false &&
4029 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004030 RewriteImplementationDecl(CIMP);
4031 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004032}
4033
4034void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4035 const std::string &Name,
4036 ValueDecl *VD, bool def) {
4037 assert(BlockByRefDeclNo.count(VD) &&
4038 "RewriteByRefString: ByRef decl missing");
4039 if (def)
4040 ResultStr += "struct ";
4041 ResultStr += "__Block_byref_" + Name +
4042 "_" + utostr(BlockByRefDeclNo[VD]) ;
4043}
4044
4045static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4046 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4047 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4048 return false;
4049}
4050
4051std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4052 StringRef funcName,
4053 std::string Tag) {
4054 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004055 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004056 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004057 SourceLocation BlockLoc = CE->getExprLoc();
4058 std::string S;
4059 ConvertSourceLocationToLineDirective(BlockLoc, S);
4060
4061 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4062 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004063
4064 BlockDecl *BD = CE->getBlockDecl();
4065
4066 if (isa<FunctionNoProtoType>(AFT)) {
4067 // No user-supplied arguments. Still need to pass in a pointer to the
4068 // block (to reference imported block decl refs).
4069 S += "(" + StructRef + " *__cself)";
4070 } else if (BD->param_empty()) {
4071 S += "(" + StructRef + " *__cself)";
4072 } else {
4073 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4074 assert(FT && "SynthesizeBlockFunc: No function proto");
4075 S += '(';
4076 // first add the implicit argument.
4077 S += StructRef + " *__cself, ";
4078 std::string ParamStr;
4079 for (BlockDecl::param_iterator AI = BD->param_begin(),
4080 E = BD->param_end(); AI != E; ++AI) {
4081 if (AI != BD->param_begin()) S += ", ";
4082 ParamStr = (*AI)->getNameAsString();
4083 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004084 (void)convertBlockPointerToFunctionPointer(QT);
4085 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004086 S += ParamStr;
4087 }
4088 if (FT->isVariadic()) {
4089 if (!BD->param_empty()) S += ", ";
4090 S += "...";
4091 }
4092 S += ')';
4093 }
4094 S += " {\n";
4095
4096 // Create local declarations to avoid rewriting all closure decl ref exprs.
4097 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004098 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004099 E = BlockByRefDecls.end(); I != E; ++I) {
4100 S += " ";
4101 std::string Name = (*I)->getNameAsString();
4102 std::string TypeString;
4103 RewriteByRefString(TypeString, Name, (*I));
4104 TypeString += " *";
4105 Name = TypeString + Name;
4106 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4107 }
4108 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004109 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004110 E = BlockByCopyDecls.end(); I != E; ++I) {
4111 S += " ";
4112 // Handle nested closure invocation. For example:
4113 //
4114 // void (^myImportedClosure)(void);
4115 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4116 //
4117 // void (^anotherClosure)(void);
4118 // anotherClosure = ^(void) {
4119 // myImportedClosure(); // import and invoke the closure
4120 // };
4121 //
4122 if (isTopLevelBlockPointerType((*I)->getType())) {
4123 RewriteBlockPointerTypeVariable(S, (*I));
4124 S += " = (";
4125 RewriteBlockPointerType(S, (*I)->getType());
4126 S += ")";
4127 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4128 }
4129 else {
4130 std::string Name = (*I)->getNameAsString();
4131 QualType QT = (*I)->getType();
4132 if (HasLocalVariableExternalStorage(*I))
4133 QT = Context->getPointerType(QT);
4134 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4135 S += Name + " = __cself->" +
4136 (*I)->getNameAsString() + "; // bound by copy\n";
4137 }
4138 }
4139 std::string RewrittenStr = RewrittenBlockExprs[CE];
4140 const char *cstr = RewrittenStr.c_str();
4141 while (*cstr++ != '{') ;
4142 S += cstr;
4143 S += "\n";
4144 return S;
4145}
4146
4147std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4148 StringRef funcName,
4149 std::string Tag) {
4150 std::string StructRef = "struct " + Tag;
4151 std::string S = "static void __";
4152
4153 S += funcName;
4154 S += "_block_copy_" + utostr(i);
4155 S += "(" + StructRef;
4156 S += "*dst, " + StructRef;
4157 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004158 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004160 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004161 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004162 S += VD->getNameAsString();
4163 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004164 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4165 else if (VD->getType()->isBlockPointerType())
4166 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4167 else
4168 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4169 }
4170 S += "}\n";
4171
4172 S += "\nstatic void __";
4173 S += funcName;
4174 S += "_block_dispose_" + utostr(i);
4175 S += "(" + StructRef;
4176 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004177 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004178 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004179 S += VD->getNameAsString();
4180 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004181 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4182 else if (VD->getType()->isBlockPointerType())
4183 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4184 else
4185 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4186 }
4187 S += "}\n";
4188 return S;
4189}
4190
4191std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4192 std::string Desc) {
4193 std::string S = "\nstruct " + Tag;
4194 std::string Constructor = " " + Tag;
4195
4196 S += " {\n struct __block_impl impl;\n";
4197 S += " struct " + Desc;
4198 S += "* Desc;\n";
4199
4200 Constructor += "(void *fp, "; // Invoke function pointer.
4201 Constructor += "struct " + Desc; // Descriptor pointer.
4202 Constructor += " *desc";
4203
4204 if (BlockDeclRefs.size()) {
4205 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004206 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004207 E = BlockByCopyDecls.end(); I != E; ++I) {
4208 S += " ";
4209 std::string FieldName = (*I)->getNameAsString();
4210 std::string ArgName = "_" + FieldName;
4211 // Handle nested closure invocation. For example:
4212 //
4213 // void (^myImportedBlock)(void);
4214 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4215 //
4216 // void (^anotherBlock)(void);
4217 // anotherBlock = ^(void) {
4218 // myImportedBlock(); // import and invoke the closure
4219 // };
4220 //
4221 if (isTopLevelBlockPointerType((*I)->getType())) {
4222 S += "struct __block_impl *";
4223 Constructor += ", void *" + ArgName;
4224 } else {
4225 QualType QT = (*I)->getType();
4226 if (HasLocalVariableExternalStorage(*I))
4227 QT = Context->getPointerType(QT);
4228 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4229 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4230 Constructor += ", " + ArgName;
4231 }
4232 S += FieldName + ";\n";
4233 }
4234 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004235 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004236 E = BlockByRefDecls.end(); I != E; ++I) {
4237 S += " ";
4238 std::string FieldName = (*I)->getNameAsString();
4239 std::string ArgName = "_" + FieldName;
4240 {
4241 std::string TypeString;
4242 RewriteByRefString(TypeString, FieldName, (*I));
4243 TypeString += " *";
4244 FieldName = TypeString + FieldName;
4245 ArgName = TypeString + ArgName;
4246 Constructor += ", " + ArgName;
4247 }
4248 S += FieldName + "; // by ref\n";
4249 }
4250 // Finish writing the constructor.
4251 Constructor += ", int flags=0)";
4252 // Initialize all "by copy" arguments.
4253 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004254 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004255 E = BlockByCopyDecls.end(); I != E; ++I) {
4256 std::string Name = (*I)->getNameAsString();
4257 if (firsTime) {
4258 Constructor += " : ";
4259 firsTime = false;
4260 }
4261 else
4262 Constructor += ", ";
4263 if (isTopLevelBlockPointerType((*I)->getType()))
4264 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4265 else
4266 Constructor += Name + "(_" + Name + ")";
4267 }
4268 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004269 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004270 E = BlockByRefDecls.end(); I != E; ++I) {
4271 std::string Name = (*I)->getNameAsString();
4272 if (firsTime) {
4273 Constructor += " : ";
4274 firsTime = false;
4275 }
4276 else
4277 Constructor += ", ";
4278 Constructor += Name + "(_" + Name + "->__forwarding)";
4279 }
4280
4281 Constructor += " {\n";
4282 if (GlobalVarDecl)
4283 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4284 else
4285 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4286 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4287
4288 Constructor += " Desc = desc;\n";
4289 } else {
4290 // Finish writing the constructor.
4291 Constructor += ", int flags=0) {\n";
4292 if (GlobalVarDecl)
4293 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4294 else
4295 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4296 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4297 Constructor += " Desc = desc;\n";
4298 }
4299 Constructor += " ";
4300 Constructor += "}\n";
4301 S += Constructor;
4302 S += "};\n";
4303 return S;
4304}
4305
4306std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4307 std::string ImplTag, int i,
4308 StringRef FunName,
4309 unsigned hasCopy) {
4310 std::string S = "\nstatic struct " + DescTag;
4311
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004312 S += " {\n size_t reserved;\n";
4313 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004314 if (hasCopy) {
4315 S += " void (*copy)(struct ";
4316 S += ImplTag; S += "*, struct ";
4317 S += ImplTag; S += "*);\n";
4318
4319 S += " void (*dispose)(struct ";
4320 S += ImplTag; S += "*);\n";
4321 }
4322 S += "} ";
4323
4324 S += DescTag + "_DATA = { 0, sizeof(struct ";
4325 S += ImplTag + ")";
4326 if (hasCopy) {
4327 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4328 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4329 }
4330 S += "};\n";
4331 return S;
4332}
4333
4334void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4335 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004336 bool RewriteSC = (GlobalVarDecl &&
4337 !Blocks.empty() &&
4338 GlobalVarDecl->getStorageClass() == SC_Static &&
4339 GlobalVarDecl->getType().getCVRQualifiers());
4340 if (RewriteSC) {
4341 std::string SC(" void __");
4342 SC += GlobalVarDecl->getNameAsString();
4343 SC += "() {}";
4344 InsertText(FunLocStart, SC);
4345 }
4346
4347 // Insert closures that were part of the function.
4348 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4349 CollectBlockDeclRefInfo(Blocks[i]);
4350 // Need to copy-in the inner copied-in variables not actually used in this
4351 // block.
4352 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004353 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004354 ValueDecl *VD = Exp->getDecl();
4355 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004356 if (!VD->hasAttr<BlocksAttr>()) {
4357 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4358 BlockByCopyDeclsPtrSet.insert(VD);
4359 BlockByCopyDecls.push_back(VD);
4360 }
4361 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004362 }
John McCall113bee02012-03-10 09:33:50 +00004363
4364 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004365 BlockByRefDeclsPtrSet.insert(VD);
4366 BlockByRefDecls.push_back(VD);
4367 }
John McCall113bee02012-03-10 09:33:50 +00004368
Fariborz Jahanian11671902012-02-07 17:11:38 +00004369 // imported objects in the inner blocks not used in the outer
4370 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004371 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004372 VD->getType()->isBlockPointerType())
4373 ImportedBlockDecls.insert(VD);
4374 }
4375
4376 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4377 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4378
4379 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4380
4381 InsertText(FunLocStart, CI);
4382
4383 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4384
4385 InsertText(FunLocStart, CF);
4386
4387 if (ImportedBlockDecls.size()) {
4388 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4389 InsertText(FunLocStart, HF);
4390 }
4391 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4392 ImportedBlockDecls.size() > 0);
4393 InsertText(FunLocStart, BD);
4394
4395 BlockDeclRefs.clear();
4396 BlockByRefDecls.clear();
4397 BlockByRefDeclsPtrSet.clear();
4398 BlockByCopyDecls.clear();
4399 BlockByCopyDeclsPtrSet.clear();
4400 ImportedBlockDecls.clear();
4401 }
4402 if (RewriteSC) {
4403 // Must insert any 'const/volatile/static here. Since it has been
4404 // removed as result of rewriting of block literals.
4405 std::string SC;
4406 if (GlobalVarDecl->getStorageClass() == SC_Static)
4407 SC = "static ";
4408 if (GlobalVarDecl->getType().isConstQualified())
4409 SC += "const ";
4410 if (GlobalVarDecl->getType().isVolatileQualified())
4411 SC += "volatile ";
4412 if (GlobalVarDecl->getType().isRestrictQualified())
4413 SC += "restrict ";
4414 InsertText(FunLocStart, SC);
4415 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004416 if (GlobalConstructionExp) {
4417 // extra fancy dance for global literal expression.
4418
4419 // Always the latest block expression on the block stack.
4420 std::string Tag = "__";
4421 Tag += FunName;
4422 Tag += "_block_impl_";
4423 Tag += utostr(Blocks.size()-1);
4424 std::string globalBuf = "static ";
4425 globalBuf += Tag; globalBuf += " ";
4426 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004427
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004428 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004429 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4430 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004431 globalBuf += constructorExprBuf.str();
4432 globalBuf += ";\n";
4433 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004434 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004435 }
4436
Fariborz Jahanian11671902012-02-07 17:11:38 +00004437 Blocks.clear();
4438 InnerDeclRefsCount.clear();
4439 InnerDeclRefs.clear();
4440 RewrittenBlockExprs.clear();
4441}
4442
4443void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004444 SourceLocation FunLocStart =
4445 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4446 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004447 StringRef FuncName = FD->getName();
4448
4449 SynthesizeBlockLiterals(FunLocStart, FuncName);
4450}
4451
4452static void BuildUniqueMethodName(std::string &Name,
4453 ObjCMethodDecl *MD) {
4454 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4455 Name = IFace->getName();
4456 Name += "__" + MD->getSelector().getAsString();
4457 // Convert colons to underscores.
4458 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00004459 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004460 Name.replace(loc, 1, "_");
4461}
4462
4463void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4464 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4465 //SourceLocation FunLocStart = MD->getLocStart();
4466 SourceLocation FunLocStart = MD->getLocStart();
4467 std::string FuncName;
4468 BuildUniqueMethodName(FuncName, MD);
4469 SynthesizeBlockLiterals(FunLocStart, FuncName);
4470}
4471
4472void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004473 for (Stmt *SubStmt : S->children())
4474 if (SubStmt) {
4475 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004476 GetBlockDeclRefExprs(CBE->getBody());
4477 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004478 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004479 }
4480 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004482 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004483 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004484 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004485 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004486}
4487
Craig Topper5603df42013-07-05 19:34:19 +00004488void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4489 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004490 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004491 for (Stmt *SubStmt : S->children())
4492 if (SubStmt) {
4493 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004494 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4495 GetInnerBlockDeclRefExprs(CBE->getBody(),
4496 InnerBlockDeclRefs,
4497 InnerContexts);
4498 }
4499 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004500 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004501 }
4502 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004504 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004505 HasLocalVariableExternalStorage(DRE->getDecl())) {
4506 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004507 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004508 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004509 if (Var->isFunctionOrMethodVarDecl())
4510 ImportedLocalExternalDecls.insert(Var);
4511 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004512 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004513}
4514
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004515/// convertObjCTypeToCStyleType - This routine converts such objc types
4516/// as qualified objects, and blocks to their closest c/c++ types that
4517/// it can. It returns true if input type was modified.
4518bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4519 QualType oldT = T;
4520 convertBlockPointerToFunctionPointer(T);
4521 if (T->isFunctionPointerType()) {
4522 QualType PointeeTy;
4523 if (const PointerType* PT = T->getAs<PointerType>()) {
4524 PointeeTy = PT->getPointeeType();
4525 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4526 T = convertFunctionTypeOfBlocks(FT);
4527 T = Context->getPointerType(T);
4528 }
4529 }
4530 }
4531
4532 convertToUnqualifiedObjCType(T);
4533 return T != oldT;
4534}
4535
Fariborz Jahanian11671902012-02-07 17:11:38 +00004536/// convertFunctionTypeOfBlocks - This routine converts a function type
4537/// whose result type may be a block pointer or whose argument type(s)
4538/// might be block pointers to an equivalent function type replacing
4539/// all block pointers to function pointers.
4540QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4541 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4542 // FTP will be null for closures that don't take arguments.
4543 // Generate a funky cast.
4544 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004545 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004546 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547
4548 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004549 for (auto &I : FTP->param_types()) {
4550 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004551 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004552 if (convertObjCTypeToCStyleType(t))
4553 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004554 ArgTypes.push_back(t);
4555 }
4556 }
4557 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004558 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004559 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004560 else FuncType = QualType(FT, 0);
4561 return FuncType;
4562}
4563
4564Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4565 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004566 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004567
4568 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4569 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004570 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4571 CPT = MExpr->getType()->getAs<BlockPointerType>();
4572 }
4573 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4574 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4575 }
4576 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4577 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4578 else if (const ConditionalOperator *CEXPR =
4579 dyn_cast<ConditionalOperator>(BlockExp)) {
4580 Expr *LHSExp = CEXPR->getLHS();
4581 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4582 Expr *RHSExp = CEXPR->getRHS();
4583 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4584 Expr *CONDExp = CEXPR->getCond();
4585 ConditionalOperator *CondExpr =
4586 new (Context) ConditionalOperator(CONDExp,
4587 SourceLocation(), cast<Expr>(LHSStmt),
4588 SourceLocation(), cast<Expr>(RHSStmt),
4589 Exp->getType(), VK_RValue, OK_Ordinary);
4590 return CondExpr;
4591 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4592 CPT = IRE->getType()->getAs<BlockPointerType>();
4593 } else if (const PseudoObjectExpr *POE
4594 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4595 CPT = POE->getType()->castAs<BlockPointerType>();
4596 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004597 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004598 }
4599 assert(CPT && "RewriteBlockClass: Bad type");
4600 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4601 assert(FT && "RewriteBlockClass: Bad type");
4602 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4603 // FTP will be null for closures that don't take arguments.
4604
4605 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4606 SourceLocation(), SourceLocation(),
4607 &Context->Idents.get("__block_impl"));
4608 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4609
4610 // Generate a funky cast.
4611 SmallVector<QualType, 8> ArgTypes;
4612
4613 // Push the block argument type.
4614 ArgTypes.push_back(PtrBlock);
4615 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004616 for (auto &I : FTP->param_types()) {
4617 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004618 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4619 if (!convertBlockPointerToFunctionPointer(t))
4620 convertToUnqualifiedObjCType(t);
4621 ArgTypes.push_back(t);
4622 }
4623 }
4624 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004625 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004626
4627 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4628
4629 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4630 CK_BitCast,
4631 const_cast<Expr*>(BlockExp));
4632 // Don't forget the parens to enforce the proper binding.
4633 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4634 BlkCast);
4635 //PE->dump();
4636
Craig Topper8ae12032014-05-07 06:21:57 +00004637 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004638 SourceLocation(),
4639 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004640 Context->VoidPtrTy, nullptr,
4641 /*BitWidth=*/nullptr, /*Mutable=*/true,
4642 ICIS_NoInit);
4643 MemberExpr *ME =
4644 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4645 FD->getType(), VK_LValue, OK_Ordinary);
4646
4647 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4648 CK_BitCast, ME);
4649 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004650
4651 SmallVector<Expr*, 8> BlkExprs;
4652 // Add the implicit argument.
4653 BlkExprs.push_back(BlkCast);
4654 // Add the user arguments.
4655 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4656 E = Exp->arg_end(); I != E; ++I) {
4657 BlkExprs.push_back(*I);
4658 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004659 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004660 Exp->getType(), VK_RValue,
4661 SourceLocation());
4662 return CE;
4663}
4664
4665// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004666// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004667// For example:
4668//
4669// int main() {
4670// __block Foo *f;
4671// __block int i;
4672//
4673// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004674// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004675// i = 77;
4676// };
4677//}
John McCall113bee02012-03-10 09:33:50 +00004678Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004679 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4680 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004681 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004682 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004683 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004684
4685 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004686 SourceLocation(),
4687 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004688 Context->VoidPtrTy, nullptr,
4689 /*BitWidth=*/nullptr, /*Mutable=*/true,
4690 ICIS_NoInit);
4691 MemberExpr *ME = new (Context)
4692 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4693 FD->getType(), VK_LValue, OK_Ordinary);
4694
4695 StringRef Name = VD->getName();
4696 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004697 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004698 Context->VoidPtrTy, nullptr,
4699 /*BitWidth=*/nullptr, /*Mutable=*/true,
4700 ICIS_NoInit);
4701 ME =
4702 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4703 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4704
4705 // Need parens to enforce precedence.
4706 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4707 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004708 ME);
4709 ReplaceStmt(DeclRefExp, PE);
4710 return PE;
4711}
4712
4713// Rewrites the imported local variable V with external storage
4714// (static, extern, etc.) as *V
4715//
4716Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4717 ValueDecl *VD = DRE->getDecl();
4718 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4719 if (!ImportedLocalExternalDecls.count(Var))
4720 return DRE;
4721 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4722 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00004723 DRE->getLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004724 // Need parens to enforce precedence.
4725 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4726 Exp);
4727 ReplaceStmt(DRE, PE);
4728 return PE;
4729}
4730
4731void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4732 SourceLocation LocStart = CE->getLParenLoc();
4733 SourceLocation LocEnd = CE->getRParenLoc();
4734
4735 // Need to avoid trying to rewrite synthesized casts.
4736 if (LocStart.isInvalid())
4737 return;
4738 // Need to avoid trying to rewrite casts contained in macros.
4739 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4740 return;
4741
4742 const char *startBuf = SM->getCharacterData(LocStart);
4743 const char *endBuf = SM->getCharacterData(LocEnd);
4744 QualType QT = CE->getType();
4745 const Type* TypePtr = QT->getAs<Type>();
4746 if (isa<TypeOfExprType>(TypePtr)) {
4747 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4748 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4749 std::string TypeAsString = "(";
4750 RewriteBlockPointerType(TypeAsString, QT);
4751 TypeAsString += ")";
4752 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4753 return;
4754 }
4755 // advance the location to startArgList.
4756 const char *argPtr = startBuf;
4757
4758 while (*argPtr++ && (argPtr < endBuf)) {
4759 switch (*argPtr) {
4760 case '^':
4761 // Replace the '^' with '*'.
4762 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4763 ReplaceText(LocStart, 1, "*");
4764 break;
4765 }
4766 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004767}
4768
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004769void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4770 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004771 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4772 CastKind != CK_AnyPointerToBlockPointerCast)
4773 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004774
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004775 QualType QT = IC->getType();
4776 (void)convertBlockPointerToFunctionPointer(QT);
4777 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4778 std::string Str = "(";
4779 Str += TypeString;
4780 Str += ")";
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004781 InsertText(IC->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004782}
4783
Fariborz Jahanian11671902012-02-07 17:11:38 +00004784void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4785 SourceLocation DeclLoc = FD->getLocation();
4786 unsigned parenCount = 0;
4787
4788 // We have 1 or more arguments that have closure pointers.
4789 const char *startBuf = SM->getCharacterData(DeclLoc);
4790 const char *startArgList = strchr(startBuf, '(');
4791
4792 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4793
4794 parenCount++;
4795 // advance the location to startArgList.
4796 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4797 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4798
4799 const char *argPtr = startArgList;
4800
4801 while (*argPtr++ && parenCount) {
4802 switch (*argPtr) {
4803 case '^':
4804 // Replace the '^' with '*'.
4805 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4806 ReplaceText(DeclLoc, 1, "*");
4807 break;
4808 case '(':
4809 parenCount++;
4810 break;
4811 case ')':
4812 parenCount--;
4813 break;
4814 }
4815 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004816}
4817
4818bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4819 const FunctionProtoType *FTP;
4820 const PointerType *PT = QT->getAs<PointerType>();
4821 if (PT) {
4822 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4823 } else {
4824 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4825 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4826 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4827 }
4828 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004829 for (const auto &I : FTP->param_types())
4830 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004831 return true;
4832 }
4833 return false;
4834}
4835
4836bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4837 const FunctionProtoType *FTP;
4838 const PointerType *PT = QT->getAs<PointerType>();
4839 if (PT) {
4840 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4841 } else {
4842 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4843 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4844 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4845 }
4846 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004847 for (const auto &I : FTP->param_types()) {
4848 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004849 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004850 if (I->isObjCObjectPointerType() &&
4851 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004852 return true;
4853 }
4854
4855 }
4856 return false;
4857}
4858
4859void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4860 const char *&RParen) {
4861 const char *argPtr = strchr(Name, '(');
4862 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4863
4864 LParen = argPtr; // output the start.
4865 argPtr++; // skip past the left paren.
4866 unsigned parenCount = 1;
4867
4868 while (*argPtr && parenCount) {
4869 switch (*argPtr) {
4870 case '(': parenCount++; break;
4871 case ')': parenCount--; break;
4872 default: break;
4873 }
4874 if (parenCount) argPtr++;
4875 }
4876 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4877 RParen = argPtr; // output the end
4878}
4879
4880void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4881 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4882 RewriteBlockPointerFunctionArgs(FD);
4883 return;
4884 }
4885 // Handle Variables and Typedefs.
4886 SourceLocation DeclLoc = ND->getLocation();
4887 QualType DeclT;
4888 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4889 DeclT = VD->getType();
4890 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4891 DeclT = TDD->getUnderlyingType();
4892 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4893 DeclT = FD->getType();
4894 else
4895 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4896
4897 const char *startBuf = SM->getCharacterData(DeclLoc);
4898 const char *endBuf = startBuf;
4899 // scan backward (from the decl location) for the end of the previous decl.
4900 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4901 startBuf--;
4902 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4903 std::string buf;
4904 unsigned OrigLength=0;
4905 // *startBuf != '^' if we are dealing with a pointer to function that
4906 // may take block argument types (which will be handled below).
4907 if (*startBuf == '^') {
4908 // Replace the '^' with '*', computing a negative offset.
4909 buf = '*';
4910 startBuf++;
4911 OrigLength++;
4912 }
4913 while (*startBuf != ')') {
4914 buf += *startBuf;
4915 startBuf++;
4916 OrigLength++;
4917 }
4918 buf += ')';
4919 OrigLength++;
4920
4921 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4922 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4923 // Replace the '^' with '*' for arguments.
4924 // Replace id<P> with id/*<>*/
4925 DeclLoc = ND->getLocation();
4926 startBuf = SM->getCharacterData(DeclLoc);
4927 const char *argListBegin, *argListEnd;
4928 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4929 while (argListBegin < argListEnd) {
4930 if (*argListBegin == '^')
4931 buf += '*';
4932 else if (*argListBegin == '<') {
4933 buf += "/*";
4934 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004935 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004936 while (*argListBegin != '>') {
4937 buf += *argListBegin++;
4938 OrigLength++;
4939 }
4940 buf += *argListBegin;
4941 buf += "*/";
4942 }
4943 else
4944 buf += *argListBegin;
4945 argListBegin++;
4946 OrigLength++;
4947 }
4948 buf += ')';
4949 OrigLength++;
4950 }
4951 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004952}
4953
Fariborz Jahanian11671902012-02-07 17:11:38 +00004954/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4955/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4956/// struct Block_byref_id_object *src) {
4957/// _Block_object_assign (&_dest->object, _src->object,
4958/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4959/// [|BLOCK_FIELD_IS_WEAK]) // object
4960/// _Block_object_assign(&_dest->object, _src->object,
4961/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4962/// [|BLOCK_FIELD_IS_WEAK]) // block
4963/// }
4964/// And:
4965/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4966/// _Block_object_dispose(_src->object,
4967/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4968/// [|BLOCK_FIELD_IS_WEAK]) // object
4969/// _Block_object_dispose(_src->object,
4970/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4971/// [|BLOCK_FIELD_IS_WEAK]) // block
4972/// }
4973
4974std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4975 int flag) {
4976 std::string S;
4977 if (CopyDestroyCache.count(flag))
4978 return S;
4979 CopyDestroyCache.insert(flag);
4980 S = "static void __Block_byref_id_object_copy_";
4981 S += utostr(flag);
4982 S += "(void *dst, void *src) {\n";
4983
4984 // offset into the object pointer is computed as:
4985 // void * + void* + int + int + void* + void *
4986 unsigned IntSize =
4987 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4988 unsigned VoidPtrSize =
4989 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4990
4991 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4992 S += " _Block_object_assign((char*)dst + ";
4993 S += utostr(offset);
4994 S += ", *(void * *) ((char*)src + ";
4995 S += utostr(offset);
4996 S += "), ";
4997 S += utostr(flag);
4998 S += ");\n}\n";
4999
5000 S += "static void __Block_byref_id_object_dispose_";
5001 S += utostr(flag);
5002 S += "(void *src) {\n";
5003 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5004 S += utostr(offset);
5005 S += "), ";
5006 S += utostr(flag);
5007 S += ");\n}\n";
5008 return S;
5009}
5010
5011/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5012/// the declaration into:
5013/// struct __Block_byref_ND {
5014/// void *__isa; // NULL for everything except __weak pointers
5015/// struct __Block_byref_ND *__forwarding;
5016/// int32_t __flags;
5017/// int32_t __size;
5018/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5019/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5020/// typex ND;
5021/// };
5022///
5023/// It then replaces declaration of ND variable with:
5024/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5025/// __size=sizeof(struct __Block_byref_ND),
5026/// ND=initializer-if-any};
5027///
5028///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005029void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5030 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005031 int flag = 0;
5032 int isa = 0;
5033 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5034 if (DeclLoc.isInvalid())
5035 // If type location is missing, it is because of missing type (a warning).
5036 // Use variable's location which is good for this case.
5037 DeclLoc = ND->getLocation();
5038 const char *startBuf = SM->getCharacterData(DeclLoc);
5039 SourceLocation X = ND->getLocEnd();
5040 X = SM->getExpansionLoc(X);
5041 const char *endBuf = SM->getCharacterData(X);
5042 std::string Name(ND->getNameAsString());
5043 std::string ByrefType;
5044 RewriteByRefString(ByrefType, Name, ND, true);
5045 ByrefType += " {\n";
5046 ByrefType += " void *__isa;\n";
5047 RewriteByRefString(ByrefType, Name, ND);
5048 ByrefType += " *__forwarding;\n";
5049 ByrefType += " int __flags;\n";
5050 ByrefType += " int __size;\n";
5051 // Add void *__Block_byref_id_object_copy;
5052 // void *__Block_byref_id_object_dispose; if needed.
5053 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005054 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005055 if (HasCopyAndDispose) {
5056 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5057 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5058 }
5059
5060 QualType T = Ty;
5061 (void)convertBlockPointerToFunctionPointer(T);
5062 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5063
5064 ByrefType += " " + Name + ";\n";
5065 ByrefType += "};\n";
5066 // Insert this type in global scope. It is needed by helper function.
5067 SourceLocation FunLocStart;
5068 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005069 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005070 else {
5071 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5072 FunLocStart = CurMethodDef->getLocStart();
5073 }
5074 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005075
Fariborz Jahanian11671902012-02-07 17:11:38 +00005076 if (Ty.isObjCGCWeak()) {
5077 flag |= BLOCK_FIELD_IS_WEAK;
5078 isa = 1;
5079 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005080 if (HasCopyAndDispose) {
5081 flag = BLOCK_BYREF_CALLER;
5082 QualType Ty = ND->getType();
5083 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5084 if (Ty->isBlockPointerType())
5085 flag |= BLOCK_FIELD_IS_BLOCK;
5086 else
5087 flag |= BLOCK_FIELD_IS_OBJECT;
5088 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5089 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005090 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005091 }
5092
5093 // struct __Block_byref_ND ND =
5094 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5095 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005096 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005097 // FIXME. rewriter does not support __block c++ objects which
5098 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005099 if (hasInit)
5100 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5101 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5102 if (CXXDecl && CXXDecl->isDefaultConstructor())
5103 hasInit = false;
5104 }
5105
Fariborz Jahanian11671902012-02-07 17:11:38 +00005106 unsigned flags = 0;
5107 if (HasCopyAndDispose)
5108 flags |= BLOCK_HAS_COPY_DISPOSE;
5109 Name = ND->getNameAsString();
5110 ByrefType.clear();
5111 RewriteByRefString(ByrefType, Name, ND);
5112 std::string ForwardingCastType("(");
5113 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005114 ByrefType += " " + Name + " = {(void*)";
5115 ByrefType += utostr(isa);
5116 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5117 ByrefType += utostr(flags);
5118 ByrefType += ", ";
5119 ByrefType += "sizeof(";
5120 RewriteByRefString(ByrefType, Name, ND);
5121 ByrefType += ")";
5122 if (HasCopyAndDispose) {
5123 ByrefType += ", __Block_byref_id_object_copy_";
5124 ByrefType += utostr(flag);
5125 ByrefType += ", __Block_byref_id_object_dispose_";
5126 ByrefType += utostr(flag);
5127 }
5128
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005129 if (!firstDecl) {
5130 // In multiple __block declarations, and for all but 1st declaration,
5131 // find location of the separating comma. This would be start location
5132 // where new text is to be inserted.
5133 DeclLoc = ND->getLocation();
5134 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5135 const char *commaBuf = startDeclBuf;
5136 while (*commaBuf != ',')
5137 commaBuf--;
5138 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5139 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5140 startBuf = commaBuf;
5141 }
5142
Fariborz Jahanian11671902012-02-07 17:11:38 +00005143 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005144 ByrefType += "};\n";
5145 unsigned nameSize = Name.size();
Simon Pilgrim2c518802017-03-30 14:13:19 +00005146 // for block or function pointer declaration. Name is already
Fariborz Jahanian11671902012-02-07 17:11:38 +00005147 // part of the declaration.
5148 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5149 nameSize = 1;
5150 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5151 }
5152 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005153 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005154 SourceLocation startLoc;
5155 Expr *E = ND->getInit();
5156 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5157 startLoc = ECE->getLParenLoc();
5158 else
5159 startLoc = E->getLocStart();
5160 startLoc = SM->getExpansionLoc(startLoc);
5161 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005162 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005163
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005164 const char separator = lastDecl ? ';' : ',';
5165 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5166 const char *separatorBuf = strchr(startInitializerBuf, separator);
5167 assert((*separatorBuf == separator) &&
5168 "RewriteByRefVar: can't find ';' or ','");
5169 SourceLocation separatorLoc =
5170 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5171
5172 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005173 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005174}
5175
5176void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5177 // Add initializers for any closure decl refs.
5178 GetBlockDeclRefExprs(Exp->getBody());
5179 if (BlockDeclRefs.size()) {
5180 // Unique all "by copy" declarations.
5181 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005182 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005183 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5184 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5185 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5186 }
5187 }
5188 // Unique all "by ref" declarations.
5189 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005190 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005191 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5192 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5193 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5194 }
5195 }
5196 // Find any imported blocks...they will need special attention.
5197 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005198 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005199 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5200 BlockDeclRefs[i]->getType()->isBlockPointerType())
5201 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5202 }
5203}
5204
5205FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5206 IdentifierInfo *ID = &Context->Idents.get(name);
5207 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5208 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005209 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005210 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211}
5212
5213Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005214 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005215 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005216
Fariborz Jahanian11671902012-02-07 17:11:38 +00005217 Blocks.push_back(Exp);
5218
5219 CollectBlockDeclRefInfo(Exp);
5220
5221 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005222 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005223 if (!InnerBlockDeclRefs.empty()) {
5224 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005225 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005226 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005227 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005228 // We need to save the copied-in variables in nested
5229 // blocks because it is needed at the end for some of the API generations.
5230 // See SynthesizeBlockLiterals routine.
5231 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5232 BlockDeclRefs.push_back(Exp);
5233 BlockByCopyDeclsPtrSet.insert(VD);
5234 BlockByCopyDecls.push_back(VD);
5235 }
John McCall113bee02012-03-10 09:33:50 +00005236 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5238 BlockDeclRefs.push_back(Exp);
5239 BlockByRefDeclsPtrSet.insert(VD);
5240 BlockByRefDecls.push_back(VD);
5241 }
5242 }
5243 // Find any imported blocks...they will need special attention.
5244 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005245 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005246 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5247 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5248 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5249 }
5250 InnerDeclRefsCount.push_back(countOfInnerDecls);
5251
5252 std::string FuncName;
5253
5254 if (CurFunctionDef)
5255 FuncName = CurFunctionDef->getNameAsString();
5256 else if (CurMethodDef)
5257 BuildUniqueMethodName(FuncName, CurMethodDef);
5258 else if (GlobalVarDecl)
5259 FuncName = std::string(GlobalVarDecl->getNameAsString());
5260
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005261 bool GlobalBlockExpr =
5262 block->getDeclContext()->getRedeclContext()->isFileContext();
5263
5264 if (GlobalBlockExpr && !GlobalVarDecl) {
5265 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5266 GlobalBlockExpr = false;
5267 }
5268
Fariborz Jahanian11671902012-02-07 17:11:38 +00005269 std::string BlockNumber = utostr(Blocks.size()-1);
5270
Fariborz Jahanian11671902012-02-07 17:11:38 +00005271 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5272
5273 // Get a pointer to the function type so we can cast appropriately.
5274 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5275 QualType FType = Context->getPointerType(BFT);
5276
5277 FunctionDecl *FD;
5278 Expr *NewRep;
5279
Benjamin Kramer60509af2013-09-09 14:48:42 +00005280 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005281 std::string Tag;
5282
5283 if (GlobalBlockExpr)
5284 Tag = "__global_";
5285 else
5286 Tag = "__";
5287 Tag += FuncName + "_block_impl_" + BlockNumber;
5288
Fariborz Jahanian11671902012-02-07 17:11:38 +00005289 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005290 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005291 SourceLocation());
5292
5293 SmallVector<Expr*, 4> InitExprs;
5294
5295 // Initialize the block function.
5296 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005297 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5298 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005299 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5300 CK_BitCast, Arg);
5301 InitExprs.push_back(castExpr);
5302
5303 // Initialize the block descriptor.
5304 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5305
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005306 VarDecl *NewVD = VarDecl::Create(
5307 *Context, TUDecl, SourceLocation(), SourceLocation(),
5308 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005309 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005310 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005311 Context->VoidPtrTy,
5312 VK_LValue,
5313 SourceLocation()),
5314 UO_AddrOf,
5315 Context->getPointerType(Context->VoidPtrTy),
5316 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00005317 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005318 InitExprs.push_back(DescRefExpr);
5319
5320 // Add initializers for any closure decl refs.
5321 if (BlockDeclRefs.size()) {
5322 Expr *Exp;
5323 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005324 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005325 E = BlockByCopyDecls.end(); I != E; ++I) {
5326 if (isObjCType((*I)->getType())) {
5327 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5328 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005329 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5330 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005331 if (HasLocalVariableExternalStorage(*I)) {
5332 QualType QT = (*I)->getType();
5333 QT = Context->getPointerType(QT);
5334 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005335 OK_Ordinary, SourceLocation(),
5336 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005337 }
5338 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5339 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005340 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5341 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005342 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5343 CK_BitCast, Arg);
5344 } else {
5345 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005346 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5347 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005348 if (HasLocalVariableExternalStorage(*I)) {
5349 QualType QT = (*I)->getType();
5350 QT = Context->getPointerType(QT);
5351 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005352 OK_Ordinary, SourceLocation(),
5353 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005354 }
5355
5356 }
5357 InitExprs.push_back(Exp);
5358 }
5359 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005360 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 E = BlockByRefDecls.end(); I != E; ++I) {
5362 ValueDecl *ND = (*I);
5363 std::string Name(ND->getNameAsString());
5364 std::string RecName;
5365 RewriteByRefString(RecName, Name, ND, true);
5366 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5367 + sizeof("struct"));
5368 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5369 SourceLocation(), SourceLocation(),
5370 II);
5371 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5372 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5373
5374 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005375 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005376 SourceLocation());
5377 bool isNestedCapturedVar = false;
5378 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005379 for (const auto &CI : block->captures()) {
5380 const VarDecl *variable = CI.getVariable();
5381 if (variable == ND && CI.isNested()) {
5382 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005383 "SynthBlockInitExpr - captured block variable is not byref");
5384 isNestedCapturedVar = true;
5385 break;
5386 }
5387 }
5388 // captured nested byref variable has its address passed. Do not take
5389 // its address again.
5390 if (!isNestedCapturedVar)
5391 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5392 Context->getPointerType(Exp->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005393 VK_RValue, OK_Ordinary, SourceLocation(),
5394 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5396 InitExprs.push_back(Exp);
5397 }
5398 }
5399 if (ImportedBlockDecls.size()) {
5400 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5401 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5402 unsigned IntSize =
5403 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5404 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5405 Context->IntTy, SourceLocation());
5406 InitExprs.push_back(FlagExp);
5407 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005408 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005409 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005410
5411 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005412 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005413 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5414 GlobalConstructionExp = NewRep;
5415 NewRep = DRE;
5416 }
5417
Fariborz Jahanian11671902012-02-07 17:11:38 +00005418 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5419 Context->getPointerType(NewRep->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005420 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005421 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5422 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005423 // Put Paren around the call.
5424 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5425 NewRep);
5426
Fariborz Jahanian11671902012-02-07 17:11:38 +00005427 BlockDeclRefs.clear();
5428 BlockByRefDecls.clear();
5429 BlockByRefDeclsPtrSet.clear();
5430 BlockByCopyDecls.clear();
5431 BlockByCopyDeclsPtrSet.clear();
5432 ImportedBlockDecls.clear();
5433 return NewRep;
5434}
5435
5436bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5437 if (const ObjCForCollectionStmt * CS =
5438 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5439 return CS->getElement() == DS;
5440 return false;
5441}
5442
5443//===----------------------------------------------------------------------===//
5444// Function Body / Expression rewriting
5445//===----------------------------------------------------------------------===//
5446
5447Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5448 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5449 isa<DoStmt>(S) || isa<ForStmt>(S))
5450 Stmts.push_back(S);
5451 else if (isa<ObjCForCollectionStmt>(S)) {
5452 Stmts.push_back(S);
5453 ObjCBcLabelNo.push_back(++BcLabelCount);
5454 }
5455
5456 // Pseudo-object operations and ivar references need special
5457 // treatment because we're going to recursively rewrite them.
5458 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5459 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5460 return RewritePropertyOrImplicitSetter(PseudoOp);
5461 } else {
5462 return RewritePropertyOrImplicitGetter(PseudoOp);
5463 }
5464 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5465 return RewriteObjCIvarRefExpr(IvarRefExpr);
5466 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005467 else if (isa<OpaqueValueExpr>(S))
5468 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005469
5470 SourceRange OrigStmtRange = S->getSourceRange();
5471
5472 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005473 for (Stmt *&childStmt : S->children())
5474 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005475 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5476 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005477 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005478 }
5479 }
5480
5481 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005482 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005483 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5484 InnerContexts.insert(BE->getBlockDecl());
5485 ImportedLocalExternalDecls.clear();
5486 GetInnerBlockDeclRefExprs(BE->getBody(),
5487 InnerBlockDeclRefs, InnerContexts);
5488 // Rewrite the block body in place.
5489 Stmt *SaveCurrentBody = CurrentBody;
5490 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005491 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005492 // block literal on rhs of a property-dot-sytax assignment
5493 // must be replaced by its synthesize ast so getRewrittenText
5494 // works as expected. In this case, what actually ends up on RHS
5495 // is the blockTranscribed which is the helper function for the
5496 // block literal; as in: self.c = ^() {[ace ARR];};
5497 bool saveDisableReplaceStmt = DisableReplaceStmt;
5498 DisableReplaceStmt = false;
5499 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5500 DisableReplaceStmt = saveDisableReplaceStmt;
5501 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005502 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005503 ImportedLocalExternalDecls.clear();
5504 // Now we snarf the rewritten text and stash it away for later use.
5505 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5506 RewrittenBlockExprs[BE] = Str;
5507
5508 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5509
5510 //blockTranscribed->dump();
5511 ReplaceStmt(S, blockTranscribed);
5512 return blockTranscribed;
5513 }
5514 // Handle specific things.
5515 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5516 return RewriteAtEncode(AtEncode);
5517
5518 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5519 return RewriteAtSelector(AtSelector);
5520
5521 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5522 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005523
5524 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5525 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005526
Patrick Beard0caa3942012-04-19 00:25:12 +00005527 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5528 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005529
5530 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5531 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005532
5533 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5534 dyn_cast<ObjCDictionaryLiteral>(S))
5535 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005536
5537 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5538#if 0
5539 // Before we rewrite it, put the original message expression in a comment.
5540 SourceLocation startLoc = MessExpr->getLocStart();
5541 SourceLocation endLoc = MessExpr->getLocEnd();
5542
5543 const char *startBuf = SM->getCharacterData(startLoc);
5544 const char *endBuf = SM->getCharacterData(endLoc);
5545
5546 std::string messString;
5547 messString += "// ";
5548 messString.append(startBuf, endBuf-startBuf+1);
5549 messString += "\n";
5550
5551 // FIXME: Missing definition of
5552 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005553 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005554 // Tried this, but it didn't work either...
5555 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5556#endif
5557 return RewriteMessageExpr(MessExpr);
5558 }
5559
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005560 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5561 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5562 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5563 }
5564
Fariborz Jahanian11671902012-02-07 17:11:38 +00005565 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5566 return RewriteObjCTryStmt(StmtTry);
5567
5568 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5569 return RewriteObjCSynchronizedStmt(StmtTry);
5570
5571 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5572 return RewriteObjCThrowStmt(StmtThrow);
5573
5574 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5575 return RewriteObjCProtocolExpr(ProtocolExp);
5576
5577 if (ObjCForCollectionStmt *StmtForCollection =
5578 dyn_cast<ObjCForCollectionStmt>(S))
5579 return RewriteObjCForCollectionStmt(StmtForCollection,
5580 OrigStmtRange.getEnd());
5581 if (BreakStmt *StmtBreakStmt =
5582 dyn_cast<BreakStmt>(S))
5583 return RewriteBreakStmt(StmtBreakStmt);
5584 if (ContinueStmt *StmtContinueStmt =
5585 dyn_cast<ContinueStmt>(S))
5586 return RewriteContinueStmt(StmtContinueStmt);
5587
5588 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5589 // and cast exprs.
5590 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5591 // FIXME: What we're doing here is modifying the type-specifier that
5592 // precedes the first Decl. In the future the DeclGroup should have
5593 // a separate type-specifier that we can rewrite.
5594 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5595 // the context of an ObjCForCollectionStmt. For example:
5596 // NSArray *someArray;
5597 // for (id <FooProtocol> index in someArray) ;
5598 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5599 // and it depends on the original text locations/positions.
5600 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5601 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5602
5603 // Blocks rewrite rules.
5604 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5605 DI != DE; ++DI) {
5606 Decl *SD = *DI;
5607 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5608 if (isTopLevelBlockPointerType(ND->getType()))
5609 RewriteBlockPointerDecl(ND);
5610 else if (ND->getType()->isFunctionPointerType())
5611 CheckFunctionPointerDecl(ND->getType(), ND);
5612 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5613 if (VD->hasAttr<BlocksAttr>()) {
5614 static unsigned uniqueByrefDeclCount = 0;
5615 assert(!BlockByRefDeclNo.count(ND) &&
5616 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5617 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005618 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005619 }
5620 else
5621 RewriteTypeOfDecl(VD);
5622 }
5623 }
5624 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5625 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5626 RewriteBlockPointerDecl(TD);
5627 else if (TD->getUnderlyingType()->isFunctionPointerType())
5628 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5629 }
5630 }
5631 }
5632
5633 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5634 RewriteObjCQualifiedInterfaceTypes(CE);
5635
5636 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5637 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5638 assert(!Stmts.empty() && "Statement stack is empty");
5639 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5640 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5641 && "Statement stack mismatch");
5642 Stmts.pop_back();
5643 }
5644 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005645 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5646 ValueDecl *VD = DRE->getDecl();
5647 if (VD->hasAttr<BlocksAttr>())
5648 return RewriteBlockDeclRefExpr(DRE);
5649 if (HasLocalVariableExternalStorage(VD))
5650 return RewriteLocalVariableExternalStorage(DRE);
5651 }
5652
5653 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5654 if (CE->getCallee()->getType()->isBlockPointerType()) {
5655 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5656 ReplaceStmt(S, BlockCall);
5657 return BlockCall;
5658 }
5659 }
5660 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5661 RewriteCastExpr(CE);
5662 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005663 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5664 RewriteImplicitCastObjCExpr(ICE);
5665 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005666#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005667
Fariborz Jahanian11671902012-02-07 17:11:38 +00005668 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5669 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5670 ICE->getSubExpr(),
5671 SourceLocation());
5672 // Get the new text.
5673 std::string SStr;
5674 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005675 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005676 const std::string &Str = Buf.str();
5677
5678 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005679 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005680 delete S;
5681 return Replacement;
5682 }
5683#endif
5684 // Return this stmt unmodified.
5685 return S;
5686}
5687
5688void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005689 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005690 if (isTopLevelBlockPointerType(FD->getType()))
5691 RewriteBlockPointerDecl(FD);
5692 if (FD->getType()->isObjCQualifiedIdType() ||
5693 FD->getType()->isObjCQualifiedInterfaceType())
5694 RewriteObjCQualifiedInterfaceTypes(FD);
5695 }
5696}
5697
5698/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5699/// main file of the input.
5700void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5701 switch (D->getKind()) {
5702 case Decl::Function: {
5703 FunctionDecl *FD = cast<FunctionDecl>(D);
5704 if (FD->isOverloadedOperator())
5705 return;
5706
5707 // Since function prototypes don't have ParmDecl's, we check the function
5708 // prototype. This enables us to rewrite function declarations and
5709 // definitions using the same code.
5710 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5711
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005712 if (!FD->isThisDeclarationADefinition())
5713 break;
5714
Fariborz Jahanian11671902012-02-07 17:11:38 +00005715 // FIXME: If this should support Obj-C++, support CXXTryStmt
5716 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5717 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005718 CurrentBody = Body;
5719 Body =
5720 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5721 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005722 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005723 if (PropParentMap) {
5724 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005725 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005726 }
5727 // This synthesizes and inserts the block "impl" struct, invoke function,
5728 // and any copy/dispose helper functions.
5729 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005730 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005731 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005732 }
5733 break;
5734 }
5735 case Decl::ObjCMethod: {
5736 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5737 if (CompoundStmt *Body = MD->getCompoundBody()) {
5738 CurMethodDef = MD;
5739 CurrentBody = Body;
5740 Body =
5741 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5742 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005743 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005744 if (PropParentMap) {
5745 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005746 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005747 }
5748 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005749 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005750 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005751 }
5752 break;
5753 }
5754 case Decl::ObjCImplementation: {
5755 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5756 ClassImplementation.push_back(CI);
5757 break;
5758 }
5759 case Decl::ObjCCategoryImpl: {
5760 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5761 CategoryImplementation.push_back(CI);
5762 break;
5763 }
5764 case Decl::Var: {
5765 VarDecl *VD = cast<VarDecl>(D);
5766 RewriteObjCQualifiedInterfaceTypes(VD);
5767 if (isTopLevelBlockPointerType(VD->getType()))
5768 RewriteBlockPointerDecl(VD);
5769 else if (VD->getType()->isFunctionPointerType()) {
5770 CheckFunctionPointerDecl(VD->getType(), VD);
5771 if (VD->getInit()) {
5772 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5773 RewriteCastExpr(CE);
5774 }
5775 }
5776 } else if (VD->getType()->isRecordType()) {
5777 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5778 if (RD->isCompleteDefinition())
5779 RewriteRecordBody(RD);
5780 }
5781 if (VD->getInit()) {
5782 GlobalVarDecl = VD;
5783 CurrentBody = VD->getInit();
5784 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005785 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005786 if (PropParentMap) {
5787 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005788 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005789 }
5790 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005791 GlobalVarDecl = nullptr;
5792
Fariborz Jahanian11671902012-02-07 17:11:38 +00005793 // This is needed for blocks.
5794 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5795 RewriteCastExpr(CE);
5796 }
5797 }
5798 break;
5799 }
5800 case Decl::TypeAlias:
5801 case Decl::Typedef: {
5802 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5803 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5804 RewriteBlockPointerDecl(TD);
5805 else if (TD->getUnderlyingType()->isFunctionPointerType())
5806 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005807 else
5808 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005809 }
5810 break;
5811 }
5812 case Decl::CXXRecord:
5813 case Decl::Record: {
5814 RecordDecl *RD = cast<RecordDecl>(D);
5815 if (RD->isCompleteDefinition())
5816 RewriteRecordBody(RD);
5817 break;
5818 }
5819 default:
5820 break;
5821 }
5822 // Nothing yet.
5823}
5824
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005825/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5826/// protocol reference symbols in the for of:
5827/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5828static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5829 ObjCProtocolDecl *PDecl,
5830 std::string &Result) {
5831 // Also output .objc_protorefs$B section and its meta-data.
5832 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005833 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005834 Result += "struct _protocol_t *";
5835 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5836 Result += PDecl->getNameAsString();
5837 Result += " = &";
5838 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5839 Result += ";\n";
5840}
5841
Fariborz Jahanian11671902012-02-07 17:11:38 +00005842void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5843 if (Diags.hasErrorOccurred())
5844 return;
5845
5846 RewriteInclude();
5847
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005848 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005849 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005850 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005851 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005852 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5853 HandleTopLevelSingleDecl(FDecl);
5854 }
5855
Fariborz Jahanian11671902012-02-07 17:11:38 +00005856 // Here's a great place to add any extra declarations that may be needed.
5857 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005858 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5859 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5860 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005861 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005862
5863 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005864
5865 if (ClassImplementation.size() || CategoryImplementation.size())
5866 RewriteImplementations();
5867
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005868 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5869 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5870 // Write struct declaration for the class matching its ivar declarations.
5871 // Note that for modern abi, this is postponed until the end of TU
5872 // because class extensions and the implementation might declare their own
5873 // private ivars.
5874 RewriteInterfaceDecl(CDecl);
5875 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005876
Fariborz Jahanian11671902012-02-07 17:11:38 +00005877 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5878 // we are done.
5879 if (const RewriteBuffer *RewriteBuf =
5880 Rewrite.getRewriteBufferFor(MainFileID)) {
5881 //printf("Changed:\n");
5882 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5883 } else {
5884 llvm::errs() << "No changes\n";
5885 }
5886
5887 if (ClassImplementation.size() || CategoryImplementation.size() ||
5888 ProtocolExprDecls.size()) {
5889 // Rewrite Objective-c meta data*
5890 std::string ResultStr;
5891 RewriteMetaDataIntoBuffer(ResultStr);
5892 // Emit metadata.
5893 *OutFile << ResultStr;
5894 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005895 // Emit ImageInfo;
5896 {
5897 std::string ResultStr;
5898 WriteImageInfo(ResultStr);
5899 *OutFile << ResultStr;
5900 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005901 OutFile->flush();
5902}
5903
5904void RewriteModernObjC::Initialize(ASTContext &context) {
5905 InitializeCommon(context);
5906
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005907 Preamble += "#ifndef __OBJC2__\n";
5908 Preamble += "#define __OBJC2__\n";
5909 Preamble += "#endif\n";
5910
Fariborz Jahanian11671902012-02-07 17:11:38 +00005911 // declaring objc_selector outside the parameter list removes a silly
5912 // scope related warning...
5913 if (IsHeader)
5914 Preamble = "#pragma once\n";
5915 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005916 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5917 Preamble += "\n\tstruct objc_object *superClass; ";
5918 // Add a constructor for creating temporary objects.
5919 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5920 Preamble += ": object(o), superClass(s) {} ";
5921 Preamble += "\n};\n";
5922
Fariborz Jahanian11671902012-02-07 17:11:38 +00005923 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005924 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005925 // These are currently generated.
5926 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005927 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005928 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005929 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5930 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005931 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005932 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005933 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5934 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005935 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00005936
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005937 // These need be generated for performance. Currently they are not,
5938 // using API calls instead.
5939 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5940 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5941 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5942
Fariborz Jahanian11671902012-02-07 17:11:38 +00005943 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005944 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5945 Preamble += "typedef struct objc_object Protocol;\n";
5946 Preamble += "#define _REWRITER_typedef_Protocol\n";
5947 Preamble += "#endif\n";
5948 if (LangOpts.MicrosoftExt) {
5949 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5950 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005951 }
5952 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005953 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005954
5955 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5956 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5957 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5958 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5959 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5960
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005961 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005962 Preamble += "(const char *);\n";
5963 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5964 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005965 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005966 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005967 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005968 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005969 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5970 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005971 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005972 Preamble += "#ifdef _WIN64\n";
5973 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5974 Preamble += "#else\n";
5975 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5976 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005977 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5978 Preamble += "struct __objcFastEnumerationState {\n\t";
5979 Preamble += "unsigned long state;\n\t";
5980 Preamble += "void **itemsPtr;\n\t";
5981 Preamble += "unsigned long *mutationsPtr;\n\t";
5982 Preamble += "unsigned long extra[5];\n};\n";
5983 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5984 Preamble += "#define __FASTENUMERATIONSTATE\n";
5985 Preamble += "#endif\n";
5986 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5987 Preamble += "struct __NSConstantStringImpl {\n";
5988 Preamble += " int *isa;\n";
5989 Preamble += " int flags;\n";
5990 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005991 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005992 Preamble += " long long length;\n";
5993 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005994 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005995 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005996 Preamble += "};\n";
5997 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5998 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5999 Preamble += "#else\n";
6000 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6001 Preamble += "#endif\n";
6002 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6003 Preamble += "#endif\n";
6004 // Blocks preamble.
6005 Preamble += "#ifndef BLOCK_IMPL\n";
6006 Preamble += "#define BLOCK_IMPL\n";
6007 Preamble += "struct __block_impl {\n";
6008 Preamble += " void *isa;\n";
6009 Preamble += " int Flags;\n";
6010 Preamble += " int Reserved;\n";
6011 Preamble += " void *FuncPtr;\n";
6012 Preamble += "};\n";
6013 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6014 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6015 Preamble += "extern \"C\" __declspec(dllexport) "
6016 "void _Block_object_assign(void *, const void *, const int);\n";
6017 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6018 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6019 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6020 Preamble += "#else\n";
6021 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6022 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6023 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6024 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6025 Preamble += "#endif\n";
6026 Preamble += "#endif\n";
6027 if (LangOpts.MicrosoftExt) {
6028 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6029 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6030 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6031 Preamble += "#define __attribute__(X)\n";
6032 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006033 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006034 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006035 Preamble += "#endif\n";
6036 Preamble += "#ifndef __block\n";
6037 Preamble += "#define __block\n";
6038 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006039 }
6040 else {
6041 Preamble += "#define __block\n";
6042 Preamble += "#define __weak\n";
6043 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006044
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006045 // Declarations required for modern objective-c array and dictionary literals.
6046 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006047 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006048 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006049 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006050 Preamble += "\tva_list marker;\n";
6051 Preamble += "\tva_start(marker, count);\n";
6052 Preamble += "\tarr = new void *[count];\n";
6053 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6054 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6055 Preamble += "\tva_end( marker );\n";
6056 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006057 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006058 Preamble += "\tdelete[] arr;\n";
6059 Preamble += " }\n";
6060 Preamble += "};\n";
6061
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006062 // Declaration required for implementation of @autoreleasepool statement.
6063 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6064 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6065 Preamble += "struct __AtAutoreleasePool {\n";
6066 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6067 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6068 Preamble += " void * atautoreleasepoolobj;\n";
6069 Preamble += "};\n";
6070
Fariborz Jahanian11671902012-02-07 17:11:38 +00006071 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6072 // as this avoids warning in any 64bit/32bit compilation model.
6073 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6074}
6075
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00006076/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian11671902012-02-07 17:11:38 +00006077/// ivar offset.
6078void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6079 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006080 Result += "__OFFSETOFIVAR__(struct ";
6081 Result += ivar->getContainingInterface()->getNameAsString();
6082 if (LangOpts.MicrosoftExt)
6083 Result += "_IMPL";
6084 Result += ", ";
6085 if (ivar->isBitField())
6086 ObjCIvarBitfieldGroupDecl(ivar, Result);
6087 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006088 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006089 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006090}
6091
6092/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6093/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006094/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006095/// char *attributes;
6096/// }
6097
6098/// struct _prop_list_t {
6099/// uint32_t entsize; // sizeof(struct _prop_t)
6100/// uint32_t count_of_properties;
6101/// struct _prop_t prop_list[count_of_properties];
6102/// }
6103
6104/// struct _protocol_t;
6105
6106/// struct _protocol_list_t {
6107/// long protocol_count; // Note, this is 32/64 bit
6108/// struct _protocol_t * protocol_list[protocol_count];
6109/// }
6110
6111/// struct _objc_method {
6112/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006113/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006114/// char *_imp;
6115/// }
6116
6117/// struct _method_list_t {
6118/// uint32_t entsize; // sizeof(struct _objc_method)
6119/// uint32_t method_count;
6120/// struct _objc_method method_list[method_count];
6121/// }
6122
6123/// struct _protocol_t {
6124/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006125/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006126/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006127/// const struct method_list_t *instance_methods;
6128/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006129/// const struct method_list_t *optionalInstanceMethods;
6130/// const struct method_list_t *optionalClassMethods;
6131/// const struct _prop_list_t * properties;
6132/// const uint32_t size; // sizeof(struct _protocol_t)
6133/// const uint32_t flags; // = 0
6134/// const char ** extendedMethodTypes;
6135/// }
6136
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006137/// struct _ivar_t {
6138/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006139/// const char *name;
6140/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006141/// uint32_t alignment;
6142/// uint32_t size;
6143/// }
6144
6145/// struct _ivar_list_t {
6146/// uint32 entsize; // sizeof(struct _ivar_t)
6147/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006148/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006149/// }
6150
6151/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006152/// uint32_t flags;
6153/// uint32_t instanceStart;
6154/// uint32_t instanceSize;
6155/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006156/// const uint8_t *ivarLayout;
6157/// const char *name;
6158/// const struct _method_list_t *baseMethods;
6159/// const struct _protocol_list_t *baseProtocols;
6160/// const struct _ivar_list_t *ivars;
6161/// const uint8_t *weakIvarLayout;
6162/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006163/// }
6164
6165/// struct _class_t {
6166/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006167/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006168/// void *cache;
6169/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006170/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006171/// }
6172
6173/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006174/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006175/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006176/// const struct _method_list_t *instance_methods;
6177/// const struct _method_list_t *class_methods;
6178/// const struct _protocol_list_t *protocols;
6179/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006180/// }
6181
6182/// MessageRefTy - LLVM for:
6183/// struct _message_ref_t {
6184/// IMP messenger;
6185/// SEL name;
6186/// };
6187
6188/// SuperMessageRefTy - LLVM for:
6189/// struct _super_message_ref_t {
6190/// SUPER_IMP messenger;
6191/// SEL name;
6192/// };
6193
Fariborz Jahanian45489622012-03-14 18:09:23 +00006194static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006195 static bool meta_data_declared = false;
6196 if (meta_data_declared)
6197 return;
6198
6199 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006200 Result += "\tconst char *name;\n";
6201 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 Result += "};\n";
6203
6204 Result += "\nstruct _protocol_t;\n";
6205
Fariborz Jahanian11671902012-02-07 17:11:38 +00006206 Result += "\nstruct _objc_method {\n";
6207 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006208 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006209 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006210 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006211
6212 Result += "\nstruct _protocol_t {\n";
6213 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006214 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006215 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006216 Result += "\tconst struct method_list_t *instance_methods;\n";
6217 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006218 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6219 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6220 Result += "\tconst struct _prop_list_t * properties;\n";
6221 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6222 Result += "\tconst unsigned int flags; // = 0\n";
6223 Result += "\tconst char ** extendedMethodTypes;\n";
6224 Result += "};\n";
6225
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006226 Result += "\nstruct _ivar_t {\n";
6227 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006228 Result += "\tconst char *name;\n";
6229 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006230 Result += "\tunsigned int alignment;\n";
6231 Result += "\tunsigned int size;\n";
6232 Result += "};\n";
6233
6234 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006235 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006236 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006237 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006238 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6239 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006240 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006241 Result += "\tconst unsigned char *ivarLayout;\n";
6242 Result += "\tconst char *name;\n";
6243 Result += "\tconst struct _method_list_t *baseMethods;\n";
6244 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6245 Result += "\tconst struct _ivar_list_t *ivars;\n";
6246 Result += "\tconst unsigned char *weakIvarLayout;\n";
6247 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006248 Result += "};\n";
6249
6250 Result += "\nstruct _class_t {\n";
6251 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006252 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006253 Result += "\tvoid *cache;\n";
6254 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006255 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006256 Result += "};\n";
6257
6258 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006259 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006260 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006261 Result += "\tconst struct _method_list_t *instance_methods;\n";
6262 Result += "\tconst struct _method_list_t *class_methods;\n";
6263 Result += "\tconst struct _protocol_list_t *protocols;\n";
6264 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006265 Result += "};\n";
6266
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006267 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006268 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006269 meta_data_declared = true;
6270}
6271
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006272static void Write_protocol_list_t_TypeDecl(std::string &Result,
6273 long super_protocol_count) {
6274 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6275 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6276 Result += "\tstruct _protocol_t *super_protocols[";
6277 Result += utostr(super_protocol_count); Result += "];\n";
6278 Result += "}";
6279}
6280
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006281static void Write_method_list_t_TypeDecl(std::string &Result,
6282 unsigned int method_count) {
6283 Result += "struct /*_method_list_t*/"; Result += " {\n";
6284 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6285 Result += "\tunsigned int method_count;\n";
6286 Result += "\tstruct _objc_method method_list[";
6287 Result += utostr(method_count); Result += "];\n";
6288 Result += "}";
6289}
6290
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006291static void Write__prop_list_t_TypeDecl(std::string &Result,
6292 unsigned int property_count) {
6293 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6294 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6295 Result += "\tunsigned int count_of_properties;\n";
6296 Result += "\tstruct _prop_t prop_list[";
6297 Result += utostr(property_count); Result += "];\n";
6298 Result += "}";
6299}
6300
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006301static void Write__ivar_list_t_TypeDecl(std::string &Result,
6302 unsigned int ivar_count) {
6303 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6304 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6305 Result += "\tunsigned int count;\n";
6306 Result += "\tstruct _ivar_t ivar_list[";
6307 Result += utostr(ivar_count); Result += "];\n";
6308 Result += "}";
6309}
6310
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006311static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6312 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6313 StringRef VarName,
6314 StringRef ProtocolName) {
6315 if (SuperProtocols.size() > 0) {
6316 Result += "\nstatic ";
6317 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6318 Result += " "; Result += VarName;
6319 Result += ProtocolName;
6320 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6321 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6322 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6323 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6324 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6325 Result += SuperPD->getNameAsString();
6326 if (i == e-1)
6327 Result += "\n};\n";
6328 else
6329 Result += ",\n";
6330 }
6331 }
6332}
6333
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006334static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6335 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006336 ArrayRef<ObjCMethodDecl *> Methods,
6337 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006338 StringRef TopLevelDeclName,
6339 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006340 if (Methods.size() > 0) {
6341 Result += "\nstatic ";
6342 Write_method_list_t_TypeDecl(Result, Methods.size());
6343 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006344 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006345 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6346 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6347 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6348 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6349 ObjCMethodDecl *MD = Methods[i];
6350 if (i == 0)
6351 Result += "\t{{(struct objc_selector *)\"";
6352 else
6353 Result += "\t{(struct objc_selector *)\"";
6354 Result += (MD)->getSelector().getAsString(); Result += "\"";
6355 Result += ", ";
John McCall843dfcc2016-11-29 21:57:00 +00006356 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006357 Result += "\""; Result += MethodTypeString; Result += "\"";
6358 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006359 if (!MethodImpl)
6360 Result += "0";
6361 else {
6362 Result += "(void *)";
6363 Result += RewriteObj.MethodInternalNames[MD];
6364 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006365 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006366 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006367 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006368 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006369 }
6370 Result += "};\n";
6371 }
6372}
6373
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006374static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006375 ASTContext *Context, std::string &Result,
6376 ArrayRef<ObjCPropertyDecl *> Properties,
6377 const Decl *Container,
6378 StringRef VarName,
6379 StringRef ProtocolName) {
6380 if (Properties.size() > 0) {
6381 Result += "\nstatic ";
6382 Write__prop_list_t_TypeDecl(Result, Properties.size());
6383 Result += " "; Result += VarName;
6384 Result += ProtocolName;
6385 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6386 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6387 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6388 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6389 ObjCPropertyDecl *PropDecl = Properties[i];
6390 if (i == 0)
6391 Result += "\t{{\"";
6392 else
6393 Result += "\t{\"";
6394 Result += PropDecl->getName(); Result += "\",";
John McCall843dfcc2016-11-29 21:57:00 +00006395 std::string PropertyTypeString =
6396 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6397 std::string QuotePropertyTypeString;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006398 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6399 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6400 if (i == e-1)
6401 Result += "}}\n";
6402 else
6403 Result += "},\n";
6404 }
6405 Result += "};\n";
6406 }
6407}
6408
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006409// Metadata flags
6410enum MetaDataDlags {
6411 CLS = 0x0,
6412 CLS_META = 0x1,
6413 CLS_ROOT = 0x2,
6414 OBJC2_CLS_HIDDEN = 0x10,
6415 CLS_EXCEPTION = 0x20,
6416
6417 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6418 CLS_HAS_IVAR_RELEASER = 0x40,
6419 /// class was compiled with -fobjc-arr
6420 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6421};
6422
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006423static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6424 unsigned int flags,
6425 const std::string &InstanceStart,
6426 const std::string &InstanceSize,
6427 ArrayRef<ObjCMethodDecl *>baseMethods,
6428 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6429 ArrayRef<ObjCIvarDecl *>ivars,
6430 ArrayRef<ObjCPropertyDecl *>Properties,
6431 StringRef VarName,
6432 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006433 Result += "\nstatic struct _class_ro_t ";
6434 Result += VarName; Result += ClassName;
6435 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6436 Result += "\t";
6437 Result += llvm::utostr(flags); Result += ", ";
6438 Result += InstanceStart; Result += ", ";
6439 Result += InstanceSize; Result += ", \n";
6440 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006441 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6442 if (Triple.getArch() == llvm::Triple::x86_64)
6443 // uint32_t const reserved; // only when building for 64bit targets
6444 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006445 // const uint8_t * const ivarLayout;
6446 Result += "0, \n\t";
6447 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006448 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006449 if (baseMethods.size() > 0) {
6450 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006451 if (metaclass)
6452 Result += "_OBJC_$_CLASS_METHODS_";
6453 else
6454 Result += "_OBJC_$_INSTANCE_METHODS_";
6455 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006456 Result += ",\n\t";
6457 }
6458 else
6459 Result += "0, \n\t";
6460
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006461 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006462 Result += "(const struct _objc_protocol_list *)&";
6463 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6464 Result += ",\n\t";
6465 }
6466 else
6467 Result += "0, \n\t";
6468
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006469 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006470 Result += "(const struct _ivar_list_t *)&";
6471 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6472 Result += ",\n\t";
6473 }
6474 else
6475 Result += "0, \n\t";
6476
6477 // weakIvarLayout
6478 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006479 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006480 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006481 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006482 Result += ",\n";
6483 }
6484 else
6485 Result += "0, \n";
6486
6487 Result += "};\n";
6488}
6489
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006490static void Write_class_t(ASTContext *Context, std::string &Result,
6491 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006492 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6493 bool rootClass = (!CDecl->getSuperClass());
6494 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006495
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006496 if (!rootClass) {
6497 // Find the Root class
6498 RootClass = CDecl->getSuperClass();
6499 while (RootClass->getSuperClass()) {
6500 RootClass = RootClass->getSuperClass();
6501 }
6502 }
6503
6504 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006505 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006506 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006507 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006508 if (CDecl->getImplementation())
6509 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006510 else
6511 Result += "__declspec(dllimport) ";
6512
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006513 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006514 Result += CDecl->getNameAsString();
6515 Result += ";\n";
6516 }
6517 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006518 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006519 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006520 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006521 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006522 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006523 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006524 else
6525 Result += "__declspec(dllimport) ";
6526
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006527 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006528 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006529 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006530 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006531
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006532 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006533 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006534 if (RootClass->getImplementation())
6535 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006536 else
6537 Result += "__declspec(dllimport) ";
6538
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006539 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006540 Result += VarName;
6541 Result += RootClass->getNameAsString();
6542 Result += ";\n";
6543 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006544 }
6545
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006546 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6547 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006548 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6549 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006550 if (metaclass) {
6551 if (!rootClass) {
6552 Result += "0, // &"; Result += VarName;
6553 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006554 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006555 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006556 Result += CDecl->getSuperClass()->getNameAsString();
6557 Result += ",\n\t";
6558 }
6559 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006560 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006561 Result += CDecl->getNameAsString();
6562 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006563 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006564 Result += ",\n\t";
6565 }
6566 }
6567 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006568 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006569 Result += CDecl->getNameAsString();
6570 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006571 if (!rootClass) {
6572 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006573 Result += CDecl->getSuperClass()->getNameAsString();
6574 Result += ",\n\t";
6575 }
6576 else
6577 Result += "0,\n\t";
6578 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006579 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6580 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6581 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006582 Result += "&_OBJC_METACLASS_RO_$_";
6583 else
6584 Result += "&_OBJC_CLASS_RO_$_";
6585 Result += CDecl->getNameAsString();
6586 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006587
6588 // Add static function to initialize some of the meta-data fields.
6589 // avoid doing it twice.
6590 if (metaclass)
6591 return;
6592
6593 const ObjCInterfaceDecl *SuperClass =
6594 rootClass ? CDecl : CDecl->getSuperClass();
6595
6596 Result += "static void OBJC_CLASS_SETUP_$_";
6597 Result += CDecl->getNameAsString();
6598 Result += "(void ) {\n";
6599 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6600 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006601 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006602
6603 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006604 Result += ".superclass = ";
6605 if (rootClass)
6606 Result += "&OBJC_CLASS_$_";
6607 else
6608 Result += "&OBJC_METACLASS_$_";
6609
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006610 Result += SuperClass->getNameAsString(); Result += ";\n";
6611
6612 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6613 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6614
6615 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6616 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6617 Result += CDecl->getNameAsString(); Result += ";\n";
6618
6619 if (!rootClass) {
6620 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6621 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6622 Result += SuperClass->getNameAsString(); Result += ";\n";
6623 }
6624
6625 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6626 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6627 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006628}
6629
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006630static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6631 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006632 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006633 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006634 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6635 ArrayRef<ObjCMethodDecl *> ClassMethods,
6636 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6637 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006638 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006639 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006640 // must declare an extern class object in case this class is not implemented
6641 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006642 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006643 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006644 if (ClassDecl->getImplementation())
6645 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006646 else
6647 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006648
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006649 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006650 Result += "OBJC_CLASS_$_"; Result += ClassName;
6651 Result += ";\n";
6652
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006653 Result += "\nstatic struct _category_t ";
6654 Result += "_OBJC_$_CATEGORY_";
6655 Result += ClassName; Result += "_$_"; Result += CatName;
6656 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6657 Result += "{\n";
6658 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006659 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006660 Result += ",\n";
6661 if (InstanceMethods.size() > 0) {
6662 Result += "\t(const struct _method_list_t *)&";
6663 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6664 Result += ClassName; Result += "_$_"; Result += CatName;
6665 Result += ",\n";
6666 }
6667 else
6668 Result += "\t0,\n";
6669
6670 if (ClassMethods.size() > 0) {
6671 Result += "\t(const struct _method_list_t *)&";
6672 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6673 Result += ClassName; Result += "_$_"; Result += CatName;
6674 Result += ",\n";
6675 }
6676 else
6677 Result += "\t0,\n";
6678
6679 if (RefedProtocols.size() > 0) {
6680 Result += "\t(const struct _protocol_list_t *)&";
6681 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6682 Result += ClassName; Result += "_$_"; Result += CatName;
6683 Result += ",\n";
6684 }
6685 else
6686 Result += "\t0,\n";
6687
6688 if (ClassProperties.size() > 0) {
6689 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6690 Result += ClassName; Result += "_$_"; Result += CatName;
6691 Result += ",\n";
6692 }
6693 else
6694 Result += "\t0,\n";
6695
6696 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006697
6698 // Add static function to initialize the class pointer in the category structure.
6699 Result += "static void OBJC_CATEGORY_SETUP_$_";
6700 Result += ClassDecl->getNameAsString();
6701 Result += "_$_";
6702 Result += CatName;
6703 Result += "(void ) {\n";
6704 Result += "\t_OBJC_$_CATEGORY_";
6705 Result += ClassDecl->getNameAsString();
6706 Result += "_$_";
6707 Result += CatName;
6708 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6709 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006710}
6711
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006712static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6713 ASTContext *Context, std::string &Result,
6714 ArrayRef<ObjCMethodDecl *> Methods,
6715 StringRef VarName,
6716 StringRef ProtocolName) {
6717 if (Methods.size() == 0)
6718 return;
6719
6720 Result += "\nstatic const char *";
6721 Result += VarName; Result += ProtocolName;
6722 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6723 Result += "{\n";
6724 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6725 ObjCMethodDecl *MD = Methods[i];
John McCall843dfcc2016-11-29 21:57:00 +00006726 std::string MethodTypeString =
6727 Context->getObjCEncodingForMethodDecl(MD, true);
6728 std::string QuoteMethodTypeString;
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006729 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6730 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6731 if (i == e-1)
6732 Result += "\n};\n";
6733 else {
6734 Result += ",\n";
6735 }
6736 }
6737}
6738
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006739static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6740 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006741 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006742 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006743 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006744 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6745 // this is what happens:
6746 /**
6747 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6748 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6749 Class->getVisibility() == HiddenVisibility)
6750 Visibility shoud be: HiddenVisibility;
6751 else
6752 Visibility shoud be: DefaultVisibility;
6753 */
6754
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006755 Result += "\n";
6756 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6757 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006758 if (Context->getLangOpts().MicrosoftExt)
6759 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6760
6761 if (!Context->getLangOpts().MicrosoftExt ||
6762 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006763 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006764 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006765 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006766 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006767 if (Ivars[i]->isBitField())
6768 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6769 else
6770 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006771 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6772 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006773 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6774 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006775 if (Ivars[i]->isBitField()) {
6776 // skip over rest of the ivar bitfields.
6777 SKIP_BITFIELDS(i , e, Ivars);
6778 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006779 }
6780}
6781
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006782static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6783 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006784 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006785 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006786 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006787 if (OriginalIvars.size() > 0) {
6788 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6789 SmallVector<ObjCIvarDecl *, 8> Ivars;
6790 // strip off all but the first ivar bitfield from each group of ivars.
6791 // Such ivars in the ivar list table will be replaced by their grouping struct
6792 // 'ivar'.
6793 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6794 if (OriginalIvars[i]->isBitField()) {
6795 Ivars.push_back(OriginalIvars[i]);
6796 // skip over rest of the ivar bitfields.
6797 SKIP_BITFIELDS(i , e, OriginalIvars);
6798 }
6799 else
6800 Ivars.push_back(OriginalIvars[i]);
6801 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006802
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006803 Result += "\nstatic ";
6804 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6805 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006806 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006807 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6808 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6809 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6810 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6811 ObjCIvarDecl *IvarDecl = Ivars[i];
6812 if (i == 0)
6813 Result += "\t{{";
6814 else
6815 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006816 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006817 if (Ivars[i]->isBitField())
6818 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6819 else
6820 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006821 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006822
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006823 Result += "\"";
6824 if (Ivars[i]->isBitField())
6825 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6826 else
6827 Result += IvarDecl->getName();
6828 Result += "\", ";
6829
6830 QualType IVQT = IvarDecl->getType();
6831 if (IvarDecl->isBitField())
6832 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6833
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006834 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006835 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006836 IvarDecl);
6837 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6838 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6839
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006840 // FIXME. this alignment represents the host alignment and need be changed to
6841 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006842 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006843 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006844 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006845 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006846 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006847 if (i == e-1)
6848 Result += "}}\n";
6849 else
6850 Result += "},\n";
6851 }
6852 Result += "};\n";
6853 }
6854}
6855
Fariborz Jahanian11671902012-02-07 17:11:38 +00006856/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006857void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6858 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006859
Fariborz Jahanian11671902012-02-07 17:11:38 +00006860 // Do not synthesize the protocol more than once.
6861 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6862 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006863 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006864
6865 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6866 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006867 // Must write out all protocol definitions in current qualifier list,
6868 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006869 for (auto *I : PDecl->protocols())
6870 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006871
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006872 // Construct method lists.
6873 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6874 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006875 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006876 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6877 OptInstanceMethods.push_back(MD);
6878 } else {
6879 InstanceMethods.push_back(MD);
6880 }
6881 }
6882
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006883 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006884 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6885 OptClassMethods.push_back(MD);
6886 } else {
6887 ClassMethods.push_back(MD);
6888 }
6889 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006890 std::vector<ObjCMethodDecl *> AllMethods;
6891 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6892 AllMethods.push_back(InstanceMethods[i]);
6893 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6894 AllMethods.push_back(ClassMethods[i]);
6895 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6896 AllMethods.push_back(OptInstanceMethods[i]);
6897 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6898 AllMethods.push_back(OptClassMethods[i]);
6899
6900 Write__extendedMethodTypes_initializer(*this, Context, Result,
6901 AllMethods,
6902 "_OBJC_PROTOCOL_METHOD_TYPES_",
6903 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006904 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006905 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006906 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6907 "_OBJC_PROTOCOL_REFS_",
6908 PDecl->getNameAsString());
6909
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006910 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006911 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006912 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006913
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006914 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006915 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006916 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006917
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006918 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006919 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006920 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006921
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006922 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006923 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006924 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006925
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006926 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006927 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6928 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006929 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006930 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006931 "_OBJC_PROTOCOL_PROPERTIES_",
6932 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006933
Fariborz Jahanian48985802012-02-08 00:50:52 +00006934 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006935 Result += "\n";
6936 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006937 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006938 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006939 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006940 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006941 Result += "\t0,\n"; // id is; is null
6942 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006943 if (SuperProtocols.size() > 0) {
6944 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6945 Result += PDecl->getNameAsString(); Result += ",\n";
6946 }
6947 else
6948 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006949 if (InstanceMethods.size() > 0) {
6950 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6951 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006952 }
6953 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006954 Result += "\t0,\n";
6955
6956 if (ClassMethods.size() > 0) {
6957 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6958 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006959 }
6960 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006961 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006962
Fariborz Jahanian48985802012-02-08 00:50:52 +00006963 if (OptInstanceMethods.size() > 0) {
6964 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6965 Result += PDecl->getNameAsString(); Result += ",\n";
6966 }
6967 else
6968 Result += "\t0,\n";
6969
6970 if (OptClassMethods.size() > 0) {
6971 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6972 Result += PDecl->getNameAsString(); Result += ",\n";
6973 }
6974 else
6975 Result += "\t0,\n";
6976
6977 if (ProtocolProperties.size() > 0) {
6978 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6979 Result += PDecl->getNameAsString(); Result += ",\n";
6980 }
6981 else
6982 Result += "\t0,\n";
6983
6984 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6985 Result += "\t0,\n";
6986
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006987 if (AllMethods.size() > 0) {
6988 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6989 Result += PDecl->getNameAsString();
6990 Result += "\n};\n";
6991 }
6992 else
6993 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006994
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006995 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006996 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006997 Result += "struct _protocol_t *";
6998 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6999 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7000 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007001
Fariborz Jahanian11671902012-02-07 17:11:38 +00007002 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00007003 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007004 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00007005}
7006
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007007/// hasObjCExceptionAttribute - Return true if this class or any super
7008/// class has the __objc_exception__ attribute.
7009/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7010static bool hasObjCExceptionAttribute(ASTContext &Context,
7011 const ObjCInterfaceDecl *OID) {
7012 if (OID->hasAttr<ObjCExceptionAttr>())
7013 return true;
7014 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7015 return hasObjCExceptionAttribute(Context, Super);
7016 return false;
7017}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007018
Fariborz Jahanian11671902012-02-07 17:11:38 +00007019void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7020 std::string &Result) {
7021 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7022
7023 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007024 if (CDecl->isImplicitInterfaceDecl())
7025 assert(false &&
7026 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007027
Fariborz Jahanian45489622012-03-14 18:09:23 +00007028 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007029 SmallVector<ObjCIvarDecl *, 8> IVars;
7030
7031 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7032 IVD; IVD = IVD->getNextIvar()) {
7033 // Ignore unnamed bit-fields.
7034 if (!IVD->getDeclName())
7035 continue;
7036 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007037 }
7038
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007039 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007040 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007041 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042
7043 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007044 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007045
7046 // If any of our property implementations have associated getters or
7047 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007048 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007049 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007050 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007051 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007052 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007053 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007054 if (!PD)
7055 continue;
7056 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007057 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007058 InstanceMethods.push_back(Getter);
7059 if (PD->isReadOnly())
7060 continue;
7061 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007062 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007063 InstanceMethods.push_back(Setter);
7064 }
7065
7066 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7067 "_OBJC_$_INSTANCE_METHODS_",
7068 IDecl->getNameAsString(), true);
7069
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007070 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007071
7072 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7073 "_OBJC_$_CLASS_METHODS_",
7074 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007075
7076 // Protocols referenced in class declaration?
7077 // Protocol's super protocol list
7078 std::vector<ObjCProtocolDecl *> RefedProtocols;
7079 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7080 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7081 E = Protocols.end();
7082 I != E; ++I) {
7083 RefedProtocols.push_back(*I);
7084 // Must write out all protocol definitions in current qualifier list,
7085 // and in their nested qualifiers before writing out current definition.
7086 RewriteObjCProtocolMetaData(*I, Result);
7087 }
7088
7089 Write_protocol_list_initializer(Context, Result,
7090 RefedProtocols,
7091 "_OBJC_CLASS_PROTOCOLS_$_",
7092 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007093
7094 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007095 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7096 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007097 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007098 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007099 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007100 CDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007101
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007102 // Data for initializing _class_ro_t metaclass meta-data
7103 uint32_t flags = CLS_META;
7104 std::string InstanceSize;
7105 std::string InstanceStart;
7106
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007107 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7108 if (classIsHidden)
7109 flags |= OBJC2_CLS_HIDDEN;
7110
7111 if (!CDecl->getSuperClass())
7112 // class is root
7113 flags |= CLS_ROOT;
7114 InstanceSize = "sizeof(struct _class_t)";
7115 InstanceStart = InstanceSize;
7116 Write__class_ro_t_initializer(Context, Result, flags,
7117 InstanceStart, InstanceSize,
7118 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007119 nullptr,
7120 nullptr,
7121 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007122 "_OBJC_METACLASS_RO_$_",
7123 CDecl->getNameAsString());
7124
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007125 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007126 flags = CLS;
7127 if (classIsHidden)
7128 flags |= OBJC2_CLS_HIDDEN;
7129
7130 if (hasObjCExceptionAttribute(*Context, CDecl))
7131 flags |= CLS_EXCEPTION;
7132
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007133 if (!CDecl->getSuperClass())
7134 // class is root
7135 flags |= CLS_ROOT;
7136
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007137 InstanceSize.clear();
7138 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007139 if (!ObjCSynthesizedStructs.count(CDecl)) {
7140 InstanceSize = "0";
7141 InstanceStart = "0";
7142 }
7143 else {
7144 InstanceSize = "sizeof(struct ";
7145 InstanceSize += CDecl->getNameAsString();
7146 InstanceSize += "_IMPL)";
7147
7148 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7149 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007150 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007151 }
7152 else
7153 InstanceStart = InstanceSize;
7154 }
7155 Write__class_ro_t_initializer(Context, Result, flags,
7156 InstanceStart, InstanceSize,
7157 InstanceMethods,
7158 RefedProtocols,
7159 IVars,
7160 ClassProperties,
7161 "_OBJC_CLASS_RO_$_",
7162 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007163
7164 Write_class_t(Context, Result,
7165 "OBJC_METACLASS_$_",
7166 CDecl, /*metaclass*/true);
7167
7168 Write_class_t(Context, Result,
7169 "OBJC_CLASS_$_",
7170 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007171
7172 if (ImplementationIsNonLazy(IDecl))
7173 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007174}
7175
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007176void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7177 int ClsDefCount = ClassImplementation.size();
7178 if (!ClsDefCount)
7179 return;
7180 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7181 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7182 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7183 for (int i = 0; i < ClsDefCount; i++) {
7184 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7185 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7186 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7187 Result += CDecl->getName(); Result += ",\n";
7188 }
7189 Result += "};\n";
7190}
7191
Fariborz Jahanian11671902012-02-07 17:11:38 +00007192void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7193 int ClsDefCount = ClassImplementation.size();
7194 int CatDefCount = CategoryImplementation.size();
7195
7196 // For each implemented class, write out all its meta data.
7197 for (int i = 0; i < ClsDefCount; i++)
7198 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7199
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007200 RewriteClassSetupInitHook(Result);
7201
Fariborz Jahanian11671902012-02-07 17:11:38 +00007202 // For each implemented category, write out all its meta data.
7203 for (int i = 0; i < CatDefCount; i++)
7204 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7205
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007206 RewriteCategorySetupInitHook(Result);
7207
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007208 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007209 if (LangOpts.MicrosoftExt)
7210 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007211 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7212 Result += llvm::utostr(ClsDefCount); Result += "]";
7213 Result +=
7214 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7215 "regular,no_dead_strip\")))= {\n";
7216 for (int i = 0; i < ClsDefCount; i++) {
7217 Result += "\t&OBJC_CLASS_$_";
7218 Result += ClassImplementation[i]->getNameAsString();
7219 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007220 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007221 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007222
7223 if (!DefinedNonLazyClasses.empty()) {
7224 if (LangOpts.MicrosoftExt)
7225 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7226 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7227 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7228 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7229 Result += ",\n";
7230 }
7231 Result += "};\n";
7232 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007233 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007234
7235 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007236 if (LangOpts.MicrosoftExt)
7237 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007238 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7239 Result += llvm::utostr(CatDefCount); Result += "]";
7240 Result +=
7241 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7242 "regular,no_dead_strip\")))= {\n";
7243 for (int i = 0; i < CatDefCount; i++) {
7244 Result += "\t&_OBJC_$_CATEGORY_";
7245 Result +=
7246 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7247 Result += "_$_";
7248 Result += CategoryImplementation[i]->getNameAsString();
7249 Result += ",\n";
7250 }
7251 Result += "};\n";
7252 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007253
7254 if (!DefinedNonLazyCategories.empty()) {
7255 if (LangOpts.MicrosoftExt)
7256 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7257 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7258 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7259 Result += "\t&_OBJC_$_CATEGORY_";
7260 Result +=
7261 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7262 Result += "_$_";
7263 Result += DefinedNonLazyCategories[i]->getNameAsString();
7264 Result += ",\n";
7265 }
7266 Result += "};\n";
7267 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007268}
7269
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007270void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7271 if (LangOpts.MicrosoftExt)
7272 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7273
7274 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7275 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007276 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007277}
7278
Fariborz Jahanian11671902012-02-07 17:11:38 +00007279/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7280/// implementation.
7281void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7282 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007283 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007284 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7285 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007286 ObjCCategoryDecl *CDecl
7287 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007288
7289 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007290 FullCategoryName += "_$_";
7291 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007292
7293 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007294 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007295
7296 // If any of our property implementations have associated getters or
7297 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007298 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007299 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007300 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007301 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007302 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007303 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007304 if (!PD)
7305 continue;
7306 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7307 InstanceMethods.push_back(Getter);
7308 if (PD->isReadOnly())
7309 continue;
7310 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7311 InstanceMethods.push_back(Setter);
7312 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007313
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007314 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7315 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7316 FullCategoryName, true);
7317
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007318 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007319
7320 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7321 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7322 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007323
7324 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007325 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007326 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7327 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007328 // Must write out all protocol definitions in current qualifier list,
7329 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007330 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007331
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007332 Write_protocol_list_initializer(Context, Result,
7333 RefedProtocols,
7334 "_OBJC_CATEGORY_PROTOCOLS_$_",
7335 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007336
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007337 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007338 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7339 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007340 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007341 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007342 "_OBJC_$_PROP_LIST_",
7343 FullCategoryName);
7344
7345 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007346 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007347 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007348 InstanceMethods,
7349 ClassMethods,
7350 RefedProtocols,
7351 ClassProperties);
7352
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007353 // Determine if this category is also "non-lazy".
7354 if (ImplementationIsNonLazy(IDecl))
7355 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007356}
7357
7358void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7359 int CatDefCount = CategoryImplementation.size();
7360 if (!CatDefCount)
7361 return;
7362 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7363 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7364 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7365 for (int i = 0; i < CatDefCount; i++) {
7366 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7367 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7368 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7369 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7370 Result += ClassDecl->getName();
7371 Result += "_$_";
7372 Result += CatDecl->getName();
7373 Result += ",\n";
7374 }
7375 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007376}
7377
7378// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7379/// class methods.
7380template<typename MethodIterator>
7381void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7382 MethodIterator MethodEnd,
7383 bool IsInstanceMethod,
7384 StringRef prefix,
7385 StringRef ClassName,
7386 std::string &Result) {
7387 if (MethodBegin == MethodEnd) return;
7388
7389 if (!objc_impl_method) {
7390 /* struct _objc_method {
7391 SEL _cmd;
7392 char *method_types;
7393 void *_imp;
7394 }
7395 */
7396 Result += "\nstruct _objc_method {\n";
7397 Result += "\tSEL _cmd;\n";
7398 Result += "\tchar *method_types;\n";
7399 Result += "\tvoid *_imp;\n";
7400 Result += "};\n";
7401
7402 objc_impl_method = true;
7403 }
7404
7405 // Build _objc_method_list for class's methods if needed
7406
7407 /* struct {
7408 struct _objc_method_list *next_method;
7409 int method_count;
7410 struct _objc_method method_list[];
7411 }
7412 */
7413 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007414 Result += "\n";
7415 if (LangOpts.MicrosoftExt) {
7416 if (IsInstanceMethod)
7417 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7418 else
7419 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7420 }
7421 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007422 Result += "\tstruct _objc_method_list *next_method;\n";
7423 Result += "\tint method_count;\n";
7424 Result += "\tstruct _objc_method method_list[";
7425 Result += utostr(NumMethods);
7426 Result += "];\n} _OBJC_";
7427 Result += prefix;
7428 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7429 Result += "_METHODS_";
7430 Result += ClassName;
7431 Result += " __attribute__ ((used, section (\"__OBJC, __";
7432 Result += IsInstanceMethod ? "inst" : "cls";
7433 Result += "_meth\")))= ";
7434 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7435
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 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7446 Result += "\t ,{(SEL)\"";
7447 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7448 std::string MethodTypeString;
7449 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7450 Result += "\", \"";
7451 Result += MethodTypeString;
7452 Result += "\", (void *)";
7453 Result += MethodInternalNames[*MethodBegin];
7454 Result += "}\n";
7455 }
7456 Result += "\t }\n};\n";
7457}
7458
7459Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7460 SourceRange OldRange = IV->getSourceRange();
7461 Expr *BaseExpr = IV->getBase();
7462
7463 // Rewrite the base, but without actually doing replaces.
7464 {
7465 DisableReplaceStmtScope S(*this);
7466 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7467 IV->setBase(BaseExpr);
7468 }
7469
7470 ObjCIvarDecl *D = IV->getDecl();
7471
7472 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007473
Fariborz Jahanian11671902012-02-07 17:11:38 +00007474 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7475 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007476 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007477 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7478 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007479 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007480 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7481 clsDeclared);
7482 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7483
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007484 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007485 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007486 if (D->isBitField())
7487 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7488 else
7489 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007490
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007491 ReferencedIvars[clsDeclared].insert(D);
7492
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007493 // cast offset to "char *".
7494 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7495 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007496 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007497 BaseExpr);
7498 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7499 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007500 Context->UnsignedLongTy, nullptr,
7501 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007502 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7503 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007504 SourceLocation());
7505 BinaryOperator *addExpr =
7506 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7507 Context->getPointerType(Context->CharTy),
Adam Nemet484aa452017-03-27 19:17:25 +00007508 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007509 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007510 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7511 SourceLocation(),
7512 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007513 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007514 if (D->isBitField())
7515 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007516
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007517 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007518 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007519 RD = RD->getDefinition();
7520 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007521 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007522 ObjCContainerDecl *CDecl =
7523 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7524 // ivar in class extensions requires special treatment.
7525 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7526 CDecl = CatDecl->getClassInterface();
7527 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007528 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007529 RecordDecl *RD = RecordDecl::Create(
7530 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7531 &Context->Idents.get(RecName));
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007532 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7533 unsigned UnsignedIntSize =
7534 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7535 Expr *Zero = IntegerLiteral::Create(*Context,
7536 llvm::APInt(UnsignedIntSize, 0),
7537 Context->UnsignedIntTy, SourceLocation());
7538 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7539 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7540 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007541 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007542 SourceLocation(),
7543 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007544 IvarT, nullptr,
7545 /*BitWidth=*/nullptr,
7546 /*Mutable=*/true, ICIS_NoInit);
7547 MemberExpr *ME = new (Context)
7548 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7549 FD->getType(), VK_LValue, OK_Ordinary);
7550 IvarT = Context->getDecltypeType(ME, ME->getType());
7551 }
7552 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007553 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007554 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007555
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007556 castExpr = NoTypeInfoCStyleCastExpr(Context,
7557 castT,
7558 CK_BitCast,
7559 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007560
7561
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007562 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007563 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00007564 SourceLocation(), false);
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007565 PE = new (Context) ParenExpr(OldRange.getBegin(),
7566 OldRange.getEnd(),
7567 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007568
7569 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007570 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007571 SourceLocation(),
7572 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007573 D->getType(), nullptr,
7574 /*BitWidth=*/D->getBitWidth(),
7575 /*Mutable=*/true, ICIS_NoInit);
7576 MemberExpr *ME = new (Context)
7577 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7578 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7579 Replacement = ME;
7580
7581 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007582 else
7583 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007584 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007585
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007586 ReplaceStmtWithRange(IV, Replacement, OldRange);
7587 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007588}
Alp Toker0621cb22014-07-16 16:48:33 +00007589
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007590#endif // CLANG_ENABLE_OBJC_REWRITER