blob: 5538fd2835d91894412d7cd0f44ad488ede72c8f [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"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
Alp Toker0621cb22014-07-16 16:48:33 +000033#ifdef CLANG_ENABLE_OBJC_REWRITER
34
Fariborz Jahanian11671902012-02-07 17:11:38 +000035using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
41
42 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 __block variable */
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 helpers */
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 support routines */
52 BLOCK_BYREF_CURRENT_MAX = 256
53 };
54
55 enum {
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000063
64 Rewriter Rewrite;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
67 ASTContext *Context;
68 SourceManager *SM;
69 TranslationUnitDecl *TUDecl;
70 FileID MainFileID;
71 const char *MainFileStart, *MainFileEnd;
72 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000080 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000082 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000083 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
87
88 // ObjC foreach break/continue generation support.
89 int BcLabelCount;
90
91 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
96
97 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000107 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000108 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000109
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120
121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000123
Fariborz Jahanian11671902012-02-07 17:11:38 +0000124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128
129 llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
John McCall113bee02012-03-10 09:33:50 +0000136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137
138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
149 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
150
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000158
Fariborz Jahanian11671902012-02-07 17:11:38 +0000159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000167 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000168 bool objc_impl_method;
169
170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
174
175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000188
Fariborz Jahanian11671902012-02-07 17:11:38 +0000189 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000190 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193 if (!Class->isThisDeclarationADefinition()) {
194 RewriteForwardClassDecl(D);
195 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000196 } else {
197 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000198 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000199 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000200 }
201 }
202
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
206 break;
207 }
208 }
209
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211 // Under modern abi, we cannot translate body of the function
212 // yet until all class extensions and its implementation is seen.
213 // This is because they may introduce new bitfields which must go
214 // into their grouping struct.
215 if (FDecl->isThisDeclarationADefinition() &&
216 // Not c functions defined inside an objc container.
217 !FDecl->isTopLevelDeclInObjCContainer()) {
218 FunctionDefinitionsSeen.push_back(FDecl);
219 break;
220 }
221 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000222 HandleTopLevelSingleDecl(*I);
223 }
224 return true;
225 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000226
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231 RewriteBlockPointerDecl(TD);
232 else if (TD->getUnderlyingType()->isFunctionPointerType())
233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234 else
235 RewriteObjCQualifiedInterfaceTypes(TD);
236 }
237 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000238 }
239
Fariborz Jahanian11671902012-02-07 17:11:38 +0000240 void HandleTopLevelSingleDecl(Decl *D);
241 void HandleDeclInMainFile(Decl *D);
242 RewriteModernObjC(std::string inFile, raw_ostream *OS,
243 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000244 bool silenceMacroWarn, bool LineInfo);
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000246 ~RewriteModernObjC() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000247
248 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000249
250 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000251 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000255 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000256
257 Stmt *ReplacingStmt = ReplacedNodes[Old];
258 if (ReplacingStmt)
259 return; // We can't rewrite the same node twice.
260
Fariborz Jahanian11671902012-02-07 17:11:38 +0000261 if (DisableReplaceStmt)
262 return;
263
264 // Measure the old text.
265 int Size = Rewrite.getRangeSize(SrcRange);
266 if (Size == -1) {
267 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
268 << Old->getSourceRange();
269 return;
270 }
271 // Get the new text.
272 std::string SStr;
273 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000274 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000275 const std::string &Str = S.str();
276
277 // If replacement succeeded or warning disabled return with no warning.
278 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279 ReplacedNodes[Old] = New;
280 return;
281 }
282 if (SilenceRewriteMacroWarning)
283 return;
284 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
285 << Old->getSourceRange();
286 }
287
288 void InsertText(SourceLocation Loc, StringRef Str,
289 bool InsertAfter = true) {
290 // If insertion succeeded or warning disabled return with no warning.
291 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292 SilenceRewriteMacroWarning)
293 return;
294
295 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296 }
297
298 void ReplaceText(SourceLocation Start, unsigned OrigLength,
299 StringRef Str) {
300 // If removal succeeded or warning disabled return with no warning.
301 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302 SilenceRewriteMacroWarning)
303 return;
304
305 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306 }
307
308 // Syntactic Rewriting.
309 void RewriteRecordBody(RecordDecl *RD);
310 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000311 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000312 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000314 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000315 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000316 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317 const std::string &typedefString);
318 void RewriteImplementations();
319 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320 ObjCImplementationDecl *IMD,
321 ObjCCategoryImplDecl *CID);
322 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323 void RewriteImplementationDecl(Decl *Dcl);
324 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325 ObjCMethodDecl *MDecl, std::string &ResultStr);
326 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327 const FunctionType *&FPRetType);
328 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329 ValueDecl *VD, bool def=false);
330 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000333 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000334 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335 void RewriteProperty(ObjCPropertyDecl *prop);
336 void RewriteFunctionDecl(FunctionDecl *FD);
337 void RewriteBlockPointerType(std::string& Str, QualType Type);
338 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000339 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000340 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341 void RewriteTypeOfDecl(VarDecl *VD);
342 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000343
344 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000345
346 // Expression Rewriting.
347 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000354 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000355 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000356 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000357 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000358 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000360 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000361 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364 SourceLocation OrigEnd);
365 Stmt *RewriteBreakStmt(BreakStmt *S);
366 Stmt *RewriteContinueStmt(ContinueStmt *S);
367 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000368 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000369
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000370 // Computes ivar bitfield group no.
371 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372 // Names field decl. for ivar bitfield group.
373 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374 // Names struct type for ivar bitfield group.
375 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376 // Names symbol for ivar bitfield group field offset.
377 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378 // Given an ivar bitfield, it builds (or finds) its group record type.
379 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380 QualType SynthesizeBitfieldGroupStructType(
381 ObjCIvarDecl *IV,
382 SmallVectorImpl<ObjCIvarDecl *> &IVars);
383
Fariborz Jahanian11671902012-02-07 17:11:38 +0000384 // Block rewriting.
385 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386
387 // Block specific rewrite rules.
388 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000389 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000390 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000391 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393
394 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395 std::string &Result);
396
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000397 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000398 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000399 bool &IsNamedDefinition);
400 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000402
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000403 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000405 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000407
408 void Initialize(ASTContext &context) override;
409
Benjamin Kramer474261a2012-06-02 10:20:41 +0000410 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000411 // rewriting routines on the new ASTs.
412 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000413 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000414 SourceLocation StartLoc=SourceLocation(),
415 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000416
417 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000418 QualType returnType,
419 SmallVectorImpl<QualType> &ArgTypes,
420 SmallVectorImpl<Expr*> &MsgExprs,
421 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000422
423 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
426
427 void SynthCountByEnumWithState(std::string &buf);
428 void SynthMsgSendFunctionDecl();
429 void SynthMsgSendSuperFunctionDecl();
430 void SynthMsgSendStretFunctionDecl();
431 void SynthMsgSendFpretFunctionDecl();
432 void SynthMsgSendSuperStretFunctionDecl();
433 void SynthGetClassFunctionDecl();
434 void SynthGetMetaClassFunctionDecl();
435 void SynthGetSuperClassFunctionDecl();
436 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000437 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000438
439 // Rewriting metadata
440 template<typename MethodIterator>
441 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442 MethodIterator MethodEnd,
443 bool IsInstanceMethod,
444 StringRef prefix,
445 StringRef ClassName,
446 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000447 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000450 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000451 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000452
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000456 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000457 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000458
459 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463
464
465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
470 std::string SynthesizeBlockImpl(BlockExpr *CE,
471 std::string Tag, std::string Desc);
472 std::string SynthesizeBlockDescriptor(std::string DescTag,
473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000481 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000493 void GetInnerBlockDeclRefExprs(Stmt *S,
494 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000495 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
508 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
514
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000515 bool convertObjCTypeToCStyleType(QualType &T);
516
Fariborz Jahanian11671902012-02-07 17:11:38 +0000517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000521
522 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
525 T = isConst ? Context->getObjCIdType().withConst()
526 : Context->getObjCIdType();
527 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
540
541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
543 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000559
Fariborz Jahanian11671902012-02-07 17:11:38 +0000560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
564
565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000575 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000581 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000590 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000591
592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000595 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000597
598 StringLiteral *getStringLiteral(StringRef Str) {
599 QualType StrType = Context->getConstantArrayType(
600 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
601 0);
602 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603 /*Pascal=*/false, StrType, SourceLocation());
604 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000605 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000606} // end anonymous namespace
Fariborz Jahanian11671902012-02-07 17:11:38 +0000607
608void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609 NamedDecl *D) {
610 if (const FunctionProtoType *fproto
611 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000612 for (const auto &I : fproto->param_types())
613 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000614 // All the args are checked/rewritten. Don't call twice!
615 RewriteBlockPointerDecl(D);
616 break;
617 }
618 }
619}
620
621void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622 const PointerType *PT = funcType->getAs<PointerType>();
623 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625}
626
627static bool IsHeaderFile(const std::string &Filename) {
628 std::string::size_type DotPos = Filename.rfind('.');
629
630 if (DotPos == std::string::npos) {
631 // no file extension
632 return false;
633 }
634
635 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636 // C header: .h
637 // C++ header: .hh or .H;
638 return Ext == "h" || Ext == "hh" || Ext == "H";
639}
640
641RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
642 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000643 bool silenceMacroWarn,
644 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000645 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000646 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000647 IsHeader = IsHeaderFile(inFile);
648 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
649 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000650 // FIXME. This should be an error. But if block is not called, it is OK. And it
651 // may break including some headers.
652 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
653 "rewriting block literal declared in global scope is not implemented");
654
Fariborz Jahanian11671902012-02-07 17:11:38 +0000655 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
656 DiagnosticsEngine::Warning,
657 "rewriter doesn't support user-specified control flow semantics "
658 "for @try/@finally (code may not execute properly)");
659}
660
David Blaikie6beb6aa2014-08-10 19:56:51 +0000661std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
662 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
663 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
664 return llvm::make_unique<RewriteModernObjC>(
665 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000666}
667
668void RewriteModernObjC::InitializeCommon(ASTContext &context) {
669 Context = &context;
670 SM = &Context->getSourceManager();
671 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000672 MsgSendFunctionDecl = nullptr;
673 MsgSendSuperFunctionDecl = nullptr;
674 MsgSendStretFunctionDecl = nullptr;
675 MsgSendSuperStretFunctionDecl = nullptr;
676 MsgSendFpretFunctionDecl = nullptr;
677 GetClassFunctionDecl = nullptr;
678 GetMetaClassFunctionDecl = nullptr;
679 GetSuperClassFunctionDecl = nullptr;
680 SelGetUidFunctionDecl = nullptr;
681 CFStringFunctionDecl = nullptr;
682 ConstantStringClassReference = nullptr;
683 NSStringRecord = nullptr;
684 CurMethodDef = nullptr;
685 CurFunctionDef = nullptr;
686 GlobalVarDecl = nullptr;
687 GlobalConstructionExp = nullptr;
688 SuperStructDecl = nullptr;
689 ProtocolTypeDecl = nullptr;
690 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000691 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000692 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000693 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000694 PropParentMap = nullptr;
695 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000696 DisableReplaceStmt = false;
697 objc_impl_method = false;
698
699 // Get the ID and start/end of the main file.
700 MainFileID = SM->getMainFileID();
701 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
702 MainFileStart = MainBuf->getBufferStart();
703 MainFileEnd = MainBuf->getBufferEnd();
704
David Blaikiebbafb8a2012-03-11 07:00:24 +0000705 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000706}
707
708//===----------------------------------------------------------------------===//
709// Top Level Driver Code
710//===----------------------------------------------------------------------===//
711
712void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
713 if (Diags.hasErrorOccurred())
714 return;
715
716 // Two cases: either the decl could be in the main file, or it could be in a
717 // #included file. If the former, rewrite it now. If the later, check to see
718 // if we rewrote the #include/#import.
719 SourceLocation Loc = D->getLocation();
720 Loc = SM->getExpansionLoc(Loc);
721
722 // If this is for a builtin, ignore it.
723 if (Loc.isInvalid()) return;
724
725 // Look for built-in declarations that we need to refer during the rewrite.
726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
727 RewriteFunctionDecl(FD);
728 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
729 // declared in <Foundation/NSString.h>
730 if (FVD->getName() == "_NSConstantStringClassReference") {
731 ConstantStringClassReference = FVD;
732 return;
733 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000734 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
735 RewriteCategoryDecl(CD);
736 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
737 if (PD->isThisDeclarationADefinition())
738 RewriteProtocolDecl(PD);
739 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
740 // Recurse into linkage specifications
741 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
742 DIEnd = LSD->decls_end();
743 DI != DIEnd; ) {
744 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
745 if (!IFace->isThisDeclarationADefinition()) {
746 SmallVector<Decl *, 8> DG;
747 SourceLocation StartLoc = IFace->getLocStart();
748 do {
749 if (isa<ObjCInterfaceDecl>(*DI) &&
750 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
751 StartLoc == (*DI)->getLocStart())
752 DG.push_back(*DI);
753 else
754 break;
755
756 ++DI;
757 } while (DI != DIEnd);
758 RewriteForwardClassDecl(DG);
759 continue;
760 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000761 else {
762 // Keep track of all interface declarations seen.
763 ObjCInterfacesSeen.push_back(IFace);
764 ++DI;
765 continue;
766 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000767 }
768
769 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
770 if (!Proto->isThisDeclarationADefinition()) {
771 SmallVector<Decl *, 8> DG;
772 SourceLocation StartLoc = Proto->getLocStart();
773 do {
774 if (isa<ObjCProtocolDecl>(*DI) &&
775 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
776 StartLoc == (*DI)->getLocStart())
777 DG.push_back(*DI);
778 else
779 break;
780
781 ++DI;
782 } while (DI != DIEnd);
783 RewriteForwardProtocolDecl(DG);
784 continue;
785 }
786 }
787
788 HandleTopLevelSingleDecl(*DI);
789 ++DI;
790 }
791 }
792 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000793 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000794 return HandleDeclInMainFile(D);
795}
796
797//===----------------------------------------------------------------------===//
798// Syntactic (non-AST) Rewriting Code
799//===----------------------------------------------------------------------===//
800
801void RewriteModernObjC::RewriteInclude() {
802 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
803 StringRef MainBuf = SM->getBufferData(MainFileID);
804 const char *MainBufStart = MainBuf.begin();
805 const char *MainBufEnd = MainBuf.end();
806 size_t ImportLen = strlen("import");
807
808 // Loop over the whole file, looking for includes.
809 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
810 if (*BufPtr == '#') {
811 if (++BufPtr == MainBufEnd)
812 return;
813 while (*BufPtr == ' ' || *BufPtr == '\t')
814 if (++BufPtr == MainBufEnd)
815 return;
816 if (!strncmp(BufPtr, "import", ImportLen)) {
817 // replace import with include
818 SourceLocation ImportLoc =
819 LocStart.getLocWithOffset(BufPtr-MainBufStart);
820 ReplaceText(ImportLoc, ImportLen, "include");
821 BufPtr += ImportLen;
822 }
823 }
824 }
825}
826
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000827static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
828 ObjCIvarDecl *IvarDecl, std::string &Result) {
829 Result += "OBJC_IVAR_$_";
830 Result += IDecl->getName();
831 Result += "$";
832 Result += IvarDecl->getName();
833}
834
835std::string
836RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
837 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
838
839 // Build name of symbol holding ivar offset.
840 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000841 if (D->isBitField())
842 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
843 else
844 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000845
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000846 std::string S = "(*(";
847 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000848 if (D->isBitField())
849 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850
851 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
852 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
853 RD = RD->getDefinition();
854 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
855 // decltype(((Foo_IMPL*)0)->bar) *
856 ObjCContainerDecl *CDecl =
857 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
858 // ivar in class extensions requires special treatment.
859 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
860 CDecl = CatDecl->getClassInterface();
861 std::string RecName = CDecl->getName();
862 RecName += "_IMPL";
863 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
864 SourceLocation(), SourceLocation(),
865 &Context->Idents.get(RecName.c_str()));
866 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
867 unsigned UnsignedIntSize =
868 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
869 Expr *Zero = IntegerLiteral::Create(*Context,
870 llvm::APInt(UnsignedIntSize, 0),
871 Context->UnsignedIntTy, SourceLocation());
872 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
873 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
874 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000875 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000876 SourceLocation(),
877 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000878 IvarT, nullptr,
879 /*BitWidth=*/nullptr, /*Mutable=*/true,
880 ICIS_NoInit);
881 MemberExpr *ME = new (Context)
882 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
883 FD->getType(), VK_LValue, OK_Ordinary);
884 IvarT = Context->getDecltypeType(ME, ME->getType());
885 }
886 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000887 convertObjCTypeToCStyleType(IvarT);
888 QualType castT = Context->getPointerType(IvarT);
889 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
890 S += TypeString;
891 S += ")";
892
893 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
894 S += "((char *)self + ";
895 S += IvarOffsetName;
896 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000897 if (D->isBitField()) {
898 S += ".";
899 S += D->getNameAsString();
900 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000901 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000902 return S;
903}
904
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000905/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
906/// been found in the class implementation. In this case, it must be synthesized.
907static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
908 ObjCPropertyDecl *PD,
909 bool getter) {
910 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
911 : !IMP->getInstanceMethod(PD->getSetterName());
912
913}
914
Fariborz Jahanian11671902012-02-07 17:11:38 +0000915void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
916 ObjCImplementationDecl *IMD,
917 ObjCCategoryImplDecl *CID) {
918 static bool objcGetPropertyDefined = false;
919 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000920 SourceLocation startGetterSetterLoc;
921
922 if (PID->getLocStart().isValid()) {
923 SourceLocation startLoc = PID->getLocStart();
924 InsertText(startLoc, "// ");
925 const char *startBuf = SM->getCharacterData(startLoc);
926 assert((*startBuf == '@') && "bogus @synthesize location");
927 const char *semiBuf = strchr(startBuf, ';');
928 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
929 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
930 }
931 else
932 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000933
934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935 return; // FIXME: is this correct?
936
937 // Generate the 'getter' function.
938 ObjCPropertyDecl *PD = PID->getPropertyDecl();
939 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000940 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000941
Bill Wendling44426052012-12-20 19:22:21 +0000942 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000943 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000944 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000946 ObjCPropertyDecl::OBJC_PR_copy));
947 std::string Getr;
948 if (GenGetProperty && !objcGetPropertyDefined) {
949 objcGetPropertyDefined = true;
950 // FIXME. Is this attribute correct in all cases?
951 Getr = "\nextern \"C\" __declspec(dllimport) "
952 "id objc_getProperty(id, SEL, long, bool);\n";
953 }
954 RewriteObjCMethodDecl(OID->getContainingInterface(),
955 PD->getGetterMethodDecl(), Getr);
956 Getr += "{ ";
957 // Synthesize an explicit cast to gain access to the ivar.
958 // See objc-act.c:objc_synthesize_new_getter() for details.
959 if (GenGetProperty) {
960 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000962 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000963 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000964 FPRetType);
965 Getr += " _TYPE";
966 if (FPRetType) {
967 Getr += ")"; // close the precedence "scope" for "*".
968
969 // Now, emit the argument types (if any).
970 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000972 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000973 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000974 std::string ParamStr =
975 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000976 Getr += ParamStr;
977 }
978 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000979 if (FT->getNumParams())
980 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000981 Getr += "...";
982 }
983 Getr += ")";
984 } else
985 Getr += "()";
986 }
987 Getr += ";\n";
988 Getr += "return (_TYPE)";
989 Getr += "objc_getProperty(self, _cmd, ";
990 RewriteIvarOffsetComputation(OID, Getr);
991 Getr += ", 1)";
992 }
993 else
994 Getr += "return " + getIvarAccessString(OID);
995 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000996 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 }
998
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000999 if (PD->isReadOnly() ||
1000 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001001 return;
1002
1003 // Generate the 'setter' function.
1004 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001005 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001006 ObjCPropertyDecl::OBJC_PR_copy);
1007 if (GenSetProperty && !objcSetPropertyDefined) {
1008 objcSetPropertyDefined = true;
1009 // FIXME. Is this attribute correct in all cases?
1010 Setr = "\nextern \"C\" __declspec(dllimport) "
1011 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012 }
1013
1014 RewriteObjCMethodDecl(OID->getContainingInterface(),
1015 PD->getSetterMethodDecl(), Setr);
1016 Setr += "{ ";
1017 // Synthesize an explicit cast to initialize the ivar.
1018 // See objc-act.c:objc_synthesize_new_setter() for details.
1019 if (GenSetProperty) {
1020 Setr += "objc_setProperty (self, _cmd, ";
1021 RewriteIvarOffsetComputation(OID, Setr);
1022 Setr += ", (id)";
1023 Setr += PD->getName();
1024 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001025 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001026 Setr += "0, ";
1027 else
1028 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001029 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 Setr += "1)";
1031 else
1032 Setr += "0)";
1033 }
1034 else {
1035 Setr += getIvarAccessString(OID) + " = ";
1036 Setr += PD->getName();
1037 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001038 Setr += "; }\n";
1039 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001040}
1041
1042static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001044 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001045 typedefString += ForwardDecl->getNameAsString();
1046 typedefString += "\n";
1047 typedefString += "#define _REWRITER_typedef_";
1048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "typedef struct objc_object ";
1051 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001052 // typedef struct { } _objc_exc_Classname;
1053 typedefString += ";\ntypedef struct {} _objc_exc_";
1054 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001055 typedefString += ";\n#endif\n";
1056}
1057
1058void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059 const std::string &typedefString) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001060 SourceLocation startLoc = ClassDecl->getLocStart();
1061 const char *startBuf = SM->getCharacterData(startLoc);
1062 const char *semiPtr = strchr(startBuf, ';');
1063 // Replace the @class with typedefs corresponding to the classes.
1064 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001065}
1066
1067void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068 std::string typedefString;
1069 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001070 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1071 if (I == D.begin()) {
1072 // Translate to typedef's that forward reference structs with the same name
1073 // as the class. As a convenience, we include the original declaration
1074 // as a comment.
1075 typedefString += "// @class ";
1076 typedefString += ForwardDecl->getNameAsString();
1077 typedefString += ";";
1078 }
1079 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001080 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001081 else
1082 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001083 }
1084 DeclGroupRef::iterator I = D.begin();
1085 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086}
1087
1088void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001089 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001090 std::string typedefString;
1091 for (unsigned i = 0; i < D.size(); i++) {
1092 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093 if (i == 0) {
1094 typedefString += "// @class ";
1095 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001096 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001097 }
1098 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099 }
1100 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101}
1102
1103void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104 // When method is a synthesized one, such as a getter/setter there is
1105 // nothing to rewrite.
1106 if (Method->isImplicit())
1107 return;
1108 SourceLocation LocStart = Method->getLocStart();
1109 SourceLocation LocEnd = Method->getLocEnd();
1110
1111 if (SM->getExpansionLineNumber(LocEnd) >
1112 SM->getExpansionLineNumber(LocStart)) {
1113 InsertText(LocStart, "#if 0\n");
1114 ReplaceText(LocEnd, 1, ";\n#endif\n");
1115 } else {
1116 InsertText(LocStart, "// ");
1117 }
1118}
1119
1120void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121 SourceLocation Loc = prop->getAtLoc();
1122
1123 ReplaceText(Loc, 0, "// ");
1124 // FIXME: handle properties that are declared across multiple lines.
1125}
1126
1127void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128 SourceLocation LocStart = CatDecl->getLocStart();
1129
1130 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001131 if (CatDecl->getIvarRBraceLoc().isValid()) {
1132 ReplaceText(LocStart, 1, "/** ");
1133 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134 }
1135 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001136 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001137 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001138
Manman Rena7a8b1f2016-01-26 18:05:23 +00001139 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001140 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001141
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001142 for (auto *I : CatDecl->instance_methods())
1143 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001144 for (auto *I : CatDecl->class_methods())
1145 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001146
1147 // Lastly, comment out the @end.
1148 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001149 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001150}
1151
1152void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153 SourceLocation LocStart = PDecl->getLocStart();
1154 assert(PDecl->isThisDeclarationADefinition());
1155
1156 // FIXME: handle protocol headers that are declared across multiple lines.
1157 ReplaceText(LocStart, 0, "// ");
1158
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001159 for (auto *I : PDecl->instance_methods())
1160 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001161 for (auto *I : PDecl->class_methods())
1162 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001163 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001164 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001165
1166 // Lastly, comment out the @end.
1167 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001168 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001169
1170 // Must comment out @optional/@required
1171 const char *startBuf = SM->getCharacterData(LocStart);
1172 const char *endBuf = SM->getCharacterData(LocEnd);
1173 for (const char *p = startBuf; p < endBuf; p++) {
1174 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1175 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1176 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1177
1178 }
1179 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1180 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1181 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1182
1183 }
1184 }
1185}
1186
1187void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1188 SourceLocation LocStart = (*D.begin())->getLocStart();
1189 if (LocStart.isInvalid())
1190 llvm_unreachable("Invalid SourceLocation");
1191 // FIXME: handle forward protocol that are declared across multiple lines.
1192 ReplaceText(LocStart, 0, "// ");
1193}
1194
1195void
Craig Topper5603df42013-07-05 19:34:19 +00001196RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001197 SourceLocation LocStart = DG[0]->getLocStart();
1198 if (LocStart.isInvalid())
1199 llvm_unreachable("Invalid SourceLocation");
1200 // FIXME: handle forward protocol that are declared across multiple lines.
1201 ReplaceText(LocStart, 0, "// ");
1202}
1203
1204void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1205 const FunctionType *&FPRetType) {
1206 if (T->isObjCQualifiedIdType())
1207 ResultStr += "id";
1208 else if (T->isFunctionPointerType() ||
1209 T->isBlockPointerType()) {
1210 // needs special handling, since pointer-to-functions have special
1211 // syntax (where a decaration models use).
1212 QualType retType = T;
1213 QualType PointeeTy;
1214 if (const PointerType* PT = retType->getAs<PointerType>())
1215 PointeeTy = PT->getPointeeType();
1216 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1217 PointeeTy = BPT->getPointeeType();
1218 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001219 ResultStr +=
1220 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001221 ResultStr += "(*";
1222 }
1223 } else
1224 ResultStr += T.getAsString(Context->getPrintingPolicy());
1225}
1226
1227void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1228 ObjCMethodDecl *OMD,
1229 std::string &ResultStr) {
1230 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001231 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001232 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001233 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001234 ResultStr += " ";
1235
1236 // Unique method name
1237 std::string NameStr;
1238
1239 if (OMD->isInstanceMethod())
1240 NameStr += "_I_";
1241 else
1242 NameStr += "_C_";
1243
1244 NameStr += IDecl->getNameAsString();
1245 NameStr += "_";
1246
1247 if (ObjCCategoryImplDecl *CID =
1248 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1249 NameStr += CID->getNameAsString();
1250 NameStr += "_";
1251 }
1252 // Append selector names, replacing ':' with '_'
1253 {
1254 std::string selString = OMD->getSelector().getAsString();
1255 int len = selString.size();
1256 for (int i = 0; i < len; i++)
1257 if (selString[i] == ':')
1258 selString[i] = '_';
1259 NameStr += selString;
1260 }
1261 // Remember this name for metadata emission
1262 MethodInternalNames[OMD] = NameStr;
1263 ResultStr += NameStr;
1264
1265 // Rewrite arguments
1266 ResultStr += "(";
1267
1268 // invisible arguments
1269 if (OMD->isInstanceMethod()) {
1270 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1271 selfTy = Context->getPointerType(selfTy);
1272 if (!LangOpts.MicrosoftExt) {
1273 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1274 ResultStr += "struct ";
1275 }
1276 // When rewriting for Microsoft, explicitly omit the structure name.
1277 ResultStr += IDecl->getNameAsString();
1278 ResultStr += " *";
1279 }
1280 else
1281 ResultStr += Context->getObjCClassType().getAsString(
1282 Context->getPrintingPolicy());
1283
1284 ResultStr += " self, ";
1285 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1286 ResultStr += " _cmd";
1287
1288 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001289 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001290 ResultStr += ", ";
1291 if (PDecl->getType()->isObjCQualifiedIdType()) {
1292 ResultStr += "id ";
1293 ResultStr += PDecl->getNameAsString();
1294 } else {
1295 std::string Name = PDecl->getNameAsString();
1296 QualType QT = PDecl->getType();
1297 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001298 (void)convertBlockPointerToFunctionPointer(QT);
1299 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001300 ResultStr += Name;
1301 }
1302 }
1303 if (OMD->isVariadic())
1304 ResultStr += ", ...";
1305 ResultStr += ") ";
1306
1307 if (FPRetType) {
1308 ResultStr += ")"; // close the precedence "scope" for "*".
1309
1310 // Now, emit the argument types (if any).
1311 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1312 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001313 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001314 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001315 std::string ParamStr =
1316 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001317 ResultStr += ParamStr;
1318 }
1319 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001320 if (FT->getNumParams())
1321 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001322 ResultStr += "...";
1323 }
1324 ResultStr += ")";
1325 } else {
1326 ResultStr += "()";
1327 }
1328 }
1329}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001330
Fariborz Jahanian11671902012-02-07 17:11:38 +00001331void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1332 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1333 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1334
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001335 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001336 if (IMD->getIvarRBraceLoc().isValid()) {
1337 ReplaceText(IMD->getLocStart(), 1, "/** ");
1338 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001339 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001340 else {
1341 InsertText(IMD->getLocStart(), "// ");
1342 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001343 }
1344 else
1345 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001346
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001347 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001348 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001349 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1350 SourceLocation LocStart = OMD->getLocStart();
1351 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1352
1353 const char *startBuf = SM->getCharacterData(LocStart);
1354 const char *endBuf = SM->getCharacterData(LocEnd);
1355 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1356 }
1357
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001358 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001359 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001360 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1361 SourceLocation LocStart = OMD->getLocStart();
1362 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1363
1364 const char *startBuf = SM->getCharacterData(LocStart);
1365 const char *endBuf = SM->getCharacterData(LocEnd);
1366 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1367 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001368 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1369 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001370
1371 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1372}
1373
1374void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001375 // Do not synthesize more than once.
1376 if (ObjCSynthesizedStructs.count(ClassDecl))
1377 return;
1378 // Make sure super class's are written before current class is written.
1379 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1380 while (SuperClass) {
1381 RewriteInterfaceDecl(SuperClass);
1382 SuperClass = SuperClass->getSuperClass();
1383 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001384 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001385 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001386 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001387 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001388 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1389
Fariborz Jahanianff513382012-02-15 22:01:47 +00001390 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001391 // Mark this typedef as having been written into its c++ equivalent.
1392 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001393
Manman Rena7a8b1f2016-01-26 18:05:23 +00001394 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001395 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001396 for (auto *I : ClassDecl->instance_methods())
1397 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001398 for (auto *I : ClassDecl->class_methods())
1399 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001400
Fariborz Jahanianff513382012-02-15 22:01:47 +00001401 // Lastly, comment out the @end.
1402 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001403 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001404 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001405}
1406
1407Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1408 SourceRange OldRange = PseudoOp->getSourceRange();
1409
1410 // We just magically know some things about the structure of this
1411 // expression.
1412 ObjCMessageExpr *OldMsg =
1413 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1414 PseudoOp->getNumSemanticExprs() - 1));
1415
1416 // Because the rewriter doesn't allow us to rewrite rewritten code,
1417 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001418 Expr *Base;
1419 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001420 {
1421 DisableReplaceStmtScope S(*this);
1422
1423 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001424 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001425 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1426 Base = OldMsg->getInstanceReceiver();
1427 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1428 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1429 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001430
1431 unsigned numArgs = OldMsg->getNumArgs();
1432 for (unsigned i = 0; i < numArgs; i++) {
1433 Expr *Arg = OldMsg->getArg(i);
1434 if (isa<OpaqueValueExpr>(Arg))
1435 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1436 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1437 Args.push_back(Arg);
1438 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001439 }
1440
1441 // TODO: avoid this copy.
1442 SmallVector<SourceLocation, 1> SelLocs;
1443 OldMsg->getSelectorLocs(SelLocs);
1444
Craig Topper8ae12032014-05-07 06:21:57 +00001445 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 switch (OldMsg->getReceiverKind()) {
1447 case ObjCMessageExpr::Class:
1448 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1449 OldMsg->getValueKind(),
1450 OldMsg->getLeftLoc(),
1451 OldMsg->getClassReceiverTypeInfo(),
1452 OldMsg->getSelector(),
1453 SelLocs,
1454 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001455 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001456 OldMsg->getRightLoc(),
1457 OldMsg->isImplicit());
1458 break;
1459
1460 case ObjCMessageExpr::Instance:
1461 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1462 OldMsg->getValueKind(),
1463 OldMsg->getLeftLoc(),
1464 Base,
1465 OldMsg->getSelector(),
1466 SelLocs,
1467 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001468 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001469 OldMsg->getRightLoc(),
1470 OldMsg->isImplicit());
1471 break;
1472
1473 case ObjCMessageExpr::SuperClass:
1474 case ObjCMessageExpr::SuperInstance:
1475 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1476 OldMsg->getValueKind(),
1477 OldMsg->getLeftLoc(),
1478 OldMsg->getSuperLoc(),
1479 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1480 OldMsg->getSuperType(),
1481 OldMsg->getSelector(),
1482 SelLocs,
1483 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001484 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001485 OldMsg->getRightLoc(),
1486 OldMsg->isImplicit());
1487 break;
1488 }
1489
1490 Stmt *Replacement = SynthMessageExpr(NewMsg);
1491 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1492 return Replacement;
1493}
1494
1495Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1496 SourceRange OldRange = PseudoOp->getSourceRange();
1497
1498 // We just magically know some things about the structure of this
1499 // expression.
1500 ObjCMessageExpr *OldMsg =
1501 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1502
1503 // Because the rewriter doesn't allow us to rewrite rewritten code,
1504 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001505 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001506 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001507 {
1508 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001509 // Rebuild the base expression if we have one.
1510 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1511 Base = OldMsg->getInstanceReceiver();
1512 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1513 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1514 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001515 unsigned numArgs = OldMsg->getNumArgs();
1516 for (unsigned i = 0; i < numArgs; i++) {
1517 Expr *Arg = OldMsg->getArg(i);
1518 if (isa<OpaqueValueExpr>(Arg))
1519 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1520 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1521 Args.push_back(Arg);
1522 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001523 }
1524
1525 // Intentionally empty.
1526 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001527
Craig Topper8ae12032014-05-07 06:21:57 +00001528 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001529 switch (OldMsg->getReceiverKind()) {
1530 case ObjCMessageExpr::Class:
1531 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1532 OldMsg->getValueKind(),
1533 OldMsg->getLeftLoc(),
1534 OldMsg->getClassReceiverTypeInfo(),
1535 OldMsg->getSelector(),
1536 SelLocs,
1537 OldMsg->getMethodDecl(),
1538 Args,
1539 OldMsg->getRightLoc(),
1540 OldMsg->isImplicit());
1541 break;
1542
1543 case ObjCMessageExpr::Instance:
1544 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1545 OldMsg->getValueKind(),
1546 OldMsg->getLeftLoc(),
1547 Base,
1548 OldMsg->getSelector(),
1549 SelLocs,
1550 OldMsg->getMethodDecl(),
1551 Args,
1552 OldMsg->getRightLoc(),
1553 OldMsg->isImplicit());
1554 break;
1555
1556 case ObjCMessageExpr::SuperClass:
1557 case ObjCMessageExpr::SuperInstance:
1558 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1559 OldMsg->getValueKind(),
1560 OldMsg->getLeftLoc(),
1561 OldMsg->getSuperLoc(),
1562 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1563 OldMsg->getSuperType(),
1564 OldMsg->getSelector(),
1565 SelLocs,
1566 OldMsg->getMethodDecl(),
1567 Args,
1568 OldMsg->getRightLoc(),
1569 OldMsg->isImplicit());
1570 break;
1571 }
1572
1573 Stmt *Replacement = SynthMessageExpr(NewMsg);
1574 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1575 return Replacement;
1576}
1577
1578/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001579/// ((NSUInteger (*)
1580/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001581/// (void *)objc_msgSend)((id)l_collection,
1582/// sel_registerName(
1583/// "countByEnumeratingWithState:objects:count:"),
1584/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001585/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001586///
1587void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001588 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1589 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001590 buf += "\n\t\t";
1591 buf += "((id)l_collection,\n\t\t";
1592 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1593 buf += "\n\t\t";
1594 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001595 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001596}
1597
1598/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1599/// statement to exit to its outer synthesized loop.
1600///
1601Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1602 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1603 return S;
1604 // replace break with goto __break_label
1605 std::string buf;
1606
1607 SourceLocation startLoc = S->getLocStart();
1608 buf = "goto __break_label_";
1609 buf += utostr(ObjCBcLabelNo.back());
1610 ReplaceText(startLoc, strlen("break"), buf);
1611
Craig Topper8ae12032014-05-07 06:21:57 +00001612 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001613}
1614
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001615void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1616 SourceLocation Loc,
1617 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001618 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001619 LineString += "\n#line ";
1620 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1621 LineString += utostr(PLoc.getLine());
1622 LineString += " \"";
1623 LineString += Lexer::Stringify(PLoc.getFilename());
1624 LineString += "\"\n";
1625 }
1626}
1627
Fariborz Jahanian11671902012-02-07 17:11:38 +00001628/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1629/// statement to continue with its inner synthesized loop.
1630///
1631Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1632 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1633 return S;
1634 // replace continue with goto __continue_label
1635 std::string buf;
1636
1637 SourceLocation startLoc = S->getLocStart();
1638 buf = "goto __continue_label_";
1639 buf += utostr(ObjCBcLabelNo.back());
1640 ReplaceText(startLoc, strlen("continue"), buf);
1641
Craig Topper8ae12032014-05-07 06:21:57 +00001642 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001643}
1644
1645/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1646/// It rewrites:
1647/// for ( type elem in collection) { stmts; }
1648
1649/// Into:
1650/// {
1651/// type elem;
1652/// struct __objcFastEnumerationState enumState = { 0 };
1653/// id __rw_items[16];
1654/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001655/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001656/// objects:__rw_items count:16];
1657/// if (limit) {
1658/// unsigned long startMutations = *enumState.mutationsPtr;
1659/// do {
1660/// unsigned long counter = 0;
1661/// do {
1662/// if (startMutations != *enumState.mutationsPtr)
1663/// objc_enumerationMutation(l_collection);
1664/// elem = (type)enumState.itemsPtr[counter++];
1665/// stmts;
1666/// __continue_label: ;
1667/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001668/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1669/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001670/// elem = nil;
1671/// __break_label: ;
1672/// }
1673/// else
1674/// elem = nil;
1675/// }
1676///
1677Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1678 SourceLocation OrigEnd) {
1679 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1680 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1681 "ObjCForCollectionStmt Statement stack mismatch");
1682 assert(!ObjCBcLabelNo.empty() &&
1683 "ObjCForCollectionStmt - Label No stack empty");
1684
1685 SourceLocation startLoc = S->getLocStart();
1686 const char *startBuf = SM->getCharacterData(startLoc);
1687 StringRef elementName;
1688 std::string elementTypeAsString;
1689 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001690 // line directive first.
1691 SourceLocation ForEachLoc = S->getForLoc();
1692 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1693 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001694 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1695 // type elem;
1696 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1697 QualType ElementType = cast<ValueDecl>(D)->getType();
1698 if (ElementType->isObjCQualifiedIdType() ||
1699 ElementType->isObjCQualifiedInterfaceType())
1700 // Simply use 'id' for all qualified types.
1701 elementTypeAsString = "id";
1702 else
1703 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1704 buf += elementTypeAsString;
1705 buf += " ";
1706 elementName = D->getName();
1707 buf += elementName;
1708 buf += ";\n\t";
1709 }
1710 else {
1711 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1712 elementName = DR->getDecl()->getName();
1713 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1714 if (VD->getType()->isObjCQualifiedIdType() ||
1715 VD->getType()->isObjCQualifiedInterfaceType())
1716 // Simply use 'id' for all qualified types.
1717 elementTypeAsString = "id";
1718 else
1719 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1720 }
1721
1722 // struct __objcFastEnumerationState enumState = { 0 };
1723 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1724 // id __rw_items[16];
1725 buf += "id __rw_items[16];\n\t";
1726 // id l_collection = (id)
1727 buf += "id l_collection = (id)";
1728 // Find start location of 'collection' the hard way!
1729 const char *startCollectionBuf = startBuf;
1730 startCollectionBuf += 3; // skip 'for'
1731 startCollectionBuf = strchr(startCollectionBuf, '(');
1732 startCollectionBuf++; // skip '('
1733 // find 'in' and skip it.
1734 while (*startCollectionBuf != ' ' ||
1735 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1736 (*(startCollectionBuf+3) != ' ' &&
1737 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1738 startCollectionBuf++;
1739 startCollectionBuf += 3;
1740
1741 // Replace: "for (type element in" with string constructed thus far.
1742 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1743 // Replace ')' in for '(' type elem in collection ')' with ';'
1744 SourceLocation rightParenLoc = S->getRParenLoc();
1745 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1746 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1747 buf = ";\n\t";
1748
1749 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1750 // objects:__rw_items count:16];
1751 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001752 // NSUInteger limit =
1753 // ((NSUInteger (*)
1754 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001755 // (void *)objc_msgSend)((id)l_collection,
1756 // sel_registerName(
1757 // "countByEnumeratingWithState:objects:count:"),
1758 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001759 // (id *)__rw_items, (NSUInteger)16);
1760 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001761 SynthCountByEnumWithState(buf);
1762 buf += ";\n\t";
1763 /// if (limit) {
1764 /// unsigned long startMutations = *enumState.mutationsPtr;
1765 /// do {
1766 /// unsigned long counter = 0;
1767 /// do {
1768 /// if (startMutations != *enumState.mutationsPtr)
1769 /// objc_enumerationMutation(l_collection);
1770 /// elem = (type)enumState.itemsPtr[counter++];
1771 buf += "if (limit) {\n\t";
1772 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1773 buf += "do {\n\t\t";
1774 buf += "unsigned long counter = 0;\n\t\t";
1775 buf += "do {\n\t\t\t";
1776 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1777 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1778 buf += elementName;
1779 buf += " = (";
1780 buf += elementTypeAsString;
1781 buf += ")enumState.itemsPtr[counter++];";
1782 // Replace ')' in for '(' type elem in collection ')' with all of these.
1783 ReplaceText(lparenLoc, 1, buf);
1784
1785 /// __continue_label: ;
1786 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001787 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1788 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001789 /// elem = nil;
1790 /// __break_label: ;
1791 /// }
1792 /// else
1793 /// elem = nil;
1794 /// }
1795 ///
1796 buf = ";\n\t";
1797 buf += "__continue_label_";
1798 buf += utostr(ObjCBcLabelNo.back());
1799 buf += ": ;";
1800 buf += "\n\t\t";
1801 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001802 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001803 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001804 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001805 buf += elementName;
1806 buf += " = ((";
1807 buf += elementTypeAsString;
1808 buf += ")0);\n\t";
1809 buf += "__break_label_";
1810 buf += utostr(ObjCBcLabelNo.back());
1811 buf += ": ;\n\t";
1812 buf += "}\n\t";
1813 buf += "else\n\t\t";
1814 buf += elementName;
1815 buf += " = ((";
1816 buf += elementTypeAsString;
1817 buf += ")0);\n\t";
1818 buf += "}\n";
1819
1820 // Insert all these *after* the statement body.
1821 // FIXME: If this should support Obj-C++, support CXXTryStmt
1822 if (isa<CompoundStmt>(S->getBody())) {
1823 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1824 InsertText(endBodyLoc, buf);
1825 } else {
1826 /* Need to treat single statements specially. For example:
1827 *
1828 * for (A *a in b) if (stuff()) break;
1829 * for (A *a in b) xxxyy;
1830 *
1831 * The following code simply scans ahead to the semi to find the actual end.
1832 */
1833 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1834 const char *semiBuf = strchr(stmtBuf, ';');
1835 assert(semiBuf && "Can't find ';'");
1836 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1837 InsertText(endBodyLoc, buf);
1838 }
1839 Stmts.pop_back();
1840 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001841 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001842}
1843
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001844static void Write_RethrowObject(std::string &buf) {
1845 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1846 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1847 buf += "\tid rethrow;\n";
1848 buf += "\t} _fin_force_rethow(_rethrow);";
1849}
1850
Fariborz Jahanian11671902012-02-07 17:11:38 +00001851/// RewriteObjCSynchronizedStmt -
1852/// This routine rewrites @synchronized(expr) stmt;
1853/// into:
1854/// objc_sync_enter(expr);
1855/// @try stmt @finally { objc_sync_exit(expr); }
1856///
1857Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1858 // Get the start location and compute the semi location.
1859 SourceLocation startLoc = S->getLocStart();
1860 const char *startBuf = SM->getCharacterData(startLoc);
1861
1862 assert((*startBuf == '@') && "bogus @synchronized location");
1863
1864 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001865 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1866 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001867 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001868
Fariborz Jahanian11671902012-02-07 17:11:38 +00001869 const char *lparenBuf = startBuf;
1870 while (*lparenBuf != '(') lparenBuf++;
1871 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001872
1873 buf = "; objc_sync_enter(_sync_obj);\n";
1874 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1875 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1876 buf += "\n\tid sync_exit;";
1877 buf += "\n\t} _sync_exit(_sync_obj);\n";
1878
1879 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1880 // the sync expression is typically a message expression that's already
1881 // been rewritten! (which implies the SourceLocation's are invalid).
1882 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1883 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1884 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1885 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1886
1887 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1888 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1889 assert (*LBraceLocBuf == '{');
1890 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001891
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001892 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001893 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1894 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001895
1896 buf = "} catch (id e) {_rethrow = e;}\n";
1897 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001898 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001899 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001900
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001901 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001902
Craig Topper8ae12032014-05-07 06:21:57 +00001903 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001904}
1905
1906void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1907{
1908 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001909 for (Stmt *SubStmt : S->children())
1910 if (SubStmt)
1911 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001912
1913 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1914 Diags.Report(Context->getFullLoc(S->getLocStart()),
1915 TryFinallyContainsReturnDiag);
1916 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001917}
1918
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001919Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1920 SourceLocation startLoc = S->getAtLoc();
1921 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001922 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1923 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001924
1925 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001926}
1927
Fariborz Jahanian11671902012-02-07 17:11:38 +00001928Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001929 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001930 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001931 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001932 SourceLocation TryLocation = S->getAtTryLoc();
1933 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001934
1935 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001936 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001937 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001938 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001939 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001940 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001941 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001942 // Get the start location and compute the semi location.
1943 SourceLocation startLoc = S->getLocStart();
1944 const char *startBuf = SM->getCharacterData(startLoc);
1945
1946 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001947 if (finalStmt)
1948 ReplaceText(startLoc, 1, buf);
1949 else
1950 // @try -> try
1951 ReplaceText(startLoc, 1, "");
1952
Fariborz Jahanian11671902012-02-07 17:11:38 +00001953 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1954 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001955 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001956
Fariborz Jahanian11671902012-02-07 17:11:38 +00001957 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001958 bool AtRemoved = false;
1959 if (catchDecl) {
1960 QualType t = catchDecl->getType();
1961 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1962 // Should be a pointer to a class.
1963 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1964 if (IDecl) {
1965 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001966 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1967
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001968 startBuf = SM->getCharacterData(startLoc);
1969 assert((*startBuf == '@') && "bogus @catch location");
1970 SourceLocation rParenLoc = Catch->getRParenLoc();
1971 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1972
1973 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001974 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001975 Result += " *_"; Result += catchDecl->getNameAsString();
1976 Result += ")";
1977 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1978 // Foo *e = (Foo *)_e;
1979 Result.clear();
1980 Result = "{ ";
1981 Result += IDecl->getNameAsString();
1982 Result += " *"; Result += catchDecl->getNameAsString();
1983 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1984 Result += "_"; Result += catchDecl->getNameAsString();
1985
1986 Result += "; ";
1987 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1988 ReplaceText(lBraceLoc, 1, Result);
1989 AtRemoved = true;
1990 }
1991 }
1992 }
1993 if (!AtRemoved)
1994 // @catch -> catch
1995 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001996
Fariborz Jahanian11671902012-02-07 17:11:38 +00001997 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001998 if (finalStmt) {
1999 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002000 SourceLocation FinallyLoc = finalStmt->getLocStart();
2001
2002 if (noCatch) {
2003 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2004 buf += "catch (id e) {_rethrow = e;}\n";
2005 }
2006 else {
2007 buf += "}\n";
2008 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2009 buf += "catch (id e) {_rethrow = e;}\n";
2010 }
2011
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002012 SourceLocation startFinalLoc = finalStmt->getLocStart();
2013 ReplaceText(startFinalLoc, 8, buf);
2014 Stmt *body = finalStmt->getFinallyBody();
2015 SourceLocation startFinalBodyLoc = body->getLocStart();
2016 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002017 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002018 ReplaceText(startFinalBodyLoc, 1, buf);
2019
2020 SourceLocation endFinalBodyLoc = body->getLocEnd();
2021 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002022 // Now check for any return/continue/go statements within the @try.
2023 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002024 }
2025
Craig Topper8ae12032014-05-07 06:21:57 +00002026 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002027}
2028
2029// This can't be done with ReplaceStmt(S, ThrowExpr), since
2030// the throw expression is typically a message expression that's already
2031// been rewritten! (which implies the SourceLocation's are invalid).
2032Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2033 // Get the start location and compute the semi location.
2034 SourceLocation startLoc = S->getLocStart();
2035 const char *startBuf = SM->getCharacterData(startLoc);
2036
2037 assert((*startBuf == '@') && "bogus @throw location");
2038
2039 std::string buf;
2040 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2041 if (S->getThrowExpr())
2042 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002043 else
2044 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002045
2046 // handle "@ throw" correctly.
2047 const char *wBuf = strchr(startBuf, 'w');
2048 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2049 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2050
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002051 SourceLocation endLoc = S->getLocEnd();
2052 const char *endBuf = SM->getCharacterData(endLoc);
2053 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002054 assert((*semiBuf == ';') && "@throw: can't find ';'");
2055 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002056 if (S->getThrowExpr())
2057 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002058 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002059}
2060
2061Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2062 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002063 std::string StrEncoding;
2064 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002065 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002066 ReplaceStmt(Exp, Replacement);
2067
2068 // Replace this subexpr in the parent.
2069 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2070 return Replacement;
2071}
2072
2073Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2074 if (!SelGetUidFunctionDecl)
2075 SynthSelGetUidFunctionDecl();
2076 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2077 // Create a call to sel_registerName("selName").
2078 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002079 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002080 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002081 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002082 ReplaceStmt(Exp, SelExp);
2083 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2084 return SelExp;
2085}
2086
Craig Toppercf2126e2015-10-22 03:13:07 +00002087CallExpr *
2088RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2089 ArrayRef<Expr *> Args,
2090 SourceLocation StartLoc,
2091 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002092 // Get the type, we will need to reference it in a couple spots.
2093 QualType msgSendType = FD->getType();
2094
2095 // Create a reference to the objc_msgSend() declaration.
2096 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002097 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002098
2099 // Now, we cast the reference to a pointer to the objc_msgSend type.
2100 QualType pToFunc = Context->getPointerType(msgSendType);
2101 ImplicitCastExpr *ICE =
2102 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002103 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002104
2105 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2106
Craig Toppercf2126e2015-10-22 03:13:07 +00002107 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2108 FT->getCallResultType(*Context),
2109 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002110 return Exp;
2111}
2112
2113static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2114 const char *&startRef, const char *&endRef) {
2115 while (startBuf < endBuf) {
2116 if (*startBuf == '<')
2117 startRef = startBuf; // mark the start.
2118 if (*startBuf == '>') {
2119 if (startRef && *startRef == '<') {
2120 endRef = startBuf; // mark the end.
2121 return true;
2122 }
2123 return false;
2124 }
2125 startBuf++;
2126 }
2127 return false;
2128}
2129
2130static void scanToNextArgument(const char *&argRef) {
2131 int angle = 0;
2132 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2133 if (*argRef == '<')
2134 angle++;
2135 else if (*argRef == '>')
2136 angle--;
2137 argRef++;
2138 }
2139 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2140}
2141
2142bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2143 if (T->isObjCQualifiedIdType())
2144 return true;
2145 if (const PointerType *PT = T->getAs<PointerType>()) {
2146 if (PT->getPointeeType()->isObjCQualifiedIdType())
2147 return true;
2148 }
2149 if (T->isObjCObjectPointerType()) {
2150 T = T->getPointeeType();
2151 return T->isObjCQualifiedInterfaceType();
2152 }
2153 if (T->isArrayType()) {
2154 QualType ElemTy = Context->getBaseElementType(T);
2155 return needToScanForQualifiers(ElemTy);
2156 }
2157 return false;
2158}
2159
2160void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2161 QualType Type = E->getType();
2162 if (needToScanForQualifiers(Type)) {
2163 SourceLocation Loc, EndLoc;
2164
2165 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2166 Loc = ECE->getLParenLoc();
2167 EndLoc = ECE->getRParenLoc();
2168 } else {
2169 Loc = E->getLocStart();
2170 EndLoc = E->getLocEnd();
2171 }
2172 // This will defend against trying to rewrite synthesized expressions.
2173 if (Loc.isInvalid() || EndLoc.isInvalid())
2174 return;
2175
2176 const char *startBuf = SM->getCharacterData(Loc);
2177 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002178 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
2181 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2182 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2183 // Comment out the protocol references.
2184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
2186 }
2187 }
2188}
2189
2190void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2191 SourceLocation Loc;
2192 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002193 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002194 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2195 Loc = VD->getLocation();
2196 Type = VD->getType();
2197 }
2198 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2199 Loc = FD->getLocation();
2200 // Check for ObjC 'id' and class types that have been adorned with protocol
2201 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2202 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203 assert(funcType && "missing function type");
2204 proto = dyn_cast<FunctionProtoType>(funcType);
2205 if (!proto)
2206 return;
Alp Toker314cc812014-01-25 16:55:45 +00002207 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002208 }
2209 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2210 Loc = FD->getLocation();
2211 Type = FD->getType();
2212 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002213 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2214 Loc = TD->getLocation();
2215 Type = TD->getUnderlyingType();
2216 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002217 else
2218 return;
2219
2220 if (needToScanForQualifiers(Type)) {
2221 // Since types are unique, we need to scan the buffer.
2222
2223 const char *endBuf = SM->getCharacterData(Loc);
2224 const char *startBuf = endBuf;
2225 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2226 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002227 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229 // Get the locations of the startRef, endRef.
2230 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2231 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2232 // Comment out the protocol references.
2233 InsertText(LessLoc, "/*");
2234 InsertText(GreaterLoc, "*/");
2235 }
2236 }
2237 if (!proto)
2238 return; // most likely, was a variable
2239 // Now check arguments.
2240 const char *startBuf = SM->getCharacterData(Loc);
2241 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002242 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2243 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002244 // Since types are unique, we need to scan the buffer.
2245
2246 const char *endBuf = startBuf;
2247 // scan forward (from the decl location) for argument types.
2248 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002249 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002250 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2251 // Get the locations of the startRef, endRef.
2252 SourceLocation LessLoc =
2253 Loc.getLocWithOffset(startRef-startFuncBuf);
2254 SourceLocation GreaterLoc =
2255 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2256 // Comment out the protocol references.
2257 InsertText(LessLoc, "/*");
2258 InsertText(GreaterLoc, "*/");
2259 }
2260 startBuf = ++endBuf;
2261 }
2262 else {
2263 // If the function name is derived from a macro expansion, then the
2264 // argument buffer will not follow the name. Need to speak with Chris.
2265 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2266 startBuf++; // scan forward (from the decl location) for argument types.
2267 startBuf++;
2268 }
2269 }
2270}
2271
2272void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2273 QualType QT = ND->getType();
2274 const Type* TypePtr = QT->getAs<Type>();
2275 if (!isa<TypeOfExprType>(TypePtr))
2276 return;
2277 while (isa<TypeOfExprType>(TypePtr)) {
2278 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2279 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2280 TypePtr = QT->getAs<Type>();
2281 }
2282 // FIXME. This will not work for multiple declarators; as in:
2283 // __typeof__(a) b,c,d;
2284 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2285 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2286 const char *startBuf = SM->getCharacterData(DeclLoc);
2287 if (ND->getInit()) {
2288 std::string Name(ND->getNameAsString());
2289 TypeAsString += " " + Name + " = ";
2290 Expr *E = ND->getInit();
2291 SourceLocation startLoc;
2292 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2293 startLoc = ECE->getLParenLoc();
2294 else
2295 startLoc = E->getLocStart();
2296 startLoc = SM->getExpansionLoc(startLoc);
2297 const char *endBuf = SM->getCharacterData(startLoc);
2298 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2299 }
2300 else {
2301 SourceLocation X = ND->getLocEnd();
2302 X = SM->getExpansionLoc(X);
2303 const char *endBuf = SM->getCharacterData(X);
2304 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2305 }
2306}
2307
2308// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2309void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2310 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2311 SmallVector<QualType, 16> ArgTys;
2312 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2313 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002314 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002315 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002316 SourceLocation(),
2317 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002318 SelGetUidIdent, getFuncType,
2319 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002320}
2321
2322void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2323 // declared in <objc/objc.h>
2324 if (FD->getIdentifier() &&
2325 FD->getName() == "sel_registerName") {
2326 SelGetUidFunctionDecl = FD;
2327 return;
2328 }
2329 RewriteObjCQualifiedInterfaceTypes(FD);
2330}
2331
2332void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2333 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2334 const char *argPtr = TypeString.c_str();
2335 if (!strchr(argPtr, '^')) {
2336 Str += TypeString;
2337 return;
2338 }
2339 while (*argPtr) {
2340 Str += (*argPtr == '^' ? '*' : *argPtr);
2341 argPtr++;
2342 }
2343}
2344
2345// FIXME. Consolidate this routine with RewriteBlockPointerType.
2346void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2347 ValueDecl *VD) {
2348 QualType Type = VD->getType();
2349 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2350 const char *argPtr = TypeString.c_str();
2351 int paren = 0;
2352 while (*argPtr) {
2353 switch (*argPtr) {
2354 case '(':
2355 Str += *argPtr;
2356 paren++;
2357 break;
2358 case ')':
2359 Str += *argPtr;
2360 paren--;
2361 break;
2362 case '^':
2363 Str += '*';
2364 if (paren == 1)
2365 Str += VD->getNameAsString();
2366 break;
2367 default:
2368 Str += *argPtr;
2369 break;
2370 }
2371 argPtr++;
2372 }
2373}
2374
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002375void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2376 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2377 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2378 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2379 if (!proto)
2380 return;
Alp Toker314cc812014-01-25 16:55:45 +00002381 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002382 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2383 FdStr += " ";
2384 FdStr += FD->getName();
2385 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002386 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002387 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002388 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002389 RewriteBlockPointerType(FdStr, ArgType);
2390 if (i+1 < numArgs)
2391 FdStr += ", ";
2392 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002393 if (FD->isVariadic()) {
2394 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2395 }
2396 else
2397 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002398 InsertText(FunLocStart, FdStr);
2399}
2400
Benjamin Kramer60509af2013-09-09 14:48:42 +00002401// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2402void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2403 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002404 return;
2405 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2406 SmallVector<QualType, 16> ArgTys;
2407 QualType argT = Context->getObjCIdType();
2408 assert(!argT.isNull() && "Can't find 'id' type");
2409 ArgTys.push_back(argT);
2410 ArgTys.push_back(argT);
2411 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002412 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002413 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002414 SourceLocation(),
2415 SourceLocation(),
2416 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002417 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002418}
2419
2420// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2421void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2422 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2423 SmallVector<QualType, 16> ArgTys;
2424 QualType argT = Context->getObjCIdType();
2425 assert(!argT.isNull() && "Can't find 'id' type");
2426 ArgTys.push_back(argT);
2427 argT = Context->getObjCSelType();
2428 assert(!argT.isNull() && "Can't find 'SEL' type");
2429 ArgTys.push_back(argT);
2430 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002431 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002432 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002433 SourceLocation(),
2434 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002435 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002436 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002437}
2438
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002439// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002440void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2441 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002442 SmallVector<QualType, 2> ArgTys;
2443 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002444 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002445 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002446 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002447 SourceLocation(),
2448 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002449 msgSendIdent, msgSendType,
2450 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002451}
2452
2453// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2454void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2455 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2456 SmallVector<QualType, 16> ArgTys;
2457 QualType argT = Context->getObjCIdType();
2458 assert(!argT.isNull() && "Can't find 'id' type");
2459 ArgTys.push_back(argT);
2460 argT = Context->getObjCSelType();
2461 assert(!argT.isNull() && "Can't find 'SEL' type");
2462 ArgTys.push_back(argT);
2463 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002464 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002465 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002466 SourceLocation(),
2467 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002468 msgSendIdent, msgSendType,
2469 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002470}
2471
2472// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002473// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002474void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2475 IdentifierInfo *msgSendIdent =
2476 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002477 SmallVector<QualType, 2> ArgTys;
2478 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002480 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002481 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2482 SourceLocation(),
2483 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002484 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002485 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002486 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002487}
2488
2489// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2490void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2492 SmallVector<QualType, 16> ArgTys;
2493 QualType argT = Context->getObjCIdType();
2494 assert(!argT.isNull() && "Can't find 'id' type");
2495 ArgTys.push_back(argT);
2496 argT = Context->getObjCSelType();
2497 assert(!argT.isNull() && "Can't find 'SEL' type");
2498 ArgTys.push_back(argT);
2499 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002500 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002501 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002502 SourceLocation(),
2503 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002504 msgSendIdent, msgSendType,
2505 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002506}
2507
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002508// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002509void RewriteModernObjC::SynthGetClassFunctionDecl() {
2510 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2511 SmallVector<QualType, 16> ArgTys;
2512 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002513 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002514 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002515 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002516 SourceLocation(),
2517 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002518 getClassIdent, getClassType,
2519 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002520}
2521
2522// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2523void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2524 IdentifierInfo *getSuperClassIdent =
2525 &Context->Idents.get("class_getSuperclass");
2526 SmallVector<QualType, 16> ArgTys;
2527 ArgTys.push_back(Context->getObjCClassType());
2528 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002529 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002530 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2531 SourceLocation(),
2532 SourceLocation(),
2533 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002534 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002535 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002536}
2537
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002538// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002539void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2540 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2541 SmallVector<QualType, 16> ArgTys;
2542 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002543 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002544 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002545 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002546 SourceLocation(),
2547 SourceLocation(),
2548 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002549 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002550}
2551
2552Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002553 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554 QualType strType = getConstantStringStructType();
2555
2556 std::string S = "__NSConstantStringImpl_";
2557
2558 std::string tmpName = InFileName;
2559 unsigned i;
2560 for (i=0; i < tmpName.length(); i++) {
2561 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002562 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002563 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002564 tmpName[i] = '_';
2565 }
2566 S += tmpName;
2567 S += "_";
2568 S += utostr(NumObjCStringLiterals++);
2569
2570 Preamble += "static __NSConstantStringImpl " + S;
2571 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2572 Preamble += "0x000007c8,"; // utf8_str
2573 // The pretty printer for StringLiteral handles escape characters properly.
2574 std::string prettyBufS;
2575 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002576 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002577 Preamble += prettyBuf.str();
2578 Preamble += ",";
2579 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2580
2581 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2582 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002583 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002584 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002585 SourceLocation());
2586 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2587 Context->getPointerType(DRE->getType()),
2588 VK_RValue, OK_Ordinary,
2589 SourceLocation());
2590 // cast to NSConstantString *
2591 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2592 CK_CPointerToObjCPointerCast, Unop);
2593 ReplaceStmt(Exp, cast);
2594 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2595 return cast;
2596}
2597
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002598Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2599 unsigned IntSize =
2600 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2601
2602 Expr *FlagExp = IntegerLiteral::Create(*Context,
2603 llvm::APInt(IntSize, Exp->getValue()),
2604 Context->IntTy, Exp->getLocation());
2605 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2606 CK_BitCast, FlagExp);
2607 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2608 cast);
2609 ReplaceStmt(Exp, PE);
2610 return PE;
2611}
2612
Patrick Beard0caa3942012-04-19 00:25:12 +00002613Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002614 // synthesize declaration of helper functions needed in this routine.
2615 if (!SelGetUidFunctionDecl)
2616 SynthSelGetUidFunctionDecl();
2617 // use objc_msgSend() for all.
2618 if (!MsgSendFunctionDecl)
2619 SynthMsgSendFunctionDecl();
2620 if (!GetClassFunctionDecl)
2621 SynthGetClassFunctionDecl();
2622
2623 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2624 SourceLocation StartLoc = Exp->getLocStart();
2625 SourceLocation EndLoc = Exp->getLocEnd();
2626
2627 // Synthesize a call to objc_msgSend().
2628 SmallVector<Expr*, 4> MsgExprs;
2629 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002630
Patrick Beard0caa3942012-04-19 00:25:12 +00002631 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2632 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2633 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002634
Patrick Beard0caa3942012-04-19 00:25:12 +00002635 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002636 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002637 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002638 StartLoc, EndLoc);
2639 MsgExprs.push_back(Cls);
2640
Patrick Beard0caa3942012-04-19 00:25:12 +00002641 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002642 // it will be the 2nd argument.
2643 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002644 SelExprs.push_back(
2645 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002646 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002647 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002648 MsgExprs.push_back(SelExp);
2649
Patrick Beard0caa3942012-04-19 00:25:12 +00002650 // User provided sub-expression is the 3rd, and last, argument.
2651 Expr *subExpr = Exp->getSubExpr();
2652 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002653 QualType type = ICE->getType();
2654 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2655 CastKind CK = CK_BitCast;
2656 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2657 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002658 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002659 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002660 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002661
2662 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002663 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002664 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002665 for (const auto PI : BoxingMethod->parameters())
2666 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002667
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002668 QualType returnType = Exp->getType();
2669 // Get the type, we will need to reference it in a couple spots.
2670 QualType msgSendType = MsgSendFlavor->getType();
2671
2672 // Create a reference to the objc_msgSend() declaration.
2673 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2674 VK_LValue, SourceLocation());
2675
2676 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002677 Context->getPointerType(Context->VoidTy),
2678 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002679
2680 // Now do the "normal" pointer to function cast.
2681 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002682 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002683 castType = Context->getPointerType(castType);
2684 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2685 cast);
2686
2687 // Don't forget the parens to enforce the proper binding.
2688 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2689
2690 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002691 CallExpr *CE = new (Context)
2692 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002693 ReplaceStmt(Exp, CE);
2694 return CE;
2695}
2696
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002697Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2698 // synthesize declaration of helper functions needed in this routine.
2699 if (!SelGetUidFunctionDecl)
2700 SynthSelGetUidFunctionDecl();
2701 // use objc_msgSend() for all.
2702 if (!MsgSendFunctionDecl)
2703 SynthMsgSendFunctionDecl();
2704 if (!GetClassFunctionDecl)
2705 SynthGetClassFunctionDecl();
2706
2707 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2708 SourceLocation StartLoc = Exp->getLocStart();
2709 SourceLocation EndLoc = Exp->getLocEnd();
2710
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002711 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002712 QualType IntQT = Context->IntTy;
2713 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002714 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002715 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002716 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2717 DeclRefExpr *NSArrayDRE =
2718 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2719 SourceLocation());
2720
2721 SmallVector<Expr*, 16> InitExprs;
2722 unsigned NumElements = Exp->getNumElements();
2723 unsigned UnsignedIntSize =
2724 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725 Expr *count = IntegerLiteral::Create(*Context,
2726 llvm::APInt(UnsignedIntSize, NumElements),
2727 Context->UnsignedIntTy, SourceLocation());
2728 InitExprs.push_back(count);
2729 for (unsigned i = 0; i < NumElements; i++)
2730 InitExprs.push_back(Exp->getElement(i));
2731 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002732 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002733 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002734
2735 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002736 SourceLocation(),
2737 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002738 Context->getPointerType(Context->VoidPtrTy),
2739 nullptr, /*BitWidth=*/nullptr,
2740 /*Mutable=*/true, ICIS_NoInit);
2741 MemberExpr *ArrayLiteralME = new (Context)
2742 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2743 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2744 QualType ConstIdT = Context->getObjCIdType().withConst();
2745 CStyleCastExpr * ArrayLiteralObjects =
2746 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002747 Context->getPointerType(ConstIdT),
2748 CK_BitCast,
2749 ArrayLiteralME);
2750
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002751 // Synthesize a call to objc_msgSend().
2752 SmallVector<Expr*, 32> MsgExprs;
2753 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002754 QualType expType = Exp->getType();
2755
2756 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2757 ObjCInterfaceDecl *Class =
2758 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2759
2760 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002761 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002762 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002763 StartLoc, EndLoc);
2764 MsgExprs.push_back(Cls);
2765
2766 // Create a call to sel_registerName("arrayWithObjects:count:").
2767 // it will be the 2nd argument.
2768 SmallVector<Expr*, 4> SelExprs;
2769 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002770 SelExprs.push_back(
2771 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002772 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002773 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002774 MsgExprs.push_back(SelExp);
2775
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002776 // (const id [])objects
2777 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002778
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002779 // (NSUInteger)cnt
2780 Expr *cnt = IntegerLiteral::Create(*Context,
2781 llvm::APInt(UnsignedIntSize, NumElements),
2782 Context->UnsignedIntTy, SourceLocation());
2783 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002784
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002785 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002786 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002787 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002788 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002789 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002790
2791 QualType returnType = Exp->getType();
2792 // Get the type, we will need to reference it in a couple spots.
2793 QualType msgSendType = MsgSendFlavor->getType();
2794
2795 // Create a reference to the objc_msgSend() declaration.
2796 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2797 VK_LValue, SourceLocation());
2798
2799 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2800 Context->getPointerType(Context->VoidTy),
2801 CK_BitCast, DRE);
2802
2803 // Now do the "normal" pointer to function cast.
2804 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002805 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002806 castType = Context->getPointerType(castType);
2807 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2808 cast);
2809
2810 // Don't forget the parens to enforce the proper binding.
2811 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2812
2813 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002814 CallExpr *CE = new (Context)
2815 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002816 ReplaceStmt(Exp, CE);
2817 return CE;
2818}
2819
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002820Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2821 // synthesize declaration of helper functions needed in this routine.
2822 if (!SelGetUidFunctionDecl)
2823 SynthSelGetUidFunctionDecl();
2824 // use objc_msgSend() for all.
2825 if (!MsgSendFunctionDecl)
2826 SynthMsgSendFunctionDecl();
2827 if (!GetClassFunctionDecl)
2828 SynthGetClassFunctionDecl();
2829
2830 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2831 SourceLocation StartLoc = Exp->getLocStart();
2832 SourceLocation EndLoc = Exp->getLocEnd();
2833
2834 // Build the expression: __NSContainer_literal(int, ...).arr
2835 QualType IntQT = Context->IntTy;
2836 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002837 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002838 std::string NSDictFName("__NSContainer_literal");
2839 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2840 DeclRefExpr *NSDictDRE =
2841 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2842 SourceLocation());
2843
2844 SmallVector<Expr*, 16> KeyExprs;
2845 SmallVector<Expr*, 16> ValueExprs;
2846
2847 unsigned NumElements = Exp->getNumElements();
2848 unsigned UnsignedIntSize =
2849 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2850 Expr *count = IntegerLiteral::Create(*Context,
2851 llvm::APInt(UnsignedIntSize, NumElements),
2852 Context->UnsignedIntTy, SourceLocation());
2853 KeyExprs.push_back(count);
2854 ValueExprs.push_back(count);
2855 for (unsigned i = 0; i < NumElements; i++) {
2856 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2857 KeyExprs.push_back(Element.Key);
2858 ValueExprs.push_back(Element.Value);
2859 }
2860
2861 // (const id [])objects
2862 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002863 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002864 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002865
2866 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002867 SourceLocation(),
2868 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002869 Context->getPointerType(Context->VoidPtrTy),
2870 nullptr, /*BitWidth=*/nullptr,
2871 /*Mutable=*/true, ICIS_NoInit);
2872 MemberExpr *DictLiteralValueME = new (Context)
2873 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2874 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2875 QualType ConstIdT = Context->getObjCIdType().withConst();
2876 CStyleCastExpr * DictValueObjects =
2877 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002878 Context->getPointerType(ConstIdT),
2879 CK_BitCast,
2880 DictLiteralValueME);
2881 // (const id <NSCopying> [])keys
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002882 Expr *NSKeyCallExpr =
2883 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2884 NSDictFType, VK_LValue, SourceLocation());
2885
2886 MemberExpr *DictLiteralKeyME = new (Context)
2887 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2888 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2889
2890 CStyleCastExpr * DictKeyObjects =
2891 NoTypeInfoCStyleCastExpr(Context,
2892 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002893 CK_BitCast,
2894 DictLiteralKeyME);
2895
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002896 // Synthesize a call to objc_msgSend().
2897 SmallVector<Expr*, 32> MsgExprs;
2898 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002899 QualType expType = Exp->getType();
2900
2901 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2902 ObjCInterfaceDecl *Class =
2903 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2904
2905 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002906 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002907 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002908 StartLoc, EndLoc);
2909 MsgExprs.push_back(Cls);
2910
2911 // Create a call to sel_registerName("arrayWithObjects:count:").
2912 // it will be the 2nd argument.
2913 SmallVector<Expr*, 4> SelExprs;
2914 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002915 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002916 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002917 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 MsgExprs.push_back(SelExp);
2919
2920 // (const id [])objects
2921 MsgExprs.push_back(DictValueObjects);
2922
2923 // (const id <NSCopying> [])keys
2924 MsgExprs.push_back(DictKeyObjects);
2925
2926 // (NSUInteger)cnt
2927 Expr *cnt = IntegerLiteral::Create(*Context,
2928 llvm::APInt(UnsignedIntSize, NumElements),
2929 Context->UnsignedIntTy, SourceLocation());
2930 MsgExprs.push_back(cnt);
2931
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002932 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002933 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002934 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002935 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002936 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002937 if (const PointerType* PT = T->getAs<PointerType>()) {
2938 QualType PointeeTy = PT->getPointeeType();
2939 convertToUnqualifiedObjCType(PointeeTy);
2940 T = Context->getPointerType(PointeeTy);
2941 }
2942 ArgTypes.push_back(T);
2943 }
2944
2945 QualType returnType = Exp->getType();
2946 // Get the type, we will need to reference it in a couple spots.
2947 QualType msgSendType = MsgSendFlavor->getType();
2948
2949 // Create a reference to the objc_msgSend() declaration.
2950 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2951 VK_LValue, SourceLocation());
2952
2953 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2954 Context->getPointerType(Context->VoidTy),
2955 CK_BitCast, DRE);
2956
2957 // Now do the "normal" pointer to function cast.
2958 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002959 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002960 castType = Context->getPointerType(castType);
2961 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2962 cast);
2963
2964 // Don't forget the parens to enforce the proper binding.
2965 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2966
2967 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002968 CallExpr *CE = new (Context)
2969 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002970 ReplaceStmt(Exp, CE);
2971 return CE;
2972}
2973
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002974// struct __rw_objc_super {
2975// struct objc_object *object; struct objc_object *superClass;
2976// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002977QualType RewriteModernObjC::getSuperStructType() {
2978 if (!SuperStructDecl) {
2979 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2980 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002981 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002982 QualType FieldTypes[2];
2983
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002984 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002985 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002986 // struct objc_object *superClass;
2987 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002988
2989 // Create fields
2990 for (unsigned i = 0; i < 2; ++i) {
2991 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2992 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002993 SourceLocation(), nullptr,
2994 FieldTypes[i], nullptr,
2995 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002996 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002997 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002998 }
2999
3000 SuperStructDecl->completeDefinition();
3001 }
3002 return Context->getTagDeclType(SuperStructDecl);
3003}
3004
3005QualType RewriteModernObjC::getConstantStringStructType() {
3006 if (!ConstantStringDecl) {
3007 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3008 SourceLocation(), SourceLocation(),
3009 &Context->Idents.get("__NSConstantStringImpl"));
3010 QualType FieldTypes[4];
3011
3012 // struct objc_object *receiver;
3013 FieldTypes[0] = Context->getObjCIdType();
3014 // int flags;
3015 FieldTypes[1] = Context->IntTy;
3016 // char *str;
3017 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3018 // long length;
3019 FieldTypes[3] = Context->LongTy;
3020
3021 // Create fields
3022 for (unsigned i = 0; i < 4; ++i) {
3023 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3024 ConstantStringDecl,
3025 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003026 SourceLocation(), nullptr,
3027 FieldTypes[i], nullptr,
3028 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003029 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003030 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003031 }
3032
3033 ConstantStringDecl->completeDefinition();
3034 }
3035 return Context->getTagDeclType(ConstantStringDecl);
3036}
3037
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003038/// getFunctionSourceLocation - returns start location of a function
3039/// definition. Complication arises when function has declared as
3040/// extern "C" or extern "C" {...}
3041static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3042 FunctionDecl *FD) {
3043 if (FD->isExternC() && !FD->isMain()) {
3044 const DeclContext *DC = FD->getDeclContext();
3045 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3046 // if it is extern "C" {...}, return function decl's own location.
3047 if (!LSD->getRBraceLoc().isValid())
3048 return LSD->getExternLoc();
3049 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003050 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003051 R.RewriteBlockLiteralFunctionDecl(FD);
3052 return FD->getTypeSpecStartLoc();
3053}
3054
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003055void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3056
3057 SourceLocation Location = D->getLocation();
3058
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003059 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003060 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003061 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3062 LineString += utostr(PLoc.getLine());
3063 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003064 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003065 if (isa<ObjCMethodDecl>(D))
3066 LineString += "\"";
3067 else LineString += "\"\n";
3068
3069 Location = D->getLocStart();
3070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3071 if (FD->isExternC() && !FD->isMain()) {
3072 const DeclContext *DC = FD->getDeclContext();
3073 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3074 // if it is extern "C" {...}, return function decl's own location.
3075 if (!LSD->getRBraceLoc().isValid())
3076 Location = LSD->getExternLoc();
3077 }
3078 }
3079 InsertText(Location, LineString);
3080 }
3081}
3082
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003083/// SynthMsgSendStretCallExpr - This routine translates message expression
3084/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3085/// nil check on receiver must be performed before calling objc_msgSend_stret.
3086/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3087/// msgSendType - function type of objc_msgSend_stret(...)
3088/// returnType - Result type of the method being synthesized.
3089/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3090/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3091/// starting with receiver.
3092/// Method - Method being rewritten.
3093Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003094 QualType returnType,
3095 SmallVectorImpl<QualType> &ArgTypes,
3096 SmallVectorImpl<Expr*> &MsgExprs,
3097 ObjCMethodDecl *Method) {
3098 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003099 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3100 Method ? Method->isVariadic()
3101 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003102 castType = Context->getPointerType(castType);
3103
3104 // build type for containing the objc_msgSend_stret object.
3105 static unsigned stretCount=0;
3106 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003107 std::string str =
3108 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003109 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003110 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003111 str += " {\n\t";
3112 str += name;
3113 str += "(id receiver, SEL sel";
3114 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003115 std::string ArgName = "arg"; ArgName += utostr(i);
3116 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3117 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003118 }
3119 // could be vararg.
3120 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003121 std::string ArgName = "arg"; ArgName += utostr(i);
3122 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3123 Context->getPrintingPolicy());
3124 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003125 }
3126
3127 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003128 str += "\t unsigned size = sizeof(";
3129 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3130
3131 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3132
3133 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3134 str += ")(void *)objc_msgSend)(receiver, sel";
3135 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3136 str += ", arg"; str += utostr(i);
3137 }
3138 // could be vararg.
3139 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3140 str += ", arg"; str += utostr(i);
3141 }
3142 str+= ");\n";
3143
3144 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003145 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3146 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003147
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003148 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3149 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3150 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3151 str += ", arg"; str += utostr(i);
3152 }
3153 // could be vararg.
3154 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3155 str += ", arg"; str += utostr(i);
3156 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003157 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003158
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003159 str += "\t}\n";
3160 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3161 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003162 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003163 SourceLocation FunLocStart;
3164 if (CurFunctionDef)
3165 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3166 else {
3167 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3168 FunLocStart = CurMethodDef->getLocStart();
3169 }
3170
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003171 InsertText(FunLocStart, str);
3172 ++stretCount;
3173
3174 // AST for __Stretn(receiver, args).s;
3175 IdentifierInfo *ID = &Context->Idents.get(name);
3176 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003177 SourceLocation(), ID, castType,
3178 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003179 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3180 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003181 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003182 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003183
3184 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003185 SourceLocation(),
3186 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003187 returnType, nullptr,
3188 /*BitWidth=*/nullptr,
3189 /*Mutable=*/true, ICIS_NoInit);
3190 MemberExpr *ME = new (Context)
3191 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3192 FieldD->getType(), VK_LValue, OK_Ordinary);
3193
3194 return ME;
3195}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003196
Fariborz Jahanian11671902012-02-07 17:11:38 +00003197Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3198 SourceLocation StartLoc,
3199 SourceLocation EndLoc) {
3200 if (!SelGetUidFunctionDecl)
3201 SynthSelGetUidFunctionDecl();
3202 if (!MsgSendFunctionDecl)
3203 SynthMsgSendFunctionDecl();
3204 if (!MsgSendSuperFunctionDecl)
3205 SynthMsgSendSuperFunctionDecl();
3206 if (!MsgSendStretFunctionDecl)
3207 SynthMsgSendStretFunctionDecl();
3208 if (!MsgSendSuperStretFunctionDecl)
3209 SynthMsgSendSuperStretFunctionDecl();
3210 if (!MsgSendFpretFunctionDecl)
3211 SynthMsgSendFpretFunctionDecl();
3212 if (!GetClassFunctionDecl)
3213 SynthGetClassFunctionDecl();
3214 if (!GetSuperClassFunctionDecl)
3215 SynthGetSuperClassFunctionDecl();
3216 if (!GetMetaClassFunctionDecl)
3217 SynthGetMetaClassFunctionDecl();
3218
3219 // default to objc_msgSend().
3220 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3221 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003222 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003223 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003224 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003225 if (resultType->isRecordType())
3226 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3227 else if (resultType->isRealFloatingType())
3228 MsgSendFlavor = MsgSendFpretFunctionDecl;
3229 }
3230
3231 // Synthesize a call to objc_msgSend().
3232 SmallVector<Expr*, 8> MsgExprs;
3233 switch (Exp->getReceiverKind()) {
3234 case ObjCMessageExpr::SuperClass: {
3235 MsgSendFlavor = MsgSendSuperFunctionDecl;
3236 if (MsgSendStretFlavor)
3237 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3238 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3239
3240 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3241
3242 SmallVector<Expr*, 4> InitExprs;
3243
3244 // set the receiver to self, the first argument to all methods.
3245 InitExprs.push_back(
3246 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3247 CK_BitCast,
3248 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003249 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003250 Context->getObjCIdType(),
3251 VK_RValue,
3252 SourceLocation()))
3253 ); // set the 'receiver'.
3254
3255 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3256 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003257 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003258 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003259 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003260 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003261 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003262 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003263 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003264 StartLoc, EndLoc);
3265
3266 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3267 // To turn off a warning, type-cast to 'id'
3268 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3269 NoTypeInfoCStyleCastExpr(Context,
3270 Context->getObjCIdType(),
3271 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003272 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003273 QualType superType = getSuperStructType();
3274 Expr *SuperRep;
3275
3276 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003277 SynthSuperConstructorFunctionDecl();
3278 // Simulate a constructor call...
3279 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003280 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003281 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003282 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003283 superType, VK_LValue,
3284 SourceLocation());
3285 // The code for super is a little tricky to prevent collision with
3286 // the structure definition in the header. The rewriter has it's own
3287 // internal definition (__rw_objc_super) that is uses. This is why
3288 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003289 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003290 //
3291 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3292 Context->getPointerType(SuperRep->getType()),
3293 VK_RValue, OK_Ordinary,
3294 SourceLocation());
3295 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3296 Context->getPointerType(superType),
3297 CK_BitCast, SuperRep);
3298 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003299 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003300 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003301 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003302 SourceLocation());
3303 TypeSourceInfo *superTInfo
3304 = Context->getTrivialTypeSourceInfo(superType);
3305 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3306 superType, VK_LValue,
3307 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003308 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003309 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3310 Context->getPointerType(SuperRep->getType()),
3311 VK_RValue, OK_Ordinary,
3312 SourceLocation());
3313 }
3314 MsgExprs.push_back(SuperRep);
3315 break;
3316 }
3317
3318 case ObjCMessageExpr::Class: {
3319 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003320 ObjCInterfaceDecl *Class
3321 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3322 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003323 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003324 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003325 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003326 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3327 Context->getObjCIdType(),
3328 CK_BitCast, Cls);
3329 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003330 break;
3331 }
3332
3333 case ObjCMessageExpr::SuperInstance:{
3334 MsgSendFlavor = MsgSendSuperFunctionDecl;
3335 if (MsgSendStretFlavor)
3336 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3337 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3338 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3339 SmallVector<Expr*, 4> InitExprs;
3340
3341 InitExprs.push_back(
3342 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3343 CK_BitCast,
3344 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003345 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003346 Context->getObjCIdType(),
3347 VK_RValue, SourceLocation()))
3348 ); // set the 'receiver'.
3349
3350 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3351 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003352 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003353 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003354 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003355 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003356 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003357 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003358 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003359 StartLoc, EndLoc);
3360
3361 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3362 // To turn off a warning, type-cast to 'id'
3363 InitExprs.push_back(
3364 // set 'super class', using class_getSuperclass().
3365 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3366 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003367 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003368 QualType superType = getSuperStructType();
3369 Expr *SuperRep;
3370
3371 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003372 SynthSuperConstructorFunctionDecl();
3373 // Simulate a constructor call...
3374 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003375 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003376 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003377 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 superType, VK_LValue, SourceLocation());
3379 // The code for super is a little tricky to prevent collision with
3380 // the structure definition in the header. The rewriter has it's own
3381 // internal definition (__rw_objc_super) that is uses. This is why
3382 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003383 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003384 //
3385 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3386 Context->getPointerType(SuperRep->getType()),
3387 VK_RValue, OK_Ordinary,
3388 SourceLocation());
3389 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3390 Context->getPointerType(superType),
3391 CK_BitCast, SuperRep);
3392 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003393 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003394 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003395 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003396 SourceLocation());
3397 TypeSourceInfo *superTInfo
3398 = Context->getTrivialTypeSourceInfo(superType);
3399 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3400 superType, VK_RValue, ILE,
3401 false);
3402 }
3403 MsgExprs.push_back(SuperRep);
3404 break;
3405 }
3406
3407 case ObjCMessageExpr::Instance: {
3408 // Remove all type-casts because it may contain objc-style types; e.g.
3409 // Foo<Proto> *.
3410 Expr *recExpr = Exp->getInstanceReceiver();
3411 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3412 recExpr = CE->getSubExpr();
3413 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3414 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3415 ? CK_BlockPointerToObjCPointerCast
3416 : CK_CPointerToObjCPointerCast;
3417
3418 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3419 CK, recExpr);
3420 MsgExprs.push_back(recExpr);
3421 break;
3422 }
3423 }
3424
3425 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3426 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003427 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003428 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003429 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003430 MsgExprs.push_back(SelExp);
3431
3432 // Now push any user supplied arguments.
3433 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3434 Expr *userExpr = Exp->getArg(i);
3435 // Make all implicit casts explicit...ICE comes in handy:-)
3436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3437 // Reuse the ICE type, it is exactly what the doctor ordered.
3438 QualType type = ICE->getType();
3439 if (needToScanForQualifiers(type))
3440 type = Context->getObjCIdType();
3441 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3442 (void)convertBlockPointerToFunctionPointer(type);
3443 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3444 CastKind CK;
3445 if (SubExpr->getType()->isIntegralType(*Context) &&
3446 type->isBooleanType()) {
3447 CK = CK_IntegralToBoolean;
3448 } else if (type->isObjCObjectPointerType()) {
3449 if (SubExpr->getType()->isBlockPointerType()) {
3450 CK = CK_BlockPointerToObjCPointerCast;
3451 } else if (SubExpr->getType()->isPointerType()) {
3452 CK = CK_CPointerToObjCPointerCast;
3453 } else {
3454 CK = CK_BitCast;
3455 }
3456 } else {
3457 CK = CK_BitCast;
3458 }
3459
3460 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3461 }
3462 // Make id<P...> cast into an 'id' cast.
3463 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3464 if (CE->getType()->isObjCQualifiedIdType()) {
3465 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3466 userExpr = CE->getSubExpr();
3467 CastKind CK;
3468 if (userExpr->getType()->isIntegralType(*Context)) {
3469 CK = CK_IntegralToPointer;
3470 } else if (userExpr->getType()->isBlockPointerType()) {
3471 CK = CK_BlockPointerToObjCPointerCast;
3472 } else if (userExpr->getType()->isPointerType()) {
3473 CK = CK_CPointerToObjCPointerCast;
3474 } else {
3475 CK = CK_BitCast;
3476 }
3477 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3478 CK, userExpr);
3479 }
3480 }
3481 MsgExprs.push_back(userExpr);
3482 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3483 // out the argument in the original expression (since we aren't deleting
3484 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3485 //Exp->setArg(i, 0);
3486 }
3487 // Generate the funky cast.
3488 CastExpr *cast;
3489 SmallVector<QualType, 8> ArgTypes;
3490 QualType returnType;
3491
3492 // Push 'id' and 'SEL', the 2 implicit arguments.
3493 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3494 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3495 else
3496 ArgTypes.push_back(Context->getObjCIdType());
3497 ArgTypes.push_back(Context->getObjCSelType());
3498 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3499 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003500 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003501 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003502 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003503 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003504 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3505 (void)convertBlockPointerToFunctionPointer(t);
3506 ArgTypes.push_back(t);
3507 }
3508 returnType = Exp->getType();
3509 convertToUnqualifiedObjCType(returnType);
3510 (void)convertBlockPointerToFunctionPointer(returnType);
3511 } else {
3512 returnType = Context->getObjCIdType();
3513 }
3514 // Get the type, we will need to reference it in a couple spots.
3515 QualType msgSendType = MsgSendFlavor->getType();
3516
3517 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003518 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003519 VK_LValue, SourceLocation());
3520
3521 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3522 // If we don't do this cast, we get the following bizarre warning/note:
3523 // xx.m:13: warning: function called through a non-compatible type
3524 // xx.m:13: note: if this code is reached, the program will abort
3525 cast = NoTypeInfoCStyleCastExpr(Context,
3526 Context->getPointerType(Context->VoidTy),
3527 CK_BitCast, DRE);
3528
3529 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003530 // If we don't have a method decl, force a variadic cast.
3531 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003532 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003533 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003534 castType = Context->getPointerType(castType);
3535 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3536 cast);
3537
3538 // Don't forget the parens to enforce the proper binding.
3539 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3540
3541 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003542 CallExpr *CE = new (Context)
3543 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003544 Stmt *ReplacingStmt = CE;
3545 if (MsgSendStretFlavor) {
3546 // We have the method which returns a struct/union. Must also generate
3547 // call to objc_msgSend_stret and hang both varieties on a conditional
3548 // expression which dictate which one to envoke depending on size of
3549 // method's return type.
3550
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003551 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3552 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003553 ArgTypes, MsgExprs,
3554 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003555 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003556 }
3557 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3558 return ReplacingStmt;
3559}
3560
3561Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3562 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3563 Exp->getLocEnd());
3564
3565 // Now do the actual rewrite.
3566 ReplaceStmt(Exp, ReplacingStmt);
3567
3568 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3569 return ReplacingStmt;
3570}
3571
3572// typedef struct objc_object Protocol;
3573QualType RewriteModernObjC::getProtocolType() {
3574 if (!ProtocolTypeDecl) {
3575 TypeSourceInfo *TInfo
3576 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3577 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3578 SourceLocation(), SourceLocation(),
3579 &Context->Idents.get("Protocol"),
3580 TInfo);
3581 }
3582 return Context->getTypeDeclType(ProtocolTypeDecl);
3583}
3584
3585/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3586/// a synthesized/forward data reference (to the protocol's metadata).
3587/// The forward references (and metadata) are generated in
3588/// RewriteModernObjC::HandleTranslationUnit().
3589Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003590 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3591 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003592 IdentifierInfo *ID = &Context->Idents.get(Name);
3593 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003594 SourceLocation(), ID, getProtocolType(),
3595 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003596 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3597 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003598 CastExpr *castExpr =
3599 NoTypeInfoCStyleCastExpr(
3600 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003601 ReplaceStmt(Exp, castExpr);
3602 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3603 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3604 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003605}
3606
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003607/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3608/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003609bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003610 TagDecl *Tag,
3611 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003612 if (!IDecl)
3613 return false;
3614 SourceLocation TagLocation;
3615 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3616 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003617 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003618 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003619 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003620 TagLocation = RD->getLocation();
3621 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003622 IDecl->getLocation(), TagLocation);
3623 }
3624 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3625 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3626 return false;
3627 IsNamedDefinition = true;
3628 TagLocation = ED->getLocation();
3629 return Context->getSourceManager().isBeforeInTranslationUnit(
3630 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003631 }
3632 return false;
3633}
3634
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003635/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003636/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003637bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3638 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003639 if (isa<TypedefType>(Type)) {
3640 Result += "\t";
3641 return false;
3642 }
3643
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003644 if (Type->isArrayType()) {
3645 QualType ElemTy = Context->getBaseElementType(Type);
3646 return RewriteObjCFieldDeclType(ElemTy, Result);
3647 }
3648 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003649 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3650 if (RD->isCompleteDefinition()) {
3651 if (RD->isStruct())
3652 Result += "\n\tstruct ";
3653 else if (RD->isUnion())
3654 Result += "\n\tunion ";
3655 else
3656 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003657
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003658 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003659 if (GlobalDefinedTags.count(RD)) {
3660 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003661 Result += " ";
3662 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003663 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003664 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003665 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003666 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003667 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003668 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003669 }
3670 }
3671 else if (Type->isEnumeralType()) {
3672 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3673 if (ED->isCompleteDefinition()) {
3674 Result += "\n\tenum ";
3675 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003676 if (GlobalDefinedTags.count(ED)) {
3677 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003678 Result += " ";
3679 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003680 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003681
3682 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003683 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003684 Result += "\t"; Result += EC->getName(); Result += " = ";
3685 llvm::APSInt Val = EC->getInitVal();
3686 Result += Val.toString(10);
3687 Result += ",\n";
3688 }
3689 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003690 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003691 }
3692 }
3693
3694 Result += "\t";
3695 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003696 return false;
3697}
3698
3699
3700/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3701/// It handles elaborated types, as well as enum types in the process.
3702void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3703 std::string &Result) {
3704 QualType Type = fieldDecl->getType();
3705 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003706
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003707 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3708 if (!EleboratedType)
3709 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003710 Result += Name;
3711 if (fieldDecl->isBitField()) {
3712 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3713 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003714 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003715 const ArrayType *AT = Context->getAsArrayType(Type);
3716 do {
3717 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003718 Result += "[";
3719 llvm::APInt Dim = CAT->getSize();
3720 Result += utostr(Dim.getZExtValue());
3721 Result += "]";
3722 }
Eli Friedman07bab732012-12-13 01:43:21 +00003723 AT = Context->getAsArrayType(AT->getElementType());
3724 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003725 }
3726
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003727 Result += ";\n";
3728}
3729
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003730/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3731/// named aggregate types into the input buffer.
3732void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3733 std::string &Result) {
3734 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003735 if (isa<TypedefType>(Type))
3736 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003737 if (Type->isArrayType())
3738 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003739 ObjCContainerDecl *IDecl =
3740 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003741
3742 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003743 if (Type->isRecordType()) {
3744 TD = Type->getAs<RecordType>()->getDecl();
3745 }
3746 else if (Type->isEnumeralType()) {
3747 TD = Type->getAs<EnumType>()->getDecl();
3748 }
3749
3750 if (TD) {
3751 if (GlobalDefinedTags.count(TD))
3752 return;
3753
3754 bool IsNamedDefinition = false;
3755 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3756 RewriteObjCFieldDeclType(Type, Result);
3757 Result += ";";
3758 }
3759 if (IsNamedDefinition)
3760 GlobalDefinedTags.insert(TD);
3761 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003762}
3763
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003764unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3765 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3766 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3767 return IvarGroupNumber[IV];
3768 }
3769 unsigned GroupNo = 0;
3770 SmallVector<const ObjCIvarDecl *, 8> IVars;
3771 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3772 IVD; IVD = IVD->getNextIvar())
3773 IVars.push_back(IVD);
3774
3775 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3776 if (IVars[i]->isBitField()) {
3777 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3778 while (i < e && IVars[i]->isBitField())
3779 IvarGroupNumber[IVars[i++]] = GroupNo;
3780 if (i < e)
3781 --i;
3782 }
3783
3784 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3785 return IvarGroupNumber[IV];
3786}
3787
3788QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3789 ObjCIvarDecl *IV,
3790 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3791 std::string StructTagName;
3792 ObjCIvarBitfieldGroupType(IV, StructTagName);
3793 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3794 Context->getTranslationUnitDecl(),
3795 SourceLocation(), SourceLocation(),
3796 &Context->Idents.get(StructTagName));
3797 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3798 ObjCIvarDecl *Ivar = IVars[i];
3799 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3800 &Context->Idents.get(Ivar->getName()),
3801 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003802 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3803 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003804 }
3805 RD->completeDefinition();
3806 return Context->getTagDeclType(RD);
3807}
3808
3809QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3810 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3811 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3812 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3813 if (GroupRecordType.count(tuple))
3814 return GroupRecordType[tuple];
3815
3816 SmallVector<ObjCIvarDecl *, 8> IVars;
3817 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3818 IVD; IVD = IVD->getNextIvar()) {
3819 if (IVD->isBitField())
3820 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3821 else {
3822 if (!IVars.empty()) {
3823 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3824 // Generate the struct type for this group of bitfield ivars.
3825 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3826 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3827 IVars.clear();
3828 }
3829 }
3830 }
3831 if (!IVars.empty()) {
3832 // Do the last one.
3833 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3834 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3835 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3836 }
3837 QualType RetQT = GroupRecordType[tuple];
3838 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3839
3840 return RetQT;
3841}
3842
3843/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3844/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3845void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3846 std::string &Result) {
3847 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3848 Result += CDecl->getName();
3849 Result += "__GRBF_";
3850 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3851 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003852}
3853
3854/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3855/// Name of the struct would be: classname__T_n where n is the group number for
3856/// this ivar.
3857void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3858 std::string &Result) {
3859 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3860 Result += CDecl->getName();
3861 Result += "__T_";
3862 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3863 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003864}
3865
3866/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3867/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3868/// this ivar.
3869void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3870 std::string &Result) {
3871 Result += "OBJC_IVAR_$_";
3872 ObjCIvarBitfieldGroupDecl(IV, Result);
3873}
3874
3875#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3876 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3877 ++IX; \
3878 if (IX < ENDIX) \
3879 --IX; \
3880}
3881
Fariborz Jahanian11671902012-02-07 17:11:38 +00003882/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3883/// an objective-c class with ivars.
3884void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3885 std::string &Result) {
3886 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3887 assert(CDecl->getName() != "" &&
3888 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003889 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003890 SmallVector<ObjCIvarDecl *, 8> IVars;
3891 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003892 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003893 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003894
Fariborz Jahanian11671902012-02-07 17:11:38 +00003895 SourceLocation LocStart = CDecl->getLocStart();
3896 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003897
Fariborz Jahanian11671902012-02-07 17:11:38 +00003898 const char *startBuf = SM->getCharacterData(LocStart);
3899 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003900
Fariborz Jahanian11671902012-02-07 17:11:38 +00003901 // If no ivars and no root or if its root, directly or indirectly,
3902 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003903 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003904 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3905 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3906 ReplaceText(LocStart, endBuf-startBuf, Result);
3907 return;
3908 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003909
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003910 // Insert named struct/union definitions inside class to
3911 // outer scope. This follows semantics of locally defined
3912 // struct/unions in objective-c classes.
3913 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3914 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003915
3916 // Insert named structs which are syntheized to group ivar bitfields
3917 // to outer scope as well.
3918 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3919 if (IVars[i]->isBitField()) {
3920 ObjCIvarDecl *IV = IVars[i];
3921 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3922 RewriteObjCFieldDeclType(QT, Result);
3923 Result += ";";
3924 // skip over ivar bitfields in this group.
3925 SKIP_BITFIELDS(i , e, IVars);
3926 }
3927
Fariborz Jahanian11671902012-02-07 17:11:38 +00003928 Result += "\nstruct ";
3929 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003930 Result += "_IMPL {\n";
3931
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003932 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003933 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3934 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3935 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003936 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003937
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003938 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3939 if (IVars[i]->isBitField()) {
3940 ObjCIvarDecl *IV = IVars[i];
3941 Result += "\tstruct ";
3942 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3943 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3944 // skip over ivar bitfields in this group.
3945 SKIP_BITFIELDS(i , e, IVars);
3946 }
3947 else
3948 RewriteObjCFieldDecl(IVars[i], Result);
3949 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003950
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003951 Result += "};\n";
3952 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3953 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003954 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003955 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003956 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003957}
3958
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003959/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3960/// have been referenced in an ivar access expression.
3961void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3962 std::string &Result) {
3963 // write out ivar offset symbols which have been referenced in an ivar
3964 // access expression.
3965 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3966 if (Ivars.empty())
3967 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003968
3969 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003970 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003971 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3972 unsigned GroupNo = 0;
3973 if (IvarDecl->isBitField()) {
3974 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3975 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3976 continue;
3977 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003978 Result += "\n";
3979 if (LangOpts.MicrosoftExt)
3980 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003981 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003982 if (LangOpts.MicrosoftExt &&
3983 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003984 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3985 Result += "__declspec(dllimport) ";
3986
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003987 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003988 if (IvarDecl->isBitField()) {
3989 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3990 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3991 }
3992 else
3993 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003994 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003995 }
3996}
3997
Fariborz Jahanian11671902012-02-07 17:11:38 +00003998//===----------------------------------------------------------------------===//
3999// Meta Data Emission
4000//===----------------------------------------------------------------------===//
4001
Fariborz Jahanian11671902012-02-07 17:11:38 +00004002/// RewriteImplementations - This routine rewrites all method implementations
4003/// and emits meta-data.
4004
4005void RewriteModernObjC::RewriteImplementations() {
4006 int ClsDefCount = ClassImplementation.size();
4007 int CatDefCount = CategoryImplementation.size();
4008
4009 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004010 for (int i = 0; i < ClsDefCount; i++) {
4011 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4012 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4013 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004014 assert(false &&
4015 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004016 RewriteImplementationDecl(OIMP);
4017 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004018
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004019 for (int i = 0; i < CatDefCount; i++) {
4020 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4021 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4022 if (CDecl->isImplicitInterfaceDecl())
4023 assert(false &&
4024 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004025 RewriteImplementationDecl(CIMP);
4026 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004027}
4028
4029void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4030 const std::string &Name,
4031 ValueDecl *VD, bool def) {
4032 assert(BlockByRefDeclNo.count(VD) &&
4033 "RewriteByRefString: ByRef decl missing");
4034 if (def)
4035 ResultStr += "struct ";
4036 ResultStr += "__Block_byref_" + Name +
4037 "_" + utostr(BlockByRefDeclNo[VD]) ;
4038}
4039
4040static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4041 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4042 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4043 return false;
4044}
4045
4046std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4047 StringRef funcName,
4048 std::string Tag) {
4049 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004050 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004051 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004052 SourceLocation BlockLoc = CE->getExprLoc();
4053 std::string S;
4054 ConvertSourceLocationToLineDirective(BlockLoc, S);
4055
4056 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4057 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004058
4059 BlockDecl *BD = CE->getBlockDecl();
4060
4061 if (isa<FunctionNoProtoType>(AFT)) {
4062 // No user-supplied arguments. Still need to pass in a pointer to the
4063 // block (to reference imported block decl refs).
4064 S += "(" + StructRef + " *__cself)";
4065 } else if (BD->param_empty()) {
4066 S += "(" + StructRef + " *__cself)";
4067 } else {
4068 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4069 assert(FT && "SynthesizeBlockFunc: No function proto");
4070 S += '(';
4071 // first add the implicit argument.
4072 S += StructRef + " *__cself, ";
4073 std::string ParamStr;
4074 for (BlockDecl::param_iterator AI = BD->param_begin(),
4075 E = BD->param_end(); AI != E; ++AI) {
4076 if (AI != BD->param_begin()) S += ", ";
4077 ParamStr = (*AI)->getNameAsString();
4078 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004079 (void)convertBlockPointerToFunctionPointer(QT);
4080 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004081 S += ParamStr;
4082 }
4083 if (FT->isVariadic()) {
4084 if (!BD->param_empty()) S += ", ";
4085 S += "...";
4086 }
4087 S += ')';
4088 }
4089 S += " {\n";
4090
4091 // Create local declarations to avoid rewriting all closure decl ref exprs.
4092 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004093 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004094 E = BlockByRefDecls.end(); I != E; ++I) {
4095 S += " ";
4096 std::string Name = (*I)->getNameAsString();
4097 std::string TypeString;
4098 RewriteByRefString(TypeString, Name, (*I));
4099 TypeString += " *";
4100 Name = TypeString + Name;
4101 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4102 }
4103 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004104 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004105 E = BlockByCopyDecls.end(); I != E; ++I) {
4106 S += " ";
4107 // Handle nested closure invocation. For example:
4108 //
4109 // void (^myImportedClosure)(void);
4110 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4111 //
4112 // void (^anotherClosure)(void);
4113 // anotherClosure = ^(void) {
4114 // myImportedClosure(); // import and invoke the closure
4115 // };
4116 //
4117 if (isTopLevelBlockPointerType((*I)->getType())) {
4118 RewriteBlockPointerTypeVariable(S, (*I));
4119 S += " = (";
4120 RewriteBlockPointerType(S, (*I)->getType());
4121 S += ")";
4122 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4123 }
4124 else {
4125 std::string Name = (*I)->getNameAsString();
4126 QualType QT = (*I)->getType();
4127 if (HasLocalVariableExternalStorage(*I))
4128 QT = Context->getPointerType(QT);
4129 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4130 S += Name + " = __cself->" +
4131 (*I)->getNameAsString() + "; // bound by copy\n";
4132 }
4133 }
4134 std::string RewrittenStr = RewrittenBlockExprs[CE];
4135 const char *cstr = RewrittenStr.c_str();
4136 while (*cstr++ != '{') ;
4137 S += cstr;
4138 S += "\n";
4139 return S;
4140}
4141
4142std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4143 StringRef funcName,
4144 std::string Tag) {
4145 std::string StructRef = "struct " + Tag;
4146 std::string S = "static void __";
4147
4148 S += funcName;
4149 S += "_block_copy_" + utostr(i);
4150 S += "(" + StructRef;
4151 S += "*dst, " + StructRef;
4152 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004153 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004154 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004155 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004156 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004157 S += VD->getNameAsString();
4158 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4160 else if (VD->getType()->isBlockPointerType())
4161 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4162 else
4163 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4164 }
4165 S += "}\n";
4166
4167 S += "\nstatic void __";
4168 S += funcName;
4169 S += "_block_dispose_" + utostr(i);
4170 S += "(" + StructRef;
4171 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004172 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004173 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004174 S += VD->getNameAsString();
4175 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004176 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4177 else if (VD->getType()->isBlockPointerType())
4178 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4179 else
4180 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4181 }
4182 S += "}\n";
4183 return S;
4184}
4185
4186std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4187 std::string Desc) {
4188 std::string S = "\nstruct " + Tag;
4189 std::string Constructor = " " + Tag;
4190
4191 S += " {\n struct __block_impl impl;\n";
4192 S += " struct " + Desc;
4193 S += "* Desc;\n";
4194
4195 Constructor += "(void *fp, "; // Invoke function pointer.
4196 Constructor += "struct " + Desc; // Descriptor pointer.
4197 Constructor += " *desc";
4198
4199 if (BlockDeclRefs.size()) {
4200 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004201 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004202 E = BlockByCopyDecls.end(); I != E; ++I) {
4203 S += " ";
4204 std::string FieldName = (*I)->getNameAsString();
4205 std::string ArgName = "_" + FieldName;
4206 // Handle nested closure invocation. For example:
4207 //
4208 // void (^myImportedBlock)(void);
4209 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4210 //
4211 // void (^anotherBlock)(void);
4212 // anotherBlock = ^(void) {
4213 // myImportedBlock(); // import and invoke the closure
4214 // };
4215 //
4216 if (isTopLevelBlockPointerType((*I)->getType())) {
4217 S += "struct __block_impl *";
4218 Constructor += ", void *" + ArgName;
4219 } else {
4220 QualType QT = (*I)->getType();
4221 if (HasLocalVariableExternalStorage(*I))
4222 QT = Context->getPointerType(QT);
4223 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4224 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4225 Constructor += ", " + ArgName;
4226 }
4227 S += FieldName + ";\n";
4228 }
4229 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004230 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004231 E = BlockByRefDecls.end(); I != E; ++I) {
4232 S += " ";
4233 std::string FieldName = (*I)->getNameAsString();
4234 std::string ArgName = "_" + FieldName;
4235 {
4236 std::string TypeString;
4237 RewriteByRefString(TypeString, FieldName, (*I));
4238 TypeString += " *";
4239 FieldName = TypeString + FieldName;
4240 ArgName = TypeString + ArgName;
4241 Constructor += ", " + ArgName;
4242 }
4243 S += FieldName + "; // by ref\n";
4244 }
4245 // Finish writing the constructor.
4246 Constructor += ", int flags=0)";
4247 // Initialize all "by copy" arguments.
4248 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004249 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004250 E = BlockByCopyDecls.end(); I != E; ++I) {
4251 std::string Name = (*I)->getNameAsString();
4252 if (firsTime) {
4253 Constructor += " : ";
4254 firsTime = false;
4255 }
4256 else
4257 Constructor += ", ";
4258 if (isTopLevelBlockPointerType((*I)->getType()))
4259 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4260 else
4261 Constructor += Name + "(_" + Name + ")";
4262 }
4263 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004264 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004265 E = BlockByRefDecls.end(); I != E; ++I) {
4266 std::string Name = (*I)->getNameAsString();
4267 if (firsTime) {
4268 Constructor += " : ";
4269 firsTime = false;
4270 }
4271 else
4272 Constructor += ", ";
4273 Constructor += Name + "(_" + Name + "->__forwarding)";
4274 }
4275
4276 Constructor += " {\n";
4277 if (GlobalVarDecl)
4278 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4279 else
4280 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4281 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4282
4283 Constructor += " Desc = desc;\n";
4284 } else {
4285 // Finish writing the constructor.
4286 Constructor += ", int flags=0) {\n";
4287 if (GlobalVarDecl)
4288 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4289 else
4290 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4291 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4292 Constructor += " Desc = desc;\n";
4293 }
4294 Constructor += " ";
4295 Constructor += "}\n";
4296 S += Constructor;
4297 S += "};\n";
4298 return S;
4299}
4300
4301std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4302 std::string ImplTag, int i,
4303 StringRef FunName,
4304 unsigned hasCopy) {
4305 std::string S = "\nstatic struct " + DescTag;
4306
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004307 S += " {\n size_t reserved;\n";
4308 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004309 if (hasCopy) {
4310 S += " void (*copy)(struct ";
4311 S += ImplTag; S += "*, struct ";
4312 S += ImplTag; S += "*);\n";
4313
4314 S += " void (*dispose)(struct ";
4315 S += ImplTag; S += "*);\n";
4316 }
4317 S += "} ";
4318
4319 S += DescTag + "_DATA = { 0, sizeof(struct ";
4320 S += ImplTag + ")";
4321 if (hasCopy) {
4322 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4323 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4324 }
4325 S += "};\n";
4326 return S;
4327}
4328
4329void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4330 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004331 bool RewriteSC = (GlobalVarDecl &&
4332 !Blocks.empty() &&
4333 GlobalVarDecl->getStorageClass() == SC_Static &&
4334 GlobalVarDecl->getType().getCVRQualifiers());
4335 if (RewriteSC) {
4336 std::string SC(" void __");
4337 SC += GlobalVarDecl->getNameAsString();
4338 SC += "() {}";
4339 InsertText(FunLocStart, SC);
4340 }
4341
4342 // Insert closures that were part of the function.
4343 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4344 CollectBlockDeclRefInfo(Blocks[i]);
4345 // Need to copy-in the inner copied-in variables not actually used in this
4346 // block.
4347 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004348 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004349 ValueDecl *VD = Exp->getDecl();
4350 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004351 if (!VD->hasAttr<BlocksAttr>()) {
4352 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4353 BlockByCopyDeclsPtrSet.insert(VD);
4354 BlockByCopyDecls.push_back(VD);
4355 }
4356 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004357 }
John McCall113bee02012-03-10 09:33:50 +00004358
4359 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004360 BlockByRefDeclsPtrSet.insert(VD);
4361 BlockByRefDecls.push_back(VD);
4362 }
John McCall113bee02012-03-10 09:33:50 +00004363
Fariborz Jahanian11671902012-02-07 17:11:38 +00004364 // imported objects in the inner blocks not used in the outer
4365 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004366 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004367 VD->getType()->isBlockPointerType())
4368 ImportedBlockDecls.insert(VD);
4369 }
4370
4371 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4372 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4373
4374 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4375
4376 InsertText(FunLocStart, CI);
4377
4378 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4379
4380 InsertText(FunLocStart, CF);
4381
4382 if (ImportedBlockDecls.size()) {
4383 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4384 InsertText(FunLocStart, HF);
4385 }
4386 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4387 ImportedBlockDecls.size() > 0);
4388 InsertText(FunLocStart, BD);
4389
4390 BlockDeclRefs.clear();
4391 BlockByRefDecls.clear();
4392 BlockByRefDeclsPtrSet.clear();
4393 BlockByCopyDecls.clear();
4394 BlockByCopyDeclsPtrSet.clear();
4395 ImportedBlockDecls.clear();
4396 }
4397 if (RewriteSC) {
4398 // Must insert any 'const/volatile/static here. Since it has been
4399 // removed as result of rewriting of block literals.
4400 std::string SC;
4401 if (GlobalVarDecl->getStorageClass() == SC_Static)
4402 SC = "static ";
4403 if (GlobalVarDecl->getType().isConstQualified())
4404 SC += "const ";
4405 if (GlobalVarDecl->getType().isVolatileQualified())
4406 SC += "volatile ";
4407 if (GlobalVarDecl->getType().isRestrictQualified())
4408 SC += "restrict ";
4409 InsertText(FunLocStart, SC);
4410 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004411 if (GlobalConstructionExp) {
4412 // extra fancy dance for global literal expression.
4413
4414 // Always the latest block expression on the block stack.
4415 std::string Tag = "__";
4416 Tag += FunName;
4417 Tag += "_block_impl_";
4418 Tag += utostr(Blocks.size()-1);
4419 std::string globalBuf = "static ";
4420 globalBuf += Tag; globalBuf += " ";
4421 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004422
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004423 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004424 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4425 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004426 globalBuf += constructorExprBuf.str();
4427 globalBuf += ";\n";
4428 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004429 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004430 }
4431
Fariborz Jahanian11671902012-02-07 17:11:38 +00004432 Blocks.clear();
4433 InnerDeclRefsCount.clear();
4434 InnerDeclRefs.clear();
4435 RewrittenBlockExprs.clear();
4436}
4437
4438void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004439 SourceLocation FunLocStart =
4440 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4441 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004442 StringRef FuncName = FD->getName();
4443
4444 SynthesizeBlockLiterals(FunLocStart, FuncName);
4445}
4446
4447static void BuildUniqueMethodName(std::string &Name,
4448 ObjCMethodDecl *MD) {
4449 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4450 Name = IFace->getName();
4451 Name += "__" + MD->getSelector().getAsString();
4452 // Convert colons to underscores.
4453 std::string::size_type loc = 0;
4454 while ((loc = Name.find(":", loc)) != std::string::npos)
4455 Name.replace(loc, 1, "_");
4456}
4457
4458void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4459 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4460 //SourceLocation FunLocStart = MD->getLocStart();
4461 SourceLocation FunLocStart = MD->getLocStart();
4462 std::string FuncName;
4463 BuildUniqueMethodName(FuncName, MD);
4464 SynthesizeBlockLiterals(FunLocStart, FuncName);
4465}
4466
4467void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004468 for (Stmt *SubStmt : S->children())
4469 if (SubStmt) {
4470 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004471 GetBlockDeclRefExprs(CBE->getBody());
4472 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004473 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004474 }
4475 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004476 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004477 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004478 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004479 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004480 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004481}
4482
Craig Topper5603df42013-07-05 19:34:19 +00004483void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4484 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004485 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004486 for (Stmt *SubStmt : S->children())
4487 if (SubStmt) {
4488 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004489 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4490 GetInnerBlockDeclRefExprs(CBE->getBody(),
4491 InnerBlockDeclRefs,
4492 InnerContexts);
4493 }
4494 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004495 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004496 }
4497 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004498 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004499 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004500 HasLocalVariableExternalStorage(DRE->getDecl())) {
4501 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004502 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004503 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004504 if (Var->isFunctionOrMethodVarDecl())
4505 ImportedLocalExternalDecls.insert(Var);
4506 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004507 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004508}
4509
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004510/// convertObjCTypeToCStyleType - This routine converts such objc types
4511/// as qualified objects, and blocks to their closest c/c++ types that
4512/// it can. It returns true if input type was modified.
4513bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4514 QualType oldT = T;
4515 convertBlockPointerToFunctionPointer(T);
4516 if (T->isFunctionPointerType()) {
4517 QualType PointeeTy;
4518 if (const PointerType* PT = T->getAs<PointerType>()) {
4519 PointeeTy = PT->getPointeeType();
4520 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4521 T = convertFunctionTypeOfBlocks(FT);
4522 T = Context->getPointerType(T);
4523 }
4524 }
4525 }
4526
4527 convertToUnqualifiedObjCType(T);
4528 return T != oldT;
4529}
4530
Fariborz Jahanian11671902012-02-07 17:11:38 +00004531/// convertFunctionTypeOfBlocks - This routine converts a function type
4532/// whose result type may be a block pointer or whose argument type(s)
4533/// might be block pointers to an equivalent function type replacing
4534/// all block pointers to function pointers.
4535QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4536 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4537 // FTP will be null for closures that don't take arguments.
4538 // Generate a funky cast.
4539 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004540 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004541 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004542
4543 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004544 for (auto &I : FTP->param_types()) {
4545 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004546 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004547 if (convertObjCTypeToCStyleType(t))
4548 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004549 ArgTypes.push_back(t);
4550 }
4551 }
4552 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004553 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004554 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004555 else FuncType = QualType(FT, 0);
4556 return FuncType;
4557}
4558
4559Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4560 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004561 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004562
4563 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4564 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004565 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4566 CPT = MExpr->getType()->getAs<BlockPointerType>();
4567 }
4568 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4569 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4570 }
4571 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4572 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4573 else if (const ConditionalOperator *CEXPR =
4574 dyn_cast<ConditionalOperator>(BlockExp)) {
4575 Expr *LHSExp = CEXPR->getLHS();
4576 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4577 Expr *RHSExp = CEXPR->getRHS();
4578 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4579 Expr *CONDExp = CEXPR->getCond();
4580 ConditionalOperator *CondExpr =
4581 new (Context) ConditionalOperator(CONDExp,
4582 SourceLocation(), cast<Expr>(LHSStmt),
4583 SourceLocation(), cast<Expr>(RHSStmt),
4584 Exp->getType(), VK_RValue, OK_Ordinary);
4585 return CondExpr;
4586 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4587 CPT = IRE->getType()->getAs<BlockPointerType>();
4588 } else if (const PseudoObjectExpr *POE
4589 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4590 CPT = POE->getType()->castAs<BlockPointerType>();
4591 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004592 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004593 }
4594 assert(CPT && "RewriteBlockClass: Bad type");
4595 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4596 assert(FT && "RewriteBlockClass: Bad type");
4597 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4598 // FTP will be null for closures that don't take arguments.
4599
4600 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4601 SourceLocation(), SourceLocation(),
4602 &Context->Idents.get("__block_impl"));
4603 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4604
4605 // Generate a funky cast.
4606 SmallVector<QualType, 8> ArgTypes;
4607
4608 // Push the block argument type.
4609 ArgTypes.push_back(PtrBlock);
4610 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004611 for (auto &I : FTP->param_types()) {
4612 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004613 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4614 if (!convertBlockPointerToFunctionPointer(t))
4615 convertToUnqualifiedObjCType(t);
4616 ArgTypes.push_back(t);
4617 }
4618 }
4619 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004620 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004621
4622 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4623
4624 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4625 CK_BitCast,
4626 const_cast<Expr*>(BlockExp));
4627 // Don't forget the parens to enforce the proper binding.
4628 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4629 BlkCast);
4630 //PE->dump();
4631
Craig Topper8ae12032014-05-07 06:21:57 +00004632 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004633 SourceLocation(),
4634 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004635 Context->VoidPtrTy, nullptr,
4636 /*BitWidth=*/nullptr, /*Mutable=*/true,
4637 ICIS_NoInit);
4638 MemberExpr *ME =
4639 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4640 FD->getType(), VK_LValue, OK_Ordinary);
4641
4642 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4643 CK_BitCast, ME);
4644 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004645
4646 SmallVector<Expr*, 8> BlkExprs;
4647 // Add the implicit argument.
4648 BlkExprs.push_back(BlkCast);
4649 // Add the user arguments.
4650 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4651 E = Exp->arg_end(); I != E; ++I) {
4652 BlkExprs.push_back(*I);
4653 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004654 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004655 Exp->getType(), VK_RValue,
4656 SourceLocation());
4657 return CE;
4658}
4659
4660// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004661// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004662// For example:
4663//
4664// int main() {
4665// __block Foo *f;
4666// __block int i;
4667//
4668// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004669// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004670// i = 77;
4671// };
4672//}
John McCall113bee02012-03-10 09:33:50 +00004673Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4675 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004676 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004677 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004678 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004679
4680 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004681 SourceLocation(),
4682 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004683 Context->VoidPtrTy, nullptr,
4684 /*BitWidth=*/nullptr, /*Mutable=*/true,
4685 ICIS_NoInit);
4686 MemberExpr *ME = new (Context)
4687 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4688 FD->getType(), VK_LValue, OK_Ordinary);
4689
4690 StringRef Name = VD->getName();
4691 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004692 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004693 Context->VoidPtrTy, nullptr,
4694 /*BitWidth=*/nullptr, /*Mutable=*/true,
4695 ICIS_NoInit);
4696 ME =
4697 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4698 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4699
4700 // Need parens to enforce precedence.
4701 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4702 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004703 ME);
4704 ReplaceStmt(DeclRefExp, PE);
4705 return PE;
4706}
4707
4708// Rewrites the imported local variable V with external storage
4709// (static, extern, etc.) as *V
4710//
4711Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4712 ValueDecl *VD = DRE->getDecl();
4713 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4714 if (!ImportedLocalExternalDecls.count(Var))
4715 return DRE;
4716 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4717 VK_LValue, OK_Ordinary,
4718 DRE->getLocation());
4719 // Need parens to enforce precedence.
4720 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4721 Exp);
4722 ReplaceStmt(DRE, PE);
4723 return PE;
4724}
4725
4726void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4727 SourceLocation LocStart = CE->getLParenLoc();
4728 SourceLocation LocEnd = CE->getRParenLoc();
4729
4730 // Need to avoid trying to rewrite synthesized casts.
4731 if (LocStart.isInvalid())
4732 return;
4733 // Need to avoid trying to rewrite casts contained in macros.
4734 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4735 return;
4736
4737 const char *startBuf = SM->getCharacterData(LocStart);
4738 const char *endBuf = SM->getCharacterData(LocEnd);
4739 QualType QT = CE->getType();
4740 const Type* TypePtr = QT->getAs<Type>();
4741 if (isa<TypeOfExprType>(TypePtr)) {
4742 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4743 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4744 std::string TypeAsString = "(";
4745 RewriteBlockPointerType(TypeAsString, QT);
4746 TypeAsString += ")";
4747 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4748 return;
4749 }
4750 // advance the location to startArgList.
4751 const char *argPtr = startBuf;
4752
4753 while (*argPtr++ && (argPtr < endBuf)) {
4754 switch (*argPtr) {
4755 case '^':
4756 // Replace the '^' with '*'.
4757 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4758 ReplaceText(LocStart, 1, "*");
4759 break;
4760 }
4761 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004762}
4763
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004764void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4765 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004766 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4767 CastKind != CK_AnyPointerToBlockPointerCast)
4768 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004769
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004770 QualType QT = IC->getType();
4771 (void)convertBlockPointerToFunctionPointer(QT);
4772 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4773 std::string Str = "(";
4774 Str += TypeString;
4775 Str += ")";
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004776 InsertText(IC->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004777}
4778
Fariborz Jahanian11671902012-02-07 17:11:38 +00004779void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4780 SourceLocation DeclLoc = FD->getLocation();
4781 unsigned parenCount = 0;
4782
4783 // We have 1 or more arguments that have closure pointers.
4784 const char *startBuf = SM->getCharacterData(DeclLoc);
4785 const char *startArgList = strchr(startBuf, '(');
4786
4787 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4788
4789 parenCount++;
4790 // advance the location to startArgList.
4791 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4792 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4793
4794 const char *argPtr = startArgList;
4795
4796 while (*argPtr++ && parenCount) {
4797 switch (*argPtr) {
4798 case '^':
4799 // Replace the '^' with '*'.
4800 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4801 ReplaceText(DeclLoc, 1, "*");
4802 break;
4803 case '(':
4804 parenCount++;
4805 break;
4806 case ')':
4807 parenCount--;
4808 break;
4809 }
4810 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004811}
4812
4813bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4814 const FunctionProtoType *FTP;
4815 const PointerType *PT = QT->getAs<PointerType>();
4816 if (PT) {
4817 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4818 } else {
4819 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4820 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4821 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4822 }
4823 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004824 for (const auto &I : FTP->param_types())
4825 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004826 return true;
4827 }
4828 return false;
4829}
4830
4831bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4832 const FunctionProtoType *FTP;
4833 const PointerType *PT = QT->getAs<PointerType>();
4834 if (PT) {
4835 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4836 } else {
4837 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4838 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4839 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4840 }
4841 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004842 for (const auto &I : FTP->param_types()) {
4843 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004844 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004845 if (I->isObjCObjectPointerType() &&
4846 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004847 return true;
4848 }
4849
4850 }
4851 return false;
4852}
4853
4854void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4855 const char *&RParen) {
4856 const char *argPtr = strchr(Name, '(');
4857 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4858
4859 LParen = argPtr; // output the start.
4860 argPtr++; // skip past the left paren.
4861 unsigned parenCount = 1;
4862
4863 while (*argPtr && parenCount) {
4864 switch (*argPtr) {
4865 case '(': parenCount++; break;
4866 case ')': parenCount--; break;
4867 default: break;
4868 }
4869 if (parenCount) argPtr++;
4870 }
4871 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4872 RParen = argPtr; // output the end
4873}
4874
4875void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4876 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4877 RewriteBlockPointerFunctionArgs(FD);
4878 return;
4879 }
4880 // Handle Variables and Typedefs.
4881 SourceLocation DeclLoc = ND->getLocation();
4882 QualType DeclT;
4883 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4884 DeclT = VD->getType();
4885 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4886 DeclT = TDD->getUnderlyingType();
4887 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4888 DeclT = FD->getType();
4889 else
4890 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4891
4892 const char *startBuf = SM->getCharacterData(DeclLoc);
4893 const char *endBuf = startBuf;
4894 // scan backward (from the decl location) for the end of the previous decl.
4895 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4896 startBuf--;
4897 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4898 std::string buf;
4899 unsigned OrigLength=0;
4900 // *startBuf != '^' if we are dealing with a pointer to function that
4901 // may take block argument types (which will be handled below).
4902 if (*startBuf == '^') {
4903 // Replace the '^' with '*', computing a negative offset.
4904 buf = '*';
4905 startBuf++;
4906 OrigLength++;
4907 }
4908 while (*startBuf != ')') {
4909 buf += *startBuf;
4910 startBuf++;
4911 OrigLength++;
4912 }
4913 buf += ')';
4914 OrigLength++;
4915
4916 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4917 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4918 // Replace the '^' with '*' for arguments.
4919 // Replace id<P> with id/*<>*/
4920 DeclLoc = ND->getLocation();
4921 startBuf = SM->getCharacterData(DeclLoc);
4922 const char *argListBegin, *argListEnd;
4923 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4924 while (argListBegin < argListEnd) {
4925 if (*argListBegin == '^')
4926 buf += '*';
4927 else if (*argListBegin == '<') {
4928 buf += "/*";
4929 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004930 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004931 while (*argListBegin != '>') {
4932 buf += *argListBegin++;
4933 OrigLength++;
4934 }
4935 buf += *argListBegin;
4936 buf += "*/";
4937 }
4938 else
4939 buf += *argListBegin;
4940 argListBegin++;
4941 OrigLength++;
4942 }
4943 buf += ')';
4944 OrigLength++;
4945 }
4946 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004947}
4948
Fariborz Jahanian11671902012-02-07 17:11:38 +00004949/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4950/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4951/// struct Block_byref_id_object *src) {
4952/// _Block_object_assign (&_dest->object, _src->object,
4953/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4954/// [|BLOCK_FIELD_IS_WEAK]) // object
4955/// _Block_object_assign(&_dest->object, _src->object,
4956/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4957/// [|BLOCK_FIELD_IS_WEAK]) // block
4958/// }
4959/// And:
4960/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4961/// _Block_object_dispose(_src->object,
4962/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4963/// [|BLOCK_FIELD_IS_WEAK]) // object
4964/// _Block_object_dispose(_src->object,
4965/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4966/// [|BLOCK_FIELD_IS_WEAK]) // block
4967/// }
4968
4969std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4970 int flag) {
4971 std::string S;
4972 if (CopyDestroyCache.count(flag))
4973 return S;
4974 CopyDestroyCache.insert(flag);
4975 S = "static void __Block_byref_id_object_copy_";
4976 S += utostr(flag);
4977 S += "(void *dst, void *src) {\n";
4978
4979 // offset into the object pointer is computed as:
4980 // void * + void* + int + int + void* + void *
4981 unsigned IntSize =
4982 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4983 unsigned VoidPtrSize =
4984 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4985
4986 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4987 S += " _Block_object_assign((char*)dst + ";
4988 S += utostr(offset);
4989 S += ", *(void * *) ((char*)src + ";
4990 S += utostr(offset);
4991 S += "), ";
4992 S += utostr(flag);
4993 S += ");\n}\n";
4994
4995 S += "static void __Block_byref_id_object_dispose_";
4996 S += utostr(flag);
4997 S += "(void *src) {\n";
4998 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4999 S += utostr(offset);
5000 S += "), ";
5001 S += utostr(flag);
5002 S += ");\n}\n";
5003 return S;
5004}
5005
5006/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5007/// the declaration into:
5008/// struct __Block_byref_ND {
5009/// void *__isa; // NULL for everything except __weak pointers
5010/// struct __Block_byref_ND *__forwarding;
5011/// int32_t __flags;
5012/// int32_t __size;
5013/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5014/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5015/// typex ND;
5016/// };
5017///
5018/// It then replaces declaration of ND variable with:
5019/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5020/// __size=sizeof(struct __Block_byref_ND),
5021/// ND=initializer-if-any};
5022///
5023///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005024void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5025 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005026 int flag = 0;
5027 int isa = 0;
5028 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5029 if (DeclLoc.isInvalid())
5030 // If type location is missing, it is because of missing type (a warning).
5031 // Use variable's location which is good for this case.
5032 DeclLoc = ND->getLocation();
5033 const char *startBuf = SM->getCharacterData(DeclLoc);
5034 SourceLocation X = ND->getLocEnd();
5035 X = SM->getExpansionLoc(X);
5036 const char *endBuf = SM->getCharacterData(X);
5037 std::string Name(ND->getNameAsString());
5038 std::string ByrefType;
5039 RewriteByRefString(ByrefType, Name, ND, true);
5040 ByrefType += " {\n";
5041 ByrefType += " void *__isa;\n";
5042 RewriteByRefString(ByrefType, Name, ND);
5043 ByrefType += " *__forwarding;\n";
5044 ByrefType += " int __flags;\n";
5045 ByrefType += " int __size;\n";
5046 // Add void *__Block_byref_id_object_copy;
5047 // void *__Block_byref_id_object_dispose; if needed.
5048 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005049 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005050 if (HasCopyAndDispose) {
5051 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5052 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5053 }
5054
5055 QualType T = Ty;
5056 (void)convertBlockPointerToFunctionPointer(T);
5057 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5058
5059 ByrefType += " " + Name + ";\n";
5060 ByrefType += "};\n";
5061 // Insert this type in global scope. It is needed by helper function.
5062 SourceLocation FunLocStart;
5063 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005064 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005065 else {
5066 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5067 FunLocStart = CurMethodDef->getLocStart();
5068 }
5069 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005070
Fariborz Jahanian11671902012-02-07 17:11:38 +00005071 if (Ty.isObjCGCWeak()) {
5072 flag |= BLOCK_FIELD_IS_WEAK;
5073 isa = 1;
5074 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005075 if (HasCopyAndDispose) {
5076 flag = BLOCK_BYREF_CALLER;
5077 QualType Ty = ND->getType();
5078 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5079 if (Ty->isBlockPointerType())
5080 flag |= BLOCK_FIELD_IS_BLOCK;
5081 else
5082 flag |= BLOCK_FIELD_IS_OBJECT;
5083 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5084 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005085 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005086 }
5087
5088 // struct __Block_byref_ND ND =
5089 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5090 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005091 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005092 // FIXME. rewriter does not support __block c++ objects which
5093 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005094 if (hasInit)
5095 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5096 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5097 if (CXXDecl && CXXDecl->isDefaultConstructor())
5098 hasInit = false;
5099 }
5100
Fariborz Jahanian11671902012-02-07 17:11:38 +00005101 unsigned flags = 0;
5102 if (HasCopyAndDispose)
5103 flags |= BLOCK_HAS_COPY_DISPOSE;
5104 Name = ND->getNameAsString();
5105 ByrefType.clear();
5106 RewriteByRefString(ByrefType, Name, ND);
5107 std::string ForwardingCastType("(");
5108 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005109 ByrefType += " " + Name + " = {(void*)";
5110 ByrefType += utostr(isa);
5111 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5112 ByrefType += utostr(flags);
5113 ByrefType += ", ";
5114 ByrefType += "sizeof(";
5115 RewriteByRefString(ByrefType, Name, ND);
5116 ByrefType += ")";
5117 if (HasCopyAndDispose) {
5118 ByrefType += ", __Block_byref_id_object_copy_";
5119 ByrefType += utostr(flag);
5120 ByrefType += ", __Block_byref_id_object_dispose_";
5121 ByrefType += utostr(flag);
5122 }
5123
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005124 if (!firstDecl) {
5125 // In multiple __block declarations, and for all but 1st declaration,
5126 // find location of the separating comma. This would be start location
5127 // where new text is to be inserted.
5128 DeclLoc = ND->getLocation();
5129 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5130 const char *commaBuf = startDeclBuf;
5131 while (*commaBuf != ',')
5132 commaBuf--;
5133 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5134 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5135 startBuf = commaBuf;
5136 }
5137
Fariborz Jahanian11671902012-02-07 17:11:38 +00005138 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005139 ByrefType += "};\n";
5140 unsigned nameSize = Name.size();
5141 // for block or function pointer declaration. Name is aleady
5142 // part of the declaration.
5143 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5144 nameSize = 1;
5145 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5146 }
5147 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005148 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005149 SourceLocation startLoc;
5150 Expr *E = ND->getInit();
5151 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5152 startLoc = ECE->getLParenLoc();
5153 else
5154 startLoc = E->getLocStart();
5155 startLoc = SM->getExpansionLoc(startLoc);
5156 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005157 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005158
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005159 const char separator = lastDecl ? ';' : ',';
5160 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5161 const char *separatorBuf = strchr(startInitializerBuf, separator);
5162 assert((*separatorBuf == separator) &&
5163 "RewriteByRefVar: can't find ';' or ','");
5164 SourceLocation separatorLoc =
5165 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5166
5167 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005168 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005169}
5170
5171void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5172 // Add initializers for any closure decl refs.
5173 GetBlockDeclRefExprs(Exp->getBody());
5174 if (BlockDeclRefs.size()) {
5175 // Unique all "by copy" declarations.
5176 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005177 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005178 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5179 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5180 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5181 }
5182 }
5183 // Unique all "by ref" declarations.
5184 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005185 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005186 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5187 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5188 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5189 }
5190 }
5191 // Find any imported blocks...they will need special attention.
5192 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005193 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005194 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5195 BlockDeclRefs[i]->getType()->isBlockPointerType())
5196 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5197 }
5198}
5199
5200FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5201 IdentifierInfo *ID = &Context->Idents.get(name);
5202 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5203 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005204 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005205 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005206}
5207
5208Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005209 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005210 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005211
Fariborz Jahanian11671902012-02-07 17:11:38 +00005212 Blocks.push_back(Exp);
5213
5214 CollectBlockDeclRefInfo(Exp);
5215
5216 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005217 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005218 if (!InnerBlockDeclRefs.empty()) {
5219 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005220 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005221 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005222 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005223 // We need to save the copied-in variables in nested
5224 // blocks because it is needed at the end for some of the API generations.
5225 // See SynthesizeBlockLiterals routine.
5226 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5227 BlockDeclRefs.push_back(Exp);
5228 BlockByCopyDeclsPtrSet.insert(VD);
5229 BlockByCopyDecls.push_back(VD);
5230 }
John McCall113bee02012-03-10 09:33:50 +00005231 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005232 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5233 BlockDeclRefs.push_back(Exp);
5234 BlockByRefDeclsPtrSet.insert(VD);
5235 BlockByRefDecls.push_back(VD);
5236 }
5237 }
5238 // Find any imported blocks...they will need special attention.
5239 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005240 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005241 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5242 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5243 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5244 }
5245 InnerDeclRefsCount.push_back(countOfInnerDecls);
5246
5247 std::string FuncName;
5248
5249 if (CurFunctionDef)
5250 FuncName = CurFunctionDef->getNameAsString();
5251 else if (CurMethodDef)
5252 BuildUniqueMethodName(FuncName, CurMethodDef);
5253 else if (GlobalVarDecl)
5254 FuncName = std::string(GlobalVarDecl->getNameAsString());
5255
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005256 bool GlobalBlockExpr =
5257 block->getDeclContext()->getRedeclContext()->isFileContext();
5258
5259 if (GlobalBlockExpr && !GlobalVarDecl) {
5260 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5261 GlobalBlockExpr = false;
5262 }
5263
Fariborz Jahanian11671902012-02-07 17:11:38 +00005264 std::string BlockNumber = utostr(Blocks.size()-1);
5265
Fariborz Jahanian11671902012-02-07 17:11:38 +00005266 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5267
5268 // Get a pointer to the function type so we can cast appropriately.
5269 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5270 QualType FType = Context->getPointerType(BFT);
5271
5272 FunctionDecl *FD;
5273 Expr *NewRep;
5274
Benjamin Kramer60509af2013-09-09 14:48:42 +00005275 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005276 std::string Tag;
5277
5278 if (GlobalBlockExpr)
5279 Tag = "__global_";
5280 else
5281 Tag = "__";
5282 Tag += FuncName + "_block_impl_" + BlockNumber;
5283
Fariborz Jahanian11671902012-02-07 17:11:38 +00005284 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005285 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005286 SourceLocation());
5287
5288 SmallVector<Expr*, 4> InitExprs;
5289
5290 // Initialize the block function.
5291 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005292 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5293 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005294 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5295 CK_BitCast, Arg);
5296 InitExprs.push_back(castExpr);
5297
5298 // Initialize the block descriptor.
5299 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5300
5301 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5302 SourceLocation(), SourceLocation(),
5303 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005304 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005305 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005306 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005307 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005308 Context->VoidPtrTy,
5309 VK_LValue,
5310 SourceLocation()),
5311 UO_AddrOf,
5312 Context->getPointerType(Context->VoidPtrTy),
5313 VK_RValue, OK_Ordinary,
5314 SourceLocation());
5315 InitExprs.push_back(DescRefExpr);
5316
5317 // Add initializers for any closure decl refs.
5318 if (BlockDeclRefs.size()) {
5319 Expr *Exp;
5320 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005321 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005322 E = BlockByCopyDecls.end(); I != E; ++I) {
5323 if (isObjCType((*I)->getType())) {
5324 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5325 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005326 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5327 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005328 if (HasLocalVariableExternalStorage(*I)) {
5329 QualType QT = (*I)->getType();
5330 QT = Context->getPointerType(QT);
5331 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5332 OK_Ordinary, SourceLocation());
5333 }
5334 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5335 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005336 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5337 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005338 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5339 CK_BitCast, Arg);
5340 } else {
5341 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005342 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5343 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005344 if (HasLocalVariableExternalStorage(*I)) {
5345 QualType QT = (*I)->getType();
5346 QT = Context->getPointerType(QT);
5347 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5348 OK_Ordinary, SourceLocation());
5349 }
5350
5351 }
5352 InitExprs.push_back(Exp);
5353 }
5354 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005355 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005356 E = BlockByRefDecls.end(); I != E; ++I) {
5357 ValueDecl *ND = (*I);
5358 std::string Name(ND->getNameAsString());
5359 std::string RecName;
5360 RewriteByRefString(RecName, Name, ND, true);
5361 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5362 + sizeof("struct"));
5363 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5364 SourceLocation(), SourceLocation(),
5365 II);
5366 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5367 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5368
5369 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005370 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005371 SourceLocation());
5372 bool isNestedCapturedVar = false;
5373 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005374 for (const auto &CI : block->captures()) {
5375 const VarDecl *variable = CI.getVariable();
5376 if (variable == ND && CI.isNested()) {
5377 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005378 "SynthBlockInitExpr - captured block variable is not byref");
5379 isNestedCapturedVar = true;
5380 break;
5381 }
5382 }
5383 // captured nested byref variable has its address passed. Do not take
5384 // its address again.
5385 if (!isNestedCapturedVar)
5386 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5387 Context->getPointerType(Exp->getType()),
5388 VK_RValue, OK_Ordinary, SourceLocation());
5389 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5390 InitExprs.push_back(Exp);
5391 }
5392 }
5393 if (ImportedBlockDecls.size()) {
5394 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5395 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5396 unsigned IntSize =
5397 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5398 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5399 Context->IntTy, SourceLocation());
5400 InitExprs.push_back(FlagExp);
5401 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005402 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005403 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005404
5405 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005406 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005407 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5408 GlobalConstructionExp = NewRep;
5409 NewRep = DRE;
5410 }
5411
Fariborz Jahanian11671902012-02-07 17:11:38 +00005412 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5413 Context->getPointerType(NewRep->getType()),
5414 VK_RValue, OK_Ordinary, SourceLocation());
5415 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5416 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005417 // Put Paren around the call.
5418 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5419 NewRep);
5420
Fariborz Jahanian11671902012-02-07 17:11:38 +00005421 BlockDeclRefs.clear();
5422 BlockByRefDecls.clear();
5423 BlockByRefDeclsPtrSet.clear();
5424 BlockByCopyDecls.clear();
5425 BlockByCopyDeclsPtrSet.clear();
5426 ImportedBlockDecls.clear();
5427 return NewRep;
5428}
5429
5430bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5431 if (const ObjCForCollectionStmt * CS =
5432 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5433 return CS->getElement() == DS;
5434 return false;
5435}
5436
5437//===----------------------------------------------------------------------===//
5438// Function Body / Expression rewriting
5439//===----------------------------------------------------------------------===//
5440
5441Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5442 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5443 isa<DoStmt>(S) || isa<ForStmt>(S))
5444 Stmts.push_back(S);
5445 else if (isa<ObjCForCollectionStmt>(S)) {
5446 Stmts.push_back(S);
5447 ObjCBcLabelNo.push_back(++BcLabelCount);
5448 }
5449
5450 // Pseudo-object operations and ivar references need special
5451 // treatment because we're going to recursively rewrite them.
5452 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5453 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5454 return RewritePropertyOrImplicitSetter(PseudoOp);
5455 } else {
5456 return RewritePropertyOrImplicitGetter(PseudoOp);
5457 }
5458 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5459 return RewriteObjCIvarRefExpr(IvarRefExpr);
5460 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005461 else if (isa<OpaqueValueExpr>(S))
5462 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005463
5464 SourceRange OrigStmtRange = S->getSourceRange();
5465
5466 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005467 for (Stmt *&childStmt : S->children())
5468 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005469 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5470 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005471 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005472 }
5473 }
5474
5475 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005476 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005477 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5478 InnerContexts.insert(BE->getBlockDecl());
5479 ImportedLocalExternalDecls.clear();
5480 GetInnerBlockDeclRefExprs(BE->getBody(),
5481 InnerBlockDeclRefs, InnerContexts);
5482 // Rewrite the block body in place.
5483 Stmt *SaveCurrentBody = CurrentBody;
5484 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005485 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005486 // block literal on rhs of a property-dot-sytax assignment
5487 // must be replaced by its synthesize ast so getRewrittenText
5488 // works as expected. In this case, what actually ends up on RHS
5489 // is the blockTranscribed which is the helper function for the
5490 // block literal; as in: self.c = ^() {[ace ARR];};
5491 bool saveDisableReplaceStmt = DisableReplaceStmt;
5492 DisableReplaceStmt = false;
5493 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5494 DisableReplaceStmt = saveDisableReplaceStmt;
5495 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005496 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005497 ImportedLocalExternalDecls.clear();
5498 // Now we snarf the rewritten text and stash it away for later use.
5499 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5500 RewrittenBlockExprs[BE] = Str;
5501
5502 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5503
5504 //blockTranscribed->dump();
5505 ReplaceStmt(S, blockTranscribed);
5506 return blockTranscribed;
5507 }
5508 // Handle specific things.
5509 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5510 return RewriteAtEncode(AtEncode);
5511
5512 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5513 return RewriteAtSelector(AtSelector);
5514
5515 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5516 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005517
5518 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5519 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005520
Patrick Beard0caa3942012-04-19 00:25:12 +00005521 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5522 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005523
5524 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5525 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005526
5527 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5528 dyn_cast<ObjCDictionaryLiteral>(S))
5529 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005530
5531 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5532#if 0
5533 // Before we rewrite it, put the original message expression in a comment.
5534 SourceLocation startLoc = MessExpr->getLocStart();
5535 SourceLocation endLoc = MessExpr->getLocEnd();
5536
5537 const char *startBuf = SM->getCharacterData(startLoc);
5538 const char *endBuf = SM->getCharacterData(endLoc);
5539
5540 std::string messString;
5541 messString += "// ";
5542 messString.append(startBuf, endBuf-startBuf+1);
5543 messString += "\n";
5544
5545 // FIXME: Missing definition of
5546 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005547 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005548 // Tried this, but it didn't work either...
5549 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5550#endif
5551 return RewriteMessageExpr(MessExpr);
5552 }
5553
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005554 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5555 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5556 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5557 }
5558
Fariborz Jahanian11671902012-02-07 17:11:38 +00005559 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5560 return RewriteObjCTryStmt(StmtTry);
5561
5562 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5563 return RewriteObjCSynchronizedStmt(StmtTry);
5564
5565 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5566 return RewriteObjCThrowStmt(StmtThrow);
5567
5568 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5569 return RewriteObjCProtocolExpr(ProtocolExp);
5570
5571 if (ObjCForCollectionStmt *StmtForCollection =
5572 dyn_cast<ObjCForCollectionStmt>(S))
5573 return RewriteObjCForCollectionStmt(StmtForCollection,
5574 OrigStmtRange.getEnd());
5575 if (BreakStmt *StmtBreakStmt =
5576 dyn_cast<BreakStmt>(S))
5577 return RewriteBreakStmt(StmtBreakStmt);
5578 if (ContinueStmt *StmtContinueStmt =
5579 dyn_cast<ContinueStmt>(S))
5580 return RewriteContinueStmt(StmtContinueStmt);
5581
5582 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5583 // and cast exprs.
5584 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5585 // FIXME: What we're doing here is modifying the type-specifier that
5586 // precedes the first Decl. In the future the DeclGroup should have
5587 // a separate type-specifier that we can rewrite.
5588 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5589 // the context of an ObjCForCollectionStmt. For example:
5590 // NSArray *someArray;
5591 // for (id <FooProtocol> index in someArray) ;
5592 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5593 // and it depends on the original text locations/positions.
5594 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5595 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5596
5597 // Blocks rewrite rules.
5598 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5599 DI != DE; ++DI) {
5600 Decl *SD = *DI;
5601 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5602 if (isTopLevelBlockPointerType(ND->getType()))
5603 RewriteBlockPointerDecl(ND);
5604 else if (ND->getType()->isFunctionPointerType())
5605 CheckFunctionPointerDecl(ND->getType(), ND);
5606 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5607 if (VD->hasAttr<BlocksAttr>()) {
5608 static unsigned uniqueByrefDeclCount = 0;
5609 assert(!BlockByRefDeclNo.count(ND) &&
5610 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5611 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005612 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005613 }
5614 else
5615 RewriteTypeOfDecl(VD);
5616 }
5617 }
5618 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5619 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5620 RewriteBlockPointerDecl(TD);
5621 else if (TD->getUnderlyingType()->isFunctionPointerType())
5622 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5623 }
5624 }
5625 }
5626
5627 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5628 RewriteObjCQualifiedInterfaceTypes(CE);
5629
5630 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5631 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5632 assert(!Stmts.empty() && "Statement stack is empty");
5633 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5634 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5635 && "Statement stack mismatch");
5636 Stmts.pop_back();
5637 }
5638 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005639 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5640 ValueDecl *VD = DRE->getDecl();
5641 if (VD->hasAttr<BlocksAttr>())
5642 return RewriteBlockDeclRefExpr(DRE);
5643 if (HasLocalVariableExternalStorage(VD))
5644 return RewriteLocalVariableExternalStorage(DRE);
5645 }
5646
5647 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5648 if (CE->getCallee()->getType()->isBlockPointerType()) {
5649 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5650 ReplaceStmt(S, BlockCall);
5651 return BlockCall;
5652 }
5653 }
5654 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5655 RewriteCastExpr(CE);
5656 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5658 RewriteImplicitCastObjCExpr(ICE);
5659 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005660#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005661
Fariborz Jahanian11671902012-02-07 17:11:38 +00005662 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5663 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5664 ICE->getSubExpr(),
5665 SourceLocation());
5666 // Get the new text.
5667 std::string SStr;
5668 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005669 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005670 const std::string &Str = Buf.str();
5671
5672 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005673 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005674 delete S;
5675 return Replacement;
5676 }
5677#endif
5678 // Return this stmt unmodified.
5679 return S;
5680}
5681
5682void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005683 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005684 if (isTopLevelBlockPointerType(FD->getType()))
5685 RewriteBlockPointerDecl(FD);
5686 if (FD->getType()->isObjCQualifiedIdType() ||
5687 FD->getType()->isObjCQualifiedInterfaceType())
5688 RewriteObjCQualifiedInterfaceTypes(FD);
5689 }
5690}
5691
5692/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5693/// main file of the input.
5694void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5695 switch (D->getKind()) {
5696 case Decl::Function: {
5697 FunctionDecl *FD = cast<FunctionDecl>(D);
5698 if (FD->isOverloadedOperator())
5699 return;
5700
5701 // Since function prototypes don't have ParmDecl's, we check the function
5702 // prototype. This enables us to rewrite function declarations and
5703 // definitions using the same code.
5704 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5705
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005706 if (!FD->isThisDeclarationADefinition())
5707 break;
5708
Fariborz Jahanian11671902012-02-07 17:11:38 +00005709 // FIXME: If this should support Obj-C++, support CXXTryStmt
5710 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5711 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005712 CurrentBody = Body;
5713 Body =
5714 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5715 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005716 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005717 if (PropParentMap) {
5718 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005719 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005720 }
5721 // This synthesizes and inserts the block "impl" struct, invoke function,
5722 // and any copy/dispose helper functions.
5723 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005724 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005725 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005726 }
5727 break;
5728 }
5729 case Decl::ObjCMethod: {
5730 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5731 if (CompoundStmt *Body = MD->getCompoundBody()) {
5732 CurMethodDef = MD;
5733 CurrentBody = Body;
5734 Body =
5735 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5736 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005737 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005738 if (PropParentMap) {
5739 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005740 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005741 }
5742 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005743 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005744 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005745 }
5746 break;
5747 }
5748 case Decl::ObjCImplementation: {
5749 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5750 ClassImplementation.push_back(CI);
5751 break;
5752 }
5753 case Decl::ObjCCategoryImpl: {
5754 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5755 CategoryImplementation.push_back(CI);
5756 break;
5757 }
5758 case Decl::Var: {
5759 VarDecl *VD = cast<VarDecl>(D);
5760 RewriteObjCQualifiedInterfaceTypes(VD);
5761 if (isTopLevelBlockPointerType(VD->getType()))
5762 RewriteBlockPointerDecl(VD);
5763 else if (VD->getType()->isFunctionPointerType()) {
5764 CheckFunctionPointerDecl(VD->getType(), VD);
5765 if (VD->getInit()) {
5766 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5767 RewriteCastExpr(CE);
5768 }
5769 }
5770 } else if (VD->getType()->isRecordType()) {
5771 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5772 if (RD->isCompleteDefinition())
5773 RewriteRecordBody(RD);
5774 }
5775 if (VD->getInit()) {
5776 GlobalVarDecl = VD;
5777 CurrentBody = VD->getInit();
5778 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005779 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005780 if (PropParentMap) {
5781 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005782 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005783 }
5784 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005785 GlobalVarDecl = nullptr;
5786
Fariborz Jahanian11671902012-02-07 17:11:38 +00005787 // This is needed for blocks.
5788 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5789 RewriteCastExpr(CE);
5790 }
5791 }
5792 break;
5793 }
5794 case Decl::TypeAlias:
5795 case Decl::Typedef: {
5796 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5797 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5798 RewriteBlockPointerDecl(TD);
5799 else if (TD->getUnderlyingType()->isFunctionPointerType())
5800 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005801 else
5802 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005803 }
5804 break;
5805 }
5806 case Decl::CXXRecord:
5807 case Decl::Record: {
5808 RecordDecl *RD = cast<RecordDecl>(D);
5809 if (RD->isCompleteDefinition())
5810 RewriteRecordBody(RD);
5811 break;
5812 }
5813 default:
5814 break;
5815 }
5816 // Nothing yet.
5817}
5818
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005819/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5820/// protocol reference symbols in the for of:
5821/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5822static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5823 ObjCProtocolDecl *PDecl,
5824 std::string &Result) {
5825 // Also output .objc_protorefs$B section and its meta-data.
5826 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005827 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005828 Result += "struct _protocol_t *";
5829 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5830 Result += PDecl->getNameAsString();
5831 Result += " = &";
5832 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5833 Result += ";\n";
5834}
5835
Fariborz Jahanian11671902012-02-07 17:11:38 +00005836void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5837 if (Diags.hasErrorOccurred())
5838 return;
5839
5840 RewriteInclude();
5841
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005842 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005843 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005844 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005845 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005846 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5847 HandleTopLevelSingleDecl(FDecl);
5848 }
5849
Fariborz Jahanian11671902012-02-07 17:11:38 +00005850 // Here's a great place to add any extra declarations that may be needed.
5851 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005852 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5853 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5854 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005855 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005856
5857 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005858
5859 if (ClassImplementation.size() || CategoryImplementation.size())
5860 RewriteImplementations();
5861
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005862 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5863 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5864 // Write struct declaration for the class matching its ivar declarations.
5865 // Note that for modern abi, this is postponed until the end of TU
5866 // because class extensions and the implementation might declare their own
5867 // private ivars.
5868 RewriteInterfaceDecl(CDecl);
5869 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005870
Fariborz Jahanian11671902012-02-07 17:11:38 +00005871 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5872 // we are done.
5873 if (const RewriteBuffer *RewriteBuf =
5874 Rewrite.getRewriteBufferFor(MainFileID)) {
5875 //printf("Changed:\n");
5876 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5877 } else {
5878 llvm::errs() << "No changes\n";
5879 }
5880
5881 if (ClassImplementation.size() || CategoryImplementation.size() ||
5882 ProtocolExprDecls.size()) {
5883 // Rewrite Objective-c meta data*
5884 std::string ResultStr;
5885 RewriteMetaDataIntoBuffer(ResultStr);
5886 // Emit metadata.
5887 *OutFile << ResultStr;
5888 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005889 // Emit ImageInfo;
5890 {
5891 std::string ResultStr;
5892 WriteImageInfo(ResultStr);
5893 *OutFile << ResultStr;
5894 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005895 OutFile->flush();
5896}
5897
5898void RewriteModernObjC::Initialize(ASTContext &context) {
5899 InitializeCommon(context);
5900
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005901 Preamble += "#ifndef __OBJC2__\n";
5902 Preamble += "#define __OBJC2__\n";
5903 Preamble += "#endif\n";
5904
Fariborz Jahanian11671902012-02-07 17:11:38 +00005905 // declaring objc_selector outside the parameter list removes a silly
5906 // scope related warning...
5907 if (IsHeader)
5908 Preamble = "#pragma once\n";
5909 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005910 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5911 Preamble += "\n\tstruct objc_object *superClass; ";
5912 // Add a constructor for creating temporary objects.
5913 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5914 Preamble += ": object(o), superClass(s) {} ";
5915 Preamble += "\n};\n";
5916
Fariborz Jahanian11671902012-02-07 17:11:38 +00005917 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005918 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005919 // These are currently generated.
5920 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005921 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005922 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005923 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005925 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005926 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005927 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5928 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005929 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00005930
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005931 // These need be generated for performance. Currently they are not,
5932 // using API calls instead.
5933 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5934 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5935 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5936
Fariborz Jahanian11671902012-02-07 17:11:38 +00005937 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005938 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5939 Preamble += "typedef struct objc_object Protocol;\n";
5940 Preamble += "#define _REWRITER_typedef_Protocol\n";
5941 Preamble += "#endif\n";
5942 if (LangOpts.MicrosoftExt) {
5943 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5944 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005945 }
5946 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005947 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005948
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5951 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5954
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005956 Preamble += "(const char *);\n";
5957 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5958 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005959 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005960 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005961 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005962 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005963 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5964 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005965 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005966 Preamble += "#ifdef _WIN64\n";
5967 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5968 Preamble += "#else\n";
5969 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5970 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005971 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5972 Preamble += "struct __objcFastEnumerationState {\n\t";
5973 Preamble += "unsigned long state;\n\t";
5974 Preamble += "void **itemsPtr;\n\t";
5975 Preamble += "unsigned long *mutationsPtr;\n\t";
5976 Preamble += "unsigned long extra[5];\n};\n";
5977 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5978 Preamble += "#define __FASTENUMERATIONSTATE\n";
5979 Preamble += "#endif\n";
5980 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5981 Preamble += "struct __NSConstantStringImpl {\n";
5982 Preamble += " int *isa;\n";
5983 Preamble += " int flags;\n";
5984 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005985 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005986 Preamble += " long long length;\n";
5987 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005988 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005989 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005990 Preamble += "};\n";
5991 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5992 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5993 Preamble += "#else\n";
5994 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5995 Preamble += "#endif\n";
5996 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5997 Preamble += "#endif\n";
5998 // Blocks preamble.
5999 Preamble += "#ifndef BLOCK_IMPL\n";
6000 Preamble += "#define BLOCK_IMPL\n";
6001 Preamble += "struct __block_impl {\n";
6002 Preamble += " void *isa;\n";
6003 Preamble += " int Flags;\n";
6004 Preamble += " int Reserved;\n";
6005 Preamble += " void *FuncPtr;\n";
6006 Preamble += "};\n";
6007 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6008 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6009 Preamble += "extern \"C\" __declspec(dllexport) "
6010 "void _Block_object_assign(void *, const void *, const int);\n";
6011 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6012 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6013 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6014 Preamble += "#else\n";
6015 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6016 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6017 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6018 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6019 Preamble += "#endif\n";
6020 Preamble += "#endif\n";
6021 if (LangOpts.MicrosoftExt) {
6022 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6023 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6024 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6025 Preamble += "#define __attribute__(X)\n";
6026 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006027 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006028 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006029 Preamble += "#endif\n";
6030 Preamble += "#ifndef __block\n";
6031 Preamble += "#define __block\n";
6032 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006033 }
6034 else {
6035 Preamble += "#define __block\n";
6036 Preamble += "#define __weak\n";
6037 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006038
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006039 // Declarations required for modern objective-c array and dictionary literals.
6040 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006041 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006042 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006043 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006044 Preamble += "\tva_list marker;\n";
6045 Preamble += "\tva_start(marker, count);\n";
6046 Preamble += "\tarr = new void *[count];\n";
6047 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6048 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6049 Preamble += "\tva_end( marker );\n";
6050 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006051 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006052 Preamble += "\tdelete[] arr;\n";
6053 Preamble += " }\n";
6054 Preamble += "};\n";
6055
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006056 // Declaration required for implementation of @autoreleasepool statement.
6057 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6058 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6059 Preamble += "struct __AtAutoreleasePool {\n";
6060 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6061 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6062 Preamble += " void * atautoreleasepoolobj;\n";
6063 Preamble += "};\n";
6064
Fariborz Jahanian11671902012-02-07 17:11:38 +00006065 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6066 // as this avoids warning in any 64bit/32bit compilation model.
6067 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6068}
6069
6070/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6071/// ivar offset.
6072void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6073 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006074 Result += "__OFFSETOFIVAR__(struct ";
6075 Result += ivar->getContainingInterface()->getNameAsString();
6076 if (LangOpts.MicrosoftExt)
6077 Result += "_IMPL";
6078 Result += ", ";
6079 if (ivar->isBitField())
6080 ObjCIvarBitfieldGroupDecl(ivar, Result);
6081 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006083 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006084}
6085
6086/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6087/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006088/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006089/// char *attributes;
6090/// }
6091
6092/// struct _prop_list_t {
6093/// uint32_t entsize; // sizeof(struct _prop_t)
6094/// uint32_t count_of_properties;
6095/// struct _prop_t prop_list[count_of_properties];
6096/// }
6097
6098/// struct _protocol_t;
6099
6100/// struct _protocol_list_t {
6101/// long protocol_count; // Note, this is 32/64 bit
6102/// struct _protocol_t * protocol_list[protocol_count];
6103/// }
6104
6105/// struct _objc_method {
6106/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006107/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006108/// char *_imp;
6109/// }
6110
6111/// struct _method_list_t {
6112/// uint32_t entsize; // sizeof(struct _objc_method)
6113/// uint32_t method_count;
6114/// struct _objc_method method_list[method_count];
6115/// }
6116
6117/// struct _protocol_t {
6118/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006119/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006120/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006121/// const struct method_list_t *instance_methods;
6122/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006123/// const struct method_list_t *optionalInstanceMethods;
6124/// const struct method_list_t *optionalClassMethods;
6125/// const struct _prop_list_t * properties;
6126/// const uint32_t size; // sizeof(struct _protocol_t)
6127/// const uint32_t flags; // = 0
6128/// const char ** extendedMethodTypes;
6129/// }
6130
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006131/// struct _ivar_t {
6132/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006133/// const char *name;
6134/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006135/// uint32_t alignment;
6136/// uint32_t size;
6137/// }
6138
6139/// struct _ivar_list_t {
6140/// uint32 entsize; // sizeof(struct _ivar_t)
6141/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006142/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006143/// }
6144
6145/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006146/// uint32_t flags;
6147/// uint32_t instanceStart;
6148/// uint32_t instanceSize;
6149/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006150/// const uint8_t *ivarLayout;
6151/// const char *name;
6152/// const struct _method_list_t *baseMethods;
6153/// const struct _protocol_list_t *baseProtocols;
6154/// const struct _ivar_list_t *ivars;
6155/// const uint8_t *weakIvarLayout;
6156/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006157/// }
6158
6159/// struct _class_t {
6160/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006161/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006162/// void *cache;
6163/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006164/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006165/// }
6166
6167/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006168/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006169/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006170/// const struct _method_list_t *instance_methods;
6171/// const struct _method_list_t *class_methods;
6172/// const struct _protocol_list_t *protocols;
6173/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006174/// }
6175
6176/// MessageRefTy - LLVM for:
6177/// struct _message_ref_t {
6178/// IMP messenger;
6179/// SEL name;
6180/// };
6181
6182/// SuperMessageRefTy - LLVM for:
6183/// struct _super_message_ref_t {
6184/// SUPER_IMP messenger;
6185/// SEL name;
6186/// };
6187
Fariborz Jahanian45489622012-03-14 18:09:23 +00006188static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006189 static bool meta_data_declared = false;
6190 if (meta_data_declared)
6191 return;
6192
6193 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006194 Result += "\tconst char *name;\n";
6195 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006196 Result += "};\n";
6197
6198 Result += "\nstruct _protocol_t;\n";
6199
Fariborz Jahanian11671902012-02-07 17:11:38 +00006200 Result += "\nstruct _objc_method {\n";
6201 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006202 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006203 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006204 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006205
6206 Result += "\nstruct _protocol_t {\n";
6207 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006208 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006209 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006210 Result += "\tconst struct method_list_t *instance_methods;\n";
6211 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006212 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6213 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6214 Result += "\tconst struct _prop_list_t * properties;\n";
6215 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6216 Result += "\tconst unsigned int flags; // = 0\n";
6217 Result += "\tconst char ** extendedMethodTypes;\n";
6218 Result += "};\n";
6219
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006220 Result += "\nstruct _ivar_t {\n";
6221 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006222 Result += "\tconst char *name;\n";
6223 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006224 Result += "\tunsigned int alignment;\n";
6225 Result += "\tunsigned int size;\n";
6226 Result += "};\n";
6227
6228 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006229 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006230 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006231 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006232 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6233 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006234 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006235 Result += "\tconst unsigned char *ivarLayout;\n";
6236 Result += "\tconst char *name;\n";
6237 Result += "\tconst struct _method_list_t *baseMethods;\n";
6238 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6239 Result += "\tconst struct _ivar_list_t *ivars;\n";
6240 Result += "\tconst unsigned char *weakIvarLayout;\n";
6241 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006242 Result += "};\n";
6243
6244 Result += "\nstruct _class_t {\n";
6245 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006246 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006247 Result += "\tvoid *cache;\n";
6248 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006249 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006250 Result += "};\n";
6251
6252 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006253 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006254 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006255 Result += "\tconst struct _method_list_t *instance_methods;\n";
6256 Result += "\tconst struct _method_list_t *class_methods;\n";
6257 Result += "\tconst struct _protocol_list_t *protocols;\n";
6258 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006259 Result += "};\n";
6260
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006261 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006262 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006263 meta_data_declared = true;
6264}
6265
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006266static void Write_protocol_list_t_TypeDecl(std::string &Result,
6267 long super_protocol_count) {
6268 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6269 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6270 Result += "\tstruct _protocol_t *super_protocols[";
6271 Result += utostr(super_protocol_count); Result += "];\n";
6272 Result += "}";
6273}
6274
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006275static void Write_method_list_t_TypeDecl(std::string &Result,
6276 unsigned int method_count) {
6277 Result += "struct /*_method_list_t*/"; Result += " {\n";
6278 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6279 Result += "\tunsigned int method_count;\n";
6280 Result += "\tstruct _objc_method method_list[";
6281 Result += utostr(method_count); Result += "];\n";
6282 Result += "}";
6283}
6284
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006285static void Write__prop_list_t_TypeDecl(std::string &Result,
6286 unsigned int property_count) {
6287 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6288 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6289 Result += "\tunsigned int count_of_properties;\n";
6290 Result += "\tstruct _prop_t prop_list[";
6291 Result += utostr(property_count); Result += "];\n";
6292 Result += "}";
6293}
6294
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006295static void Write__ivar_list_t_TypeDecl(std::string &Result,
6296 unsigned int ivar_count) {
6297 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6298 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6299 Result += "\tunsigned int count;\n";
6300 Result += "\tstruct _ivar_t ivar_list[";
6301 Result += utostr(ivar_count); Result += "];\n";
6302 Result += "}";
6303}
6304
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006305static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6306 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6307 StringRef VarName,
6308 StringRef ProtocolName) {
6309 if (SuperProtocols.size() > 0) {
6310 Result += "\nstatic ";
6311 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6312 Result += " "; Result += VarName;
6313 Result += ProtocolName;
6314 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6315 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6316 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6317 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6318 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6319 Result += SuperPD->getNameAsString();
6320 if (i == e-1)
6321 Result += "\n};\n";
6322 else
6323 Result += ",\n";
6324 }
6325 }
6326}
6327
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006328static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6329 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006330 ArrayRef<ObjCMethodDecl *> Methods,
6331 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006332 StringRef TopLevelDeclName,
6333 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006334 if (Methods.size() > 0) {
6335 Result += "\nstatic ";
6336 Write_method_list_t_TypeDecl(Result, Methods.size());
6337 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006338 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006339 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6340 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6341 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6342 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6343 ObjCMethodDecl *MD = Methods[i];
6344 if (i == 0)
6345 Result += "\t{{(struct objc_selector *)\"";
6346 else
6347 Result += "\t{(struct objc_selector *)\"";
6348 Result += (MD)->getSelector().getAsString(); Result += "\"";
6349 Result += ", ";
6350 std::string MethodTypeString;
6351 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6352 Result += "\""; Result += MethodTypeString; Result += "\"";
6353 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006354 if (!MethodImpl)
6355 Result += "0";
6356 else {
6357 Result += "(void *)";
6358 Result += RewriteObj.MethodInternalNames[MD];
6359 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006360 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006361 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006362 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006363 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006364 }
6365 Result += "};\n";
6366 }
6367}
6368
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006369static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006370 ASTContext *Context, std::string &Result,
6371 ArrayRef<ObjCPropertyDecl *> Properties,
6372 const Decl *Container,
6373 StringRef VarName,
6374 StringRef ProtocolName) {
6375 if (Properties.size() > 0) {
6376 Result += "\nstatic ";
6377 Write__prop_list_t_TypeDecl(Result, Properties.size());
6378 Result += " "; Result += VarName;
6379 Result += ProtocolName;
6380 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6381 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6382 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6383 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6384 ObjCPropertyDecl *PropDecl = Properties[i];
6385 if (i == 0)
6386 Result += "\t{{\"";
6387 else
6388 Result += "\t{\"";
6389 Result += PropDecl->getName(); Result += "\",";
6390 std::string PropertyTypeString, QuotePropertyTypeString;
6391 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6392 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6393 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6394 if (i == e-1)
6395 Result += "}}\n";
6396 else
6397 Result += "},\n";
6398 }
6399 Result += "};\n";
6400 }
6401}
6402
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006403// Metadata flags
6404enum MetaDataDlags {
6405 CLS = 0x0,
6406 CLS_META = 0x1,
6407 CLS_ROOT = 0x2,
6408 OBJC2_CLS_HIDDEN = 0x10,
6409 CLS_EXCEPTION = 0x20,
6410
6411 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6412 CLS_HAS_IVAR_RELEASER = 0x40,
6413 /// class was compiled with -fobjc-arr
6414 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6415};
6416
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006417static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6418 unsigned int flags,
6419 const std::string &InstanceStart,
6420 const std::string &InstanceSize,
6421 ArrayRef<ObjCMethodDecl *>baseMethods,
6422 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6423 ArrayRef<ObjCIvarDecl *>ivars,
6424 ArrayRef<ObjCPropertyDecl *>Properties,
6425 StringRef VarName,
6426 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006427 Result += "\nstatic struct _class_ro_t ";
6428 Result += VarName; Result += ClassName;
6429 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6430 Result += "\t";
6431 Result += llvm::utostr(flags); Result += ", ";
6432 Result += InstanceStart; Result += ", ";
6433 Result += InstanceSize; Result += ", \n";
6434 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006435 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6436 if (Triple.getArch() == llvm::Triple::x86_64)
6437 // uint32_t const reserved; // only when building for 64bit targets
6438 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006439 // const uint8_t * const ivarLayout;
6440 Result += "0, \n\t";
6441 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006442 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006443 if (baseMethods.size() > 0) {
6444 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006445 if (metaclass)
6446 Result += "_OBJC_$_CLASS_METHODS_";
6447 else
6448 Result += "_OBJC_$_INSTANCE_METHODS_";
6449 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006450 Result += ",\n\t";
6451 }
6452 else
6453 Result += "0, \n\t";
6454
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006455 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006456 Result += "(const struct _objc_protocol_list *)&";
6457 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6458 Result += ",\n\t";
6459 }
6460 else
6461 Result += "0, \n\t";
6462
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006463 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006464 Result += "(const struct _ivar_list_t *)&";
6465 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6466 Result += ",\n\t";
6467 }
6468 else
6469 Result += "0, \n\t";
6470
6471 // weakIvarLayout
6472 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006473 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006474 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006475 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006476 Result += ",\n";
6477 }
6478 else
6479 Result += "0, \n";
6480
6481 Result += "};\n";
6482}
6483
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006484static void Write_class_t(ASTContext *Context, std::string &Result,
6485 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006486 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6487 bool rootClass = (!CDecl->getSuperClass());
6488 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006489
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006490 if (!rootClass) {
6491 // Find the Root class
6492 RootClass = CDecl->getSuperClass();
6493 while (RootClass->getSuperClass()) {
6494 RootClass = RootClass->getSuperClass();
6495 }
6496 }
6497
6498 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006499 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006500 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006501 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006502 if (CDecl->getImplementation())
6503 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006504 else
6505 Result += "__declspec(dllimport) ";
6506
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006507 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006508 Result += CDecl->getNameAsString();
6509 Result += ";\n";
6510 }
6511 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006512 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006513 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006514 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006515 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006516 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006517 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006518 else
6519 Result += "__declspec(dllimport) ";
6520
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006521 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006522 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006523 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006524 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006525
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006526 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006527 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006528 if (RootClass->getImplementation())
6529 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006530 else
6531 Result += "__declspec(dllimport) ";
6532
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006533 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006534 Result += VarName;
6535 Result += RootClass->getNameAsString();
6536 Result += ";\n";
6537 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006538 }
6539
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006540 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6541 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006542 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6543 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006544 if (metaclass) {
6545 if (!rootClass) {
6546 Result += "0, // &"; Result += VarName;
6547 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006548 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006549 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006550 Result += CDecl->getSuperClass()->getNameAsString();
6551 Result += ",\n\t";
6552 }
6553 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006554 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006555 Result += CDecl->getNameAsString();
6556 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006557 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006558 Result += ",\n\t";
6559 }
6560 }
6561 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006562 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006563 Result += CDecl->getNameAsString();
6564 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006565 if (!rootClass) {
6566 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006567 Result += CDecl->getSuperClass()->getNameAsString();
6568 Result += ",\n\t";
6569 }
6570 else
6571 Result += "0,\n\t";
6572 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006573 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6574 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6575 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006576 Result += "&_OBJC_METACLASS_RO_$_";
6577 else
6578 Result += "&_OBJC_CLASS_RO_$_";
6579 Result += CDecl->getNameAsString();
6580 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006581
6582 // Add static function to initialize some of the meta-data fields.
6583 // avoid doing it twice.
6584 if (metaclass)
6585 return;
6586
6587 const ObjCInterfaceDecl *SuperClass =
6588 rootClass ? CDecl : CDecl->getSuperClass();
6589
6590 Result += "static void OBJC_CLASS_SETUP_$_";
6591 Result += CDecl->getNameAsString();
6592 Result += "(void ) {\n";
6593 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6594 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006595 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006596
6597 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006598 Result += ".superclass = ";
6599 if (rootClass)
6600 Result += "&OBJC_CLASS_$_";
6601 else
6602 Result += "&OBJC_METACLASS_$_";
6603
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006604 Result += SuperClass->getNameAsString(); Result += ";\n";
6605
6606 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6607 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6608
6609 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6610 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6611 Result += CDecl->getNameAsString(); Result += ";\n";
6612
6613 if (!rootClass) {
6614 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6615 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6616 Result += SuperClass->getNameAsString(); Result += ";\n";
6617 }
6618
6619 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6620 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6621 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006622}
6623
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006624static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6625 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006626 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006627 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006628 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6629 ArrayRef<ObjCMethodDecl *> ClassMethods,
6630 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6631 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006632 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006633 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006634 // must declare an extern class object in case this class is not implemented
6635 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006636 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006637 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006638 if (ClassDecl->getImplementation())
6639 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006640 else
6641 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006642
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006643 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006644 Result += "OBJC_CLASS_$_"; Result += ClassName;
6645 Result += ";\n";
6646
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006647 Result += "\nstatic struct _category_t ";
6648 Result += "_OBJC_$_CATEGORY_";
6649 Result += ClassName; Result += "_$_"; Result += CatName;
6650 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6651 Result += "{\n";
6652 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006653 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006654 Result += ",\n";
6655 if (InstanceMethods.size() > 0) {
6656 Result += "\t(const struct _method_list_t *)&";
6657 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6658 Result += ClassName; Result += "_$_"; Result += CatName;
6659 Result += ",\n";
6660 }
6661 else
6662 Result += "\t0,\n";
6663
6664 if (ClassMethods.size() > 0) {
6665 Result += "\t(const struct _method_list_t *)&";
6666 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6667 Result += ClassName; Result += "_$_"; Result += CatName;
6668 Result += ",\n";
6669 }
6670 else
6671 Result += "\t0,\n";
6672
6673 if (RefedProtocols.size() > 0) {
6674 Result += "\t(const struct _protocol_list_t *)&";
6675 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6676 Result += ClassName; Result += "_$_"; Result += CatName;
6677 Result += ",\n";
6678 }
6679 else
6680 Result += "\t0,\n";
6681
6682 if (ClassProperties.size() > 0) {
6683 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6684 Result += ClassName; Result += "_$_"; Result += CatName;
6685 Result += ",\n";
6686 }
6687 else
6688 Result += "\t0,\n";
6689
6690 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006691
6692 // Add static function to initialize the class pointer in the category structure.
6693 Result += "static void OBJC_CATEGORY_SETUP_$_";
6694 Result += ClassDecl->getNameAsString();
6695 Result += "_$_";
6696 Result += CatName;
6697 Result += "(void ) {\n";
6698 Result += "\t_OBJC_$_CATEGORY_";
6699 Result += ClassDecl->getNameAsString();
6700 Result += "_$_";
6701 Result += CatName;
6702 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6703 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006704}
6705
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006706static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6707 ASTContext *Context, std::string &Result,
6708 ArrayRef<ObjCMethodDecl *> Methods,
6709 StringRef VarName,
6710 StringRef ProtocolName) {
6711 if (Methods.size() == 0)
6712 return;
6713
6714 Result += "\nstatic const char *";
6715 Result += VarName; Result += ProtocolName;
6716 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6717 Result += "{\n";
6718 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6719 ObjCMethodDecl *MD = Methods[i];
6720 std::string MethodTypeString, QuoteMethodTypeString;
6721 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6722 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6723 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6724 if (i == e-1)
6725 Result += "\n};\n";
6726 else {
6727 Result += ",\n";
6728 }
6729 }
6730}
6731
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006732static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6733 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006734 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006735 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006736 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006737 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6738 // this is what happens:
6739 /**
6740 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6741 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6742 Class->getVisibility() == HiddenVisibility)
6743 Visibility shoud be: HiddenVisibility;
6744 else
6745 Visibility shoud be: DefaultVisibility;
6746 */
6747
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006748 Result += "\n";
6749 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6750 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006751 if (Context->getLangOpts().MicrosoftExt)
6752 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6753
6754 if (!Context->getLangOpts().MicrosoftExt ||
6755 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006756 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006757 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006758 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006759 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006760 if (Ivars[i]->isBitField())
6761 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6762 else
6763 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006764 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6765 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006766 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6767 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006768 if (Ivars[i]->isBitField()) {
6769 // skip over rest of the ivar bitfields.
6770 SKIP_BITFIELDS(i , e, Ivars);
6771 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006772 }
6773}
6774
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006775static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6776 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006777 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006778 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006779 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006780 if (OriginalIvars.size() > 0) {
6781 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6782 SmallVector<ObjCIvarDecl *, 8> Ivars;
6783 // strip off all but the first ivar bitfield from each group of ivars.
6784 // Such ivars in the ivar list table will be replaced by their grouping struct
6785 // 'ivar'.
6786 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6787 if (OriginalIvars[i]->isBitField()) {
6788 Ivars.push_back(OriginalIvars[i]);
6789 // skip over rest of the ivar bitfields.
6790 SKIP_BITFIELDS(i , e, OriginalIvars);
6791 }
6792 else
6793 Ivars.push_back(OriginalIvars[i]);
6794 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006795
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006796 Result += "\nstatic ";
6797 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6798 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006799 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006800 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6801 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6802 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6803 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6804 ObjCIvarDecl *IvarDecl = Ivars[i];
6805 if (i == 0)
6806 Result += "\t{{";
6807 else
6808 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006809 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006810 if (Ivars[i]->isBitField())
6811 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6812 else
6813 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006814 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006815
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006816 Result += "\"";
6817 if (Ivars[i]->isBitField())
6818 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6819 else
6820 Result += IvarDecl->getName();
6821 Result += "\", ";
6822
6823 QualType IVQT = IvarDecl->getType();
6824 if (IvarDecl->isBitField())
6825 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6826
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006827 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006828 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006829 IvarDecl);
6830 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6831 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6832
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006833 // FIXME. this alignment represents the host alignment and need be changed to
6834 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006835 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006836 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006837 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006838 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006839 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006840 if (i == e-1)
6841 Result += "}}\n";
6842 else
6843 Result += "},\n";
6844 }
6845 Result += "};\n";
6846 }
6847}
6848
Fariborz Jahanian11671902012-02-07 17:11:38 +00006849/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006850void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6851 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006852
Fariborz Jahanian11671902012-02-07 17:11:38 +00006853 // Do not synthesize the protocol more than once.
6854 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6855 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006856 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006857
6858 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6859 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006860 // Must write out all protocol definitions in current qualifier list,
6861 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006862 for (auto *I : PDecl->protocols())
6863 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006864
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006865 // Construct method lists.
6866 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6867 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006868 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006869 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6870 OptInstanceMethods.push_back(MD);
6871 } else {
6872 InstanceMethods.push_back(MD);
6873 }
6874 }
6875
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006876 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006877 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6878 OptClassMethods.push_back(MD);
6879 } else {
6880 ClassMethods.push_back(MD);
6881 }
6882 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006883 std::vector<ObjCMethodDecl *> AllMethods;
6884 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6885 AllMethods.push_back(InstanceMethods[i]);
6886 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6887 AllMethods.push_back(ClassMethods[i]);
6888 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6889 AllMethods.push_back(OptInstanceMethods[i]);
6890 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6891 AllMethods.push_back(OptClassMethods[i]);
6892
6893 Write__extendedMethodTypes_initializer(*this, Context, Result,
6894 AllMethods,
6895 "_OBJC_PROTOCOL_METHOD_TYPES_",
6896 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006897 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006898 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006899 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6900 "_OBJC_PROTOCOL_REFS_",
6901 PDecl->getNameAsString());
6902
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006903 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006904 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006905 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006906
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006907 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006908 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006909 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006910
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006911 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006912 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006913 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006914
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006915 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006916 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006917 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006918
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006919 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006920 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6921 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006922 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006923 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006924 "_OBJC_PROTOCOL_PROPERTIES_",
6925 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006926
Fariborz Jahanian48985802012-02-08 00:50:52 +00006927 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006928 Result += "\n";
6929 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006930 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006931 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006932 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006933 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006934 Result += "\t0,\n"; // id is; is null
6935 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006936 if (SuperProtocols.size() > 0) {
6937 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6938 Result += PDecl->getNameAsString(); Result += ",\n";
6939 }
6940 else
6941 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006942 if (InstanceMethods.size() > 0) {
6943 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6944 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006945 }
6946 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006947 Result += "\t0,\n";
6948
6949 if (ClassMethods.size() > 0) {
6950 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_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";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006955
Fariborz Jahanian48985802012-02-08 00:50:52 +00006956 if (OptInstanceMethods.size() > 0) {
6957 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6958 Result += PDecl->getNameAsString(); Result += ",\n";
6959 }
6960 else
6961 Result += "\t0,\n";
6962
6963 if (OptClassMethods.size() > 0) {
6964 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6965 Result += PDecl->getNameAsString(); Result += ",\n";
6966 }
6967 else
6968 Result += "\t0,\n";
6969
6970 if (ProtocolProperties.size() > 0) {
6971 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6972 Result += PDecl->getNameAsString(); Result += ",\n";
6973 }
6974 else
6975 Result += "\t0,\n";
6976
6977 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6978 Result += "\t0,\n";
6979
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006980 if (AllMethods.size() > 0) {
6981 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6982 Result += PDecl->getNameAsString();
6983 Result += "\n};\n";
6984 }
6985 else
6986 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006987
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006988 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006989 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006990 Result += "struct _protocol_t *";
6991 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6992 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6993 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006994
Fariborz Jahanian11671902012-02-07 17:11:38 +00006995 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00006996 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00006997 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00006998}
6999
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007000/// hasObjCExceptionAttribute - Return true if this class or any super
7001/// class has the __objc_exception__ attribute.
7002/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7003static bool hasObjCExceptionAttribute(ASTContext &Context,
7004 const ObjCInterfaceDecl *OID) {
7005 if (OID->hasAttr<ObjCExceptionAttr>())
7006 return true;
7007 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7008 return hasObjCExceptionAttribute(Context, Super);
7009 return false;
7010}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007011
Fariborz Jahanian11671902012-02-07 17:11:38 +00007012void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7013 std::string &Result) {
7014 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7015
7016 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007017 if (CDecl->isImplicitInterfaceDecl())
7018 assert(false &&
7019 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007020
Fariborz Jahanian45489622012-03-14 18:09:23 +00007021 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007022 SmallVector<ObjCIvarDecl *, 8> IVars;
7023
7024 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7025 IVD; IVD = IVD->getNextIvar()) {
7026 // Ignore unnamed bit-fields.
7027 if (!IVD->getDeclName())
7028 continue;
7029 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007030 }
7031
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007032 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007033 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007034 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007035
7036 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007037 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007038
7039 // If any of our property implementations have associated getters or
7040 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007041 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007042 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007043 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007044 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007045 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007046 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007047 if (!PD)
7048 continue;
7049 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007050 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007051 InstanceMethods.push_back(Getter);
7052 if (PD->isReadOnly())
7053 continue;
7054 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007055 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007056 InstanceMethods.push_back(Setter);
7057 }
7058
7059 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7060 "_OBJC_$_INSTANCE_METHODS_",
7061 IDecl->getNameAsString(), true);
7062
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007063 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007064
7065 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7066 "_OBJC_$_CLASS_METHODS_",
7067 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007068
7069 // Protocols referenced in class declaration?
7070 // Protocol's super protocol list
7071 std::vector<ObjCProtocolDecl *> RefedProtocols;
7072 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7073 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7074 E = Protocols.end();
7075 I != E; ++I) {
7076 RefedProtocols.push_back(*I);
7077 // Must write out all protocol definitions in current qualifier list,
7078 // and in their nested qualifiers before writing out current definition.
7079 RewriteObjCProtocolMetaData(*I, Result);
7080 }
7081
7082 Write_protocol_list_initializer(Context, Result,
7083 RefedProtocols,
7084 "_OBJC_CLASS_PROTOCOLS_$_",
7085 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007086
7087 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007088 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7089 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007090 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007091 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007092 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007093 CDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007094
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007095 // Data for initializing _class_ro_t metaclass meta-data
7096 uint32_t flags = CLS_META;
7097 std::string InstanceSize;
7098 std::string InstanceStart;
7099
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007100 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7101 if (classIsHidden)
7102 flags |= OBJC2_CLS_HIDDEN;
7103
7104 if (!CDecl->getSuperClass())
7105 // class is root
7106 flags |= CLS_ROOT;
7107 InstanceSize = "sizeof(struct _class_t)";
7108 InstanceStart = InstanceSize;
7109 Write__class_ro_t_initializer(Context, Result, flags,
7110 InstanceStart, InstanceSize,
7111 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007112 nullptr,
7113 nullptr,
7114 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007115 "_OBJC_METACLASS_RO_$_",
7116 CDecl->getNameAsString());
7117
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007118 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007119 flags = CLS;
7120 if (classIsHidden)
7121 flags |= OBJC2_CLS_HIDDEN;
7122
7123 if (hasObjCExceptionAttribute(*Context, CDecl))
7124 flags |= CLS_EXCEPTION;
7125
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007126 if (!CDecl->getSuperClass())
7127 // class is root
7128 flags |= CLS_ROOT;
7129
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007130 InstanceSize.clear();
7131 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007132 if (!ObjCSynthesizedStructs.count(CDecl)) {
7133 InstanceSize = "0";
7134 InstanceStart = "0";
7135 }
7136 else {
7137 InstanceSize = "sizeof(struct ";
7138 InstanceSize += CDecl->getNameAsString();
7139 InstanceSize += "_IMPL)";
7140
7141 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7142 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007143 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007144 }
7145 else
7146 InstanceStart = InstanceSize;
7147 }
7148 Write__class_ro_t_initializer(Context, Result, flags,
7149 InstanceStart, InstanceSize,
7150 InstanceMethods,
7151 RefedProtocols,
7152 IVars,
7153 ClassProperties,
7154 "_OBJC_CLASS_RO_$_",
7155 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007156
7157 Write_class_t(Context, Result,
7158 "OBJC_METACLASS_$_",
7159 CDecl, /*metaclass*/true);
7160
7161 Write_class_t(Context, Result,
7162 "OBJC_CLASS_$_",
7163 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007164
7165 if (ImplementationIsNonLazy(IDecl))
7166 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007167}
7168
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007169void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7170 int ClsDefCount = ClassImplementation.size();
7171 if (!ClsDefCount)
7172 return;
7173 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7174 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7175 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7176 for (int i = 0; i < ClsDefCount; i++) {
7177 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7178 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7179 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7180 Result += CDecl->getName(); Result += ",\n";
7181 }
7182 Result += "};\n";
7183}
7184
Fariborz Jahanian11671902012-02-07 17:11:38 +00007185void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7186 int ClsDefCount = ClassImplementation.size();
7187 int CatDefCount = CategoryImplementation.size();
7188
7189 // For each implemented class, write out all its meta data.
7190 for (int i = 0; i < ClsDefCount; i++)
7191 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7192
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007193 RewriteClassSetupInitHook(Result);
7194
Fariborz Jahanian11671902012-02-07 17:11:38 +00007195 // For each implemented category, write out all its meta data.
7196 for (int i = 0; i < CatDefCount; i++)
7197 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7198
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007199 RewriteCategorySetupInitHook(Result);
7200
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007201 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007202 if (LangOpts.MicrosoftExt)
7203 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007204 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7205 Result += llvm::utostr(ClsDefCount); Result += "]";
7206 Result +=
7207 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7208 "regular,no_dead_strip\")))= {\n";
7209 for (int i = 0; i < ClsDefCount; i++) {
7210 Result += "\t&OBJC_CLASS_$_";
7211 Result += ClassImplementation[i]->getNameAsString();
7212 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007213 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007214 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007215
7216 if (!DefinedNonLazyClasses.empty()) {
7217 if (LangOpts.MicrosoftExt)
7218 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7219 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7220 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7221 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7222 Result += ",\n";
7223 }
7224 Result += "};\n";
7225 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007226 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007227
7228 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007229 if (LangOpts.MicrosoftExt)
7230 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007231 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7232 Result += llvm::utostr(CatDefCount); Result += "]";
7233 Result +=
7234 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7235 "regular,no_dead_strip\")))= {\n";
7236 for (int i = 0; i < CatDefCount; i++) {
7237 Result += "\t&_OBJC_$_CATEGORY_";
7238 Result +=
7239 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7240 Result += "_$_";
7241 Result += CategoryImplementation[i]->getNameAsString();
7242 Result += ",\n";
7243 }
7244 Result += "};\n";
7245 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007246
7247 if (!DefinedNonLazyCategories.empty()) {
7248 if (LangOpts.MicrosoftExt)
7249 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7250 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7251 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7252 Result += "\t&_OBJC_$_CATEGORY_";
7253 Result +=
7254 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7255 Result += "_$_";
7256 Result += DefinedNonLazyCategories[i]->getNameAsString();
7257 Result += ",\n";
7258 }
7259 Result += "};\n";
7260 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007261}
7262
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007263void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7264 if (LangOpts.MicrosoftExt)
7265 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7266
7267 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7268 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007269 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007270}
7271
Fariborz Jahanian11671902012-02-07 17:11:38 +00007272/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7273/// implementation.
7274void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7275 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007276 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007277 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7278 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007279 ObjCCategoryDecl *CDecl
7280 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007281
7282 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007283 FullCategoryName += "_$_";
7284 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007285
7286 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007287 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007288
7289 // If any of our property implementations have associated getters or
7290 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007291 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007292 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007293 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007294 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007295 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007296 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007297 if (!PD)
7298 continue;
7299 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7300 InstanceMethods.push_back(Getter);
7301 if (PD->isReadOnly())
7302 continue;
7303 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7304 InstanceMethods.push_back(Setter);
7305 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007306
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007307 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7308 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7309 FullCategoryName, true);
7310
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007311 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007312
7313 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7314 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7315 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007316
7317 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007318 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007319 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7320 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007321 // Must write out all protocol definitions in current qualifier list,
7322 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007323 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007324
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007325 Write_protocol_list_initializer(Context, Result,
7326 RefedProtocols,
7327 "_OBJC_CATEGORY_PROTOCOLS_$_",
7328 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007329
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007330 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007331 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7332 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007333 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007334 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007335 "_OBJC_$_PROP_LIST_",
7336 FullCategoryName);
7337
7338 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007339 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007340 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007341 InstanceMethods,
7342 ClassMethods,
7343 RefedProtocols,
7344 ClassProperties);
7345
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007346 // Determine if this category is also "non-lazy".
7347 if (ImplementationIsNonLazy(IDecl))
7348 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007349}
7350
7351void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7352 int CatDefCount = CategoryImplementation.size();
7353 if (!CatDefCount)
7354 return;
7355 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7356 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7357 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7358 for (int i = 0; i < CatDefCount; i++) {
7359 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7360 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7361 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7362 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7363 Result += ClassDecl->getName();
7364 Result += "_$_";
7365 Result += CatDecl->getName();
7366 Result += ",\n";
7367 }
7368 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007369}
7370
7371// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7372/// class methods.
7373template<typename MethodIterator>
7374void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7375 MethodIterator MethodEnd,
7376 bool IsInstanceMethod,
7377 StringRef prefix,
7378 StringRef ClassName,
7379 std::string &Result) {
7380 if (MethodBegin == MethodEnd) return;
7381
7382 if (!objc_impl_method) {
7383 /* struct _objc_method {
7384 SEL _cmd;
7385 char *method_types;
7386 void *_imp;
7387 }
7388 */
7389 Result += "\nstruct _objc_method {\n";
7390 Result += "\tSEL _cmd;\n";
7391 Result += "\tchar *method_types;\n";
7392 Result += "\tvoid *_imp;\n";
7393 Result += "};\n";
7394
7395 objc_impl_method = true;
7396 }
7397
7398 // Build _objc_method_list for class's methods if needed
7399
7400 /* struct {
7401 struct _objc_method_list *next_method;
7402 int method_count;
7403 struct _objc_method method_list[];
7404 }
7405 */
7406 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007407 Result += "\n";
7408 if (LangOpts.MicrosoftExt) {
7409 if (IsInstanceMethod)
7410 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7411 else
7412 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7413 }
7414 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007415 Result += "\tstruct _objc_method_list *next_method;\n";
7416 Result += "\tint method_count;\n";
7417 Result += "\tstruct _objc_method method_list[";
7418 Result += utostr(NumMethods);
7419 Result += "];\n} _OBJC_";
7420 Result += prefix;
7421 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7422 Result += "_METHODS_";
7423 Result += ClassName;
7424 Result += " __attribute__ ((used, section (\"__OBJC, __";
7425 Result += IsInstanceMethod ? "inst" : "cls";
7426 Result += "_meth\")))= ";
7427 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7428
7429 Result += "\t,{{(SEL)\"";
7430 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7431 std::string MethodTypeString;
7432 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7433 Result += "\", \"";
7434 Result += MethodTypeString;
7435 Result += "\", (void *)";
7436 Result += MethodInternalNames[*MethodBegin];
7437 Result += "}\n";
7438 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7439 Result += "\t ,{(SEL)\"";
7440 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7441 std::string MethodTypeString;
7442 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7443 Result += "\", \"";
7444 Result += MethodTypeString;
7445 Result += "\", (void *)";
7446 Result += MethodInternalNames[*MethodBegin];
7447 Result += "}\n";
7448 }
7449 Result += "\t }\n};\n";
7450}
7451
7452Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7453 SourceRange OldRange = IV->getSourceRange();
7454 Expr *BaseExpr = IV->getBase();
7455
7456 // Rewrite the base, but without actually doing replaces.
7457 {
7458 DisableReplaceStmtScope S(*this);
7459 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7460 IV->setBase(BaseExpr);
7461 }
7462
7463 ObjCIvarDecl *D = IV->getDecl();
7464
7465 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007466
Fariborz Jahanian11671902012-02-07 17:11:38 +00007467 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7468 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007469 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007470 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7471 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007472 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007473 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7474 clsDeclared);
7475 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7476
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007477 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007478 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007479 if (D->isBitField())
7480 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7481 else
7482 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007483
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007484 ReferencedIvars[clsDeclared].insert(D);
7485
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007486 // cast offset to "char *".
7487 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7488 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007489 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007490 BaseExpr);
7491 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7492 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007493 Context->UnsignedLongTy, nullptr,
7494 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007495 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7496 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007497 SourceLocation());
7498 BinaryOperator *addExpr =
7499 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7500 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007501 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007502 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007503 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7504 SourceLocation(),
7505 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007506 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007507 if (D->isBitField())
7508 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007509
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007510 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007511 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007512 RD = RD->getDefinition();
7513 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007514 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007515 ObjCContainerDecl *CDecl =
7516 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7517 // ivar in class extensions requires special treatment.
7518 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7519 CDecl = CatDecl->getClassInterface();
7520 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007521 RecName += "_IMPL";
7522 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7523 SourceLocation(), SourceLocation(),
7524 &Context->Idents.get(RecName.c_str()));
7525 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7526 unsigned UnsignedIntSize =
7527 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7528 Expr *Zero = IntegerLiteral::Create(*Context,
7529 llvm::APInt(UnsignedIntSize, 0),
7530 Context->UnsignedIntTy, SourceLocation());
7531 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7532 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7533 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007534 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007535 SourceLocation(),
7536 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007537 IvarT, nullptr,
7538 /*BitWidth=*/nullptr,
7539 /*Mutable=*/true, ICIS_NoInit);
7540 MemberExpr *ME = new (Context)
7541 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7542 FD->getType(), VK_LValue, OK_Ordinary);
7543 IvarT = Context->getDecltypeType(ME, ME->getType());
7544 }
7545 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007546 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007547 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007548
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007549 castExpr = NoTypeInfoCStyleCastExpr(Context,
7550 castT,
7551 CK_BitCast,
7552 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007553
7554
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007555 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007556 VK_LValue, OK_Ordinary,
7557 SourceLocation());
7558 PE = new (Context) ParenExpr(OldRange.getBegin(),
7559 OldRange.getEnd(),
7560 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007561
7562 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007563 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007564 SourceLocation(),
7565 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007566 D->getType(), nullptr,
7567 /*BitWidth=*/D->getBitWidth(),
7568 /*Mutable=*/true, ICIS_NoInit);
7569 MemberExpr *ME = new (Context)
7570 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7571 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7572 Replacement = ME;
7573
7574 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007575 else
7576 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007577 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007578
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007579 ReplaceStmtWithRange(IV, Replacement, OldRange);
7580 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007581}
Alp Toker0621cb22014-07-16 16:48:33 +00007582
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007583#endif // CLANG_ENABLE_OBJC_REWRITER