blob: c97fa979f6056e6cb47e20aaf5d664cf25b82dad [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
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000138
Fariborz Jahanian11671902012-02-07 17:11:38 +0000139 // Block related declarations.
140 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142 SmallVector<ValueDecl *, 8> BlockByRefDecls;
143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
147
148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000149 llvm::DenseMap<ObjCInterfaceDecl *,
150 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
151
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000152 // ivar bitfield grouping containers
153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155 // This container maps an <class, group number for ivar> tuple to the type
156 // of the struct where the bitfield belongs.
157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000159
Fariborz Jahanian11671902012-02-07 17:11:38 +0000160 // This maps an original source AST to it's rewritten form. This allows
161 // us to avoid rewriting the same node twice (which is very uncommon).
162 // This is needed to support some of the exotic property rewriting.
163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
164
165 // Needed for header files being rewritten
166 bool IsHeader;
167 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000168 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000169 bool objc_impl_method;
170
171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
174 bool SavedValue;
175
176 public:
177 DisableReplaceStmtScope(RewriteModernObjC &R)
178 : R(R), SavedValue(R.DisableReplaceStmt) {
179 R.DisableReplaceStmt = true;
180 }
181 ~DisableReplaceStmtScope() {
182 R.DisableReplaceStmt = SavedValue;
183 }
184 };
185 void InitializeCommon(ASTContext &context);
186
187 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
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 }
238 return;
239 }
240
Fariborz Jahanian11671902012-02-07 17:11:38 +0000241 void HandleTopLevelSingleDecl(Decl *D);
242 void HandleDeclInMainFile(Decl *D);
243 RewriteModernObjC(std::string inFile, raw_ostream *OS,
244 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000245 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000246
247 ~RewriteModernObjC() {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000248
249 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000250
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
252 Stmt *ReplacingStmt = ReplacedNodes[Old];
253
254 if (ReplacingStmt)
255 return; // We can't rewrite the same node twice.
256
257 if (DisableReplaceStmt)
258 return;
259
260 // If replacement succeeded or warning disabled return with no warning.
261 if (!Rewrite.ReplaceStmt(Old, New)) {
262 ReplacedNodes[Old] = New;
263 return;
264 }
265 if (SilenceRewriteMacroWarning)
266 return;
267 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
268 << Old->getSourceRange();
269 }
270
271 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000272 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000273 if (DisableReplaceStmt)
274 return;
275
276 // Measure the old text.
277 int Size = Rewrite.getRangeSize(SrcRange);
278 if (Size == -1) {
279 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
280 << Old->getSourceRange();
281 return;
282 }
283 // Get the new text.
284 std::string SStr;
285 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000286 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000287 const std::string &Str = S.str();
288
289 // If replacement succeeded or warning disabled return with no warning.
290 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
291 ReplacedNodes[Old] = New;
292 return;
293 }
294 if (SilenceRewriteMacroWarning)
295 return;
296 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
297 << Old->getSourceRange();
298 }
299
300 void InsertText(SourceLocation Loc, StringRef Str,
301 bool InsertAfter = true) {
302 // If insertion succeeded or warning disabled return with no warning.
303 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
304 SilenceRewriteMacroWarning)
305 return;
306
307 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
308 }
309
310 void ReplaceText(SourceLocation Start, unsigned OrigLength,
311 StringRef Str) {
312 // If removal succeeded or warning disabled return with no warning.
313 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
314 SilenceRewriteMacroWarning)
315 return;
316
317 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
318 }
319
320 // Syntactic Rewriting.
321 void RewriteRecordBody(RecordDecl *RD);
322 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000323 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000324 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
325 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000326 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000327 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000328 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
329 const std::string &typedefString);
330 void RewriteImplementations();
331 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
332 ObjCImplementationDecl *IMD,
333 ObjCCategoryImplDecl *CID);
334 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
335 void RewriteImplementationDecl(Decl *Dcl);
336 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
337 ObjCMethodDecl *MDecl, std::string &ResultStr);
338 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
339 const FunctionType *&FPRetType);
340 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
341 ValueDecl *VD, bool def=false);
342 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
343 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
344 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000345 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
347 void RewriteProperty(ObjCPropertyDecl *prop);
348 void RewriteFunctionDecl(FunctionDecl *FD);
349 void RewriteBlockPointerType(std::string& Str, QualType Type);
350 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000351 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000352 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
353 void RewriteTypeOfDecl(VarDecl *VD);
354 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000355
356 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000357
358 // Expression Rewriting.
359 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
360 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
361 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
362 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
363 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
364 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
365 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000366 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000367 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000368 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000369 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000371 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000372 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000373 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
374 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
375 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
376 SourceLocation OrigEnd);
377 Stmt *RewriteBreakStmt(BreakStmt *S);
378 Stmt *RewriteContinueStmt(ContinueStmt *S);
379 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000380 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000381 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000382
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000383 // Computes ivar bitfield group no.
384 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
385 // Names field decl. for ivar bitfield group.
386 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
387 // Names struct type for ivar bitfield group.
388 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
389 // Names symbol for ivar bitfield group field offset.
390 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
391 // Given an ivar bitfield, it builds (or finds) its group record type.
392 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
393 QualType SynthesizeBitfieldGroupStructType(
394 ObjCIvarDecl *IV,
395 SmallVectorImpl<ObjCIvarDecl *> &IVars);
396
Fariborz Jahanian11671902012-02-07 17:11:38 +0000397 // Block rewriting.
398 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
399
400 // Block specific rewrite rules.
401 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000402 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000403 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000404 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
405 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
406
407 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
408 std::string &Result);
409
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000410 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000411 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000412 bool &IsNamedDefinition);
413 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
414 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000415
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000416 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
417
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000418 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
419 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000420
421 void Initialize(ASTContext &context) override;
422
Benjamin Kramer474261a2012-06-02 10:20:41 +0000423 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000424 // rewriting routines on the new ASTs.
425 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
426 Expr **args, unsigned nargs,
427 SourceLocation StartLoc=SourceLocation(),
428 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000429
430 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000431 QualType returnType,
432 SmallVectorImpl<QualType> &ArgTypes,
433 SmallVectorImpl<Expr*> &MsgExprs,
434 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000435
436 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
437 SourceLocation StartLoc=SourceLocation(),
438 SourceLocation EndLoc=SourceLocation());
439
440 void SynthCountByEnumWithState(std::string &buf);
441 void SynthMsgSendFunctionDecl();
442 void SynthMsgSendSuperFunctionDecl();
443 void SynthMsgSendStretFunctionDecl();
444 void SynthMsgSendFpretFunctionDecl();
445 void SynthMsgSendSuperStretFunctionDecl();
446 void SynthGetClassFunctionDecl();
447 void SynthGetMetaClassFunctionDecl();
448 void SynthGetSuperClassFunctionDecl();
449 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000450 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000451
452 // Rewriting metadata
453 template<typename MethodIterator>
454 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
455 MethodIterator MethodEnd,
456 bool IsInstanceMethod,
457 StringRef prefix,
458 StringRef ClassName,
459 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000460 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 const ObjCList<ObjCProtocolDecl> &Prots,
464 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000465 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000466 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000467 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000468
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000469 void RewriteMetaDataIntoBuffer(std::string &Result);
470 void WriteImageInfo(std::string &Result);
471 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000472 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474
475 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000476 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000477 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000478 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000479
480
481 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
482 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
483 StringRef funcName, std::string Tag);
484 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
485 StringRef funcName, std::string Tag);
486 std::string SynthesizeBlockImpl(BlockExpr *CE,
487 std::string Tag, std::string Desc);
488 std::string SynthesizeBlockDescriptor(std::string DescTag,
489 std::string ImplTag,
490 int i, StringRef funcName,
491 unsigned hasCopy);
492 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
493 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
494 StringRef FunName);
495 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
496 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000497 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000498
499 // Misc. helper routines.
500 QualType getProtocolType();
501 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000502 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
503 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
504 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
505
506 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
507 void CollectBlockDeclRefInfo(BlockExpr *Exp);
508 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000509 void GetInnerBlockDeclRefExprs(Stmt *S,
510 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000511 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
512
513 // We avoid calling Type::isBlockPointerType(), since it operates on the
514 // canonical type. We only care if the top-level type is a closure pointer.
515 bool isTopLevelBlockPointerType(QualType T) {
516 return isa<BlockPointerType>(T);
517 }
518
519 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
520 /// to a function pointer type and upon success, returns true; false
521 /// otherwise.
522 bool convertBlockPointerToFunctionPointer(QualType &T) {
523 if (isTopLevelBlockPointerType(T)) {
524 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
525 T = Context->getPointerType(BPT->getPointeeType());
526 return true;
527 }
528 return false;
529 }
530
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000531 bool convertObjCTypeToCStyleType(QualType &T);
532
Fariborz Jahanian11671902012-02-07 17:11:38 +0000533 bool needToScanForQualifiers(QualType T);
534 QualType getSuperStructType();
535 QualType getConstantStringStructType();
536 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
537 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
538
539 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000540 if (T->isObjCQualifiedIdType()) {
541 bool isConst = T.isConstQualified();
542 T = isConst ? Context->getObjCIdType().withConst()
543 : Context->getObjCIdType();
544 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000545 else if (T->isObjCQualifiedClassType())
546 T = Context->getObjCClassType();
547 else if (T->isObjCObjectPointerType() &&
548 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
549 if (const ObjCObjectPointerType * OBJPT =
550 T->getAsObjCInterfacePointerType()) {
551 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
552 T = QualType(IFaceT, 0);
553 T = Context->getPointerType(T);
554 }
555 }
556 }
557
558 // FIXME: This predicate seems like it would be useful to add to ASTContext.
559 bool isObjCType(QualType T) {
560 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
561 return false;
562
563 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
564
565 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
566 OCT == Context->getCanonicalType(Context->getObjCClassType()))
567 return true;
568
569 if (const PointerType *PT = OCT->getAs<PointerType>()) {
570 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
571 PT->getPointeeType()->isObjCQualifiedIdType())
572 return true;
573 }
574 return false;
575 }
576 bool PointerTypeTakesAnyBlockArguments(QualType QT);
577 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
578 void GetExtentOfArgList(const char *Name, const char *&LParen,
579 const char *&RParen);
580
581 void QuoteDoublequotes(std::string &From, std::string &To) {
582 for (unsigned i = 0; i < From.length(); i++) {
583 if (From[i] == '"')
584 To += "\\\"";
585 else
586 To += From[i];
587 }
588 }
589
590 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000591 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000592 bool variadic = false) {
593 if (result == Context->getObjCInstanceType())
594 result = Context->getObjCIdType();
595 FunctionProtoType::ExtProtoInfo fpi;
596 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000597 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000598 }
599
600 // Helper function: create a CStyleCastExpr with trivial type source info.
601 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
602 CastKind Kind, Expr *E) {
603 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000604 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
605 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000606 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000607
608 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
609 IdentifierInfo* II = &Context->Idents.get("load");
610 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000611 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000612 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000613
614 StringLiteral *getStringLiteral(StringRef Str) {
615 QualType StrType = Context->getConstantArrayType(
616 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
617 0);
618 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
619 /*Pascal=*/false, StrType, SourceLocation());
620 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000621 };
622
623}
624
625void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
626 NamedDecl *D) {
627 if (const FunctionProtoType *fproto
628 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000629 for (const auto &I : fproto->param_types())
630 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000631 // All the args are checked/rewritten. Don't call twice!
632 RewriteBlockPointerDecl(D);
633 break;
634 }
635 }
636}
637
638void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
639 const PointerType *PT = funcType->getAs<PointerType>();
640 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
641 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
642}
643
644static bool IsHeaderFile(const std::string &Filename) {
645 std::string::size_type DotPos = Filename.rfind('.');
646
647 if (DotPos == std::string::npos) {
648 // no file extension
649 return false;
650 }
651
652 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
653 // C header: .h
654 // C++ header: .hh or .H;
655 return Ext == "h" || Ext == "hh" || Ext == "H";
656}
657
658RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
659 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000660 bool silenceMacroWarn,
661 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000662 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000663 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000664 IsHeader = IsHeaderFile(inFile);
665 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
666 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000667 // FIXME. This should be an error. But if block is not called, it is OK. And it
668 // may break including some headers.
669 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
670 "rewriting block literal declared in global scope is not implemented");
671
Fariborz Jahanian11671902012-02-07 17:11:38 +0000672 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
673 DiagnosticsEngine::Warning,
674 "rewriter doesn't support user-specified control flow semantics "
675 "for @try/@finally (code may not execute properly)");
676}
677
David Blaikiea51666a2014-07-17 20:40:36 +0000678std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
679 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
680 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
681 return llvm::make_unique<RewriteModernObjC>(
682 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000683}
684
685void RewriteModernObjC::InitializeCommon(ASTContext &context) {
686 Context = &context;
687 SM = &Context->getSourceManager();
688 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000689 MsgSendFunctionDecl = nullptr;
690 MsgSendSuperFunctionDecl = nullptr;
691 MsgSendStretFunctionDecl = nullptr;
692 MsgSendSuperStretFunctionDecl = nullptr;
693 MsgSendFpretFunctionDecl = nullptr;
694 GetClassFunctionDecl = nullptr;
695 GetMetaClassFunctionDecl = nullptr;
696 GetSuperClassFunctionDecl = nullptr;
697 SelGetUidFunctionDecl = nullptr;
698 CFStringFunctionDecl = nullptr;
699 ConstantStringClassReference = nullptr;
700 NSStringRecord = nullptr;
701 CurMethodDef = nullptr;
702 CurFunctionDef = nullptr;
703 GlobalVarDecl = nullptr;
704 GlobalConstructionExp = nullptr;
705 SuperStructDecl = nullptr;
706 ProtocolTypeDecl = nullptr;
707 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000708 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000709 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000710 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000711 PropParentMap = nullptr;
712 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000713 DisableReplaceStmt = false;
714 objc_impl_method = false;
715
716 // Get the ID and start/end of the main file.
717 MainFileID = SM->getMainFileID();
718 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
719 MainFileStart = MainBuf->getBufferStart();
720 MainFileEnd = MainBuf->getBufferEnd();
721
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000723}
724
725//===----------------------------------------------------------------------===//
726// Top Level Driver Code
727//===----------------------------------------------------------------------===//
728
729void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
730 if (Diags.hasErrorOccurred())
731 return;
732
733 // Two cases: either the decl could be in the main file, or it could be in a
734 // #included file. If the former, rewrite it now. If the later, check to see
735 // if we rewrote the #include/#import.
736 SourceLocation Loc = D->getLocation();
737 Loc = SM->getExpansionLoc(Loc);
738
739 // If this is for a builtin, ignore it.
740 if (Loc.isInvalid()) return;
741
742 // Look for built-in declarations that we need to refer during the rewrite.
743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
744 RewriteFunctionDecl(FD);
745 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
746 // declared in <Foundation/NSString.h>
747 if (FVD->getName() == "_NSConstantStringClassReference") {
748 ConstantStringClassReference = FVD;
749 return;
750 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000751 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
752 RewriteCategoryDecl(CD);
753 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
754 if (PD->isThisDeclarationADefinition())
755 RewriteProtocolDecl(PD);
756 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000757 // FIXME. This will not work in all situations and leaving it out
758 // is harmless.
759 // RewriteLinkageSpec(LSD);
760
Fariborz Jahanian11671902012-02-07 17:11:38 +0000761 // Recurse into linkage specifications
762 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
763 DIEnd = LSD->decls_end();
764 DI != DIEnd; ) {
765 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
766 if (!IFace->isThisDeclarationADefinition()) {
767 SmallVector<Decl *, 8> DG;
768 SourceLocation StartLoc = IFace->getLocStart();
769 do {
770 if (isa<ObjCInterfaceDecl>(*DI) &&
771 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
772 StartLoc == (*DI)->getLocStart())
773 DG.push_back(*DI);
774 else
775 break;
776
777 ++DI;
778 } while (DI != DIEnd);
779 RewriteForwardClassDecl(DG);
780 continue;
781 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000782 else {
783 // Keep track of all interface declarations seen.
784 ObjCInterfacesSeen.push_back(IFace);
785 ++DI;
786 continue;
787 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000788 }
789
790 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
791 if (!Proto->isThisDeclarationADefinition()) {
792 SmallVector<Decl *, 8> DG;
793 SourceLocation StartLoc = Proto->getLocStart();
794 do {
795 if (isa<ObjCProtocolDecl>(*DI) &&
796 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
797 StartLoc == (*DI)->getLocStart())
798 DG.push_back(*DI);
799 else
800 break;
801
802 ++DI;
803 } while (DI != DIEnd);
804 RewriteForwardProtocolDecl(DG);
805 continue;
806 }
807 }
808
809 HandleTopLevelSingleDecl(*DI);
810 ++DI;
811 }
812 }
813 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000814 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000815 return HandleDeclInMainFile(D);
816}
817
818//===----------------------------------------------------------------------===//
819// Syntactic (non-AST) Rewriting Code
820//===----------------------------------------------------------------------===//
821
822void RewriteModernObjC::RewriteInclude() {
823 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
824 StringRef MainBuf = SM->getBufferData(MainFileID);
825 const char *MainBufStart = MainBuf.begin();
826 const char *MainBufEnd = MainBuf.end();
827 size_t ImportLen = strlen("import");
828
829 // Loop over the whole file, looking for includes.
830 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
831 if (*BufPtr == '#') {
832 if (++BufPtr == MainBufEnd)
833 return;
834 while (*BufPtr == ' ' || *BufPtr == '\t')
835 if (++BufPtr == MainBufEnd)
836 return;
837 if (!strncmp(BufPtr, "import", ImportLen)) {
838 // replace import with include
839 SourceLocation ImportLoc =
840 LocStart.getLocWithOffset(BufPtr-MainBufStart);
841 ReplaceText(ImportLoc, ImportLen, "include");
842 BufPtr += ImportLen;
843 }
844 }
845 }
846}
847
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000848static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
849 ObjCIvarDecl *IvarDecl, std::string &Result) {
850 Result += "OBJC_IVAR_$_";
851 Result += IDecl->getName();
852 Result += "$";
853 Result += IvarDecl->getName();
854}
855
856std::string
857RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
858 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
859
860 // Build name of symbol holding ivar offset.
861 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000862 if (D->isBitField())
863 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
864 else
865 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000866
867
868 std::string S = "(*(";
869 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000870 if (D->isBitField())
871 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000872
873 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
874 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
875 RD = RD->getDefinition();
876 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
877 // decltype(((Foo_IMPL*)0)->bar) *
878 ObjCContainerDecl *CDecl =
879 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
880 // ivar in class extensions requires special treatment.
881 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
882 CDecl = CatDecl->getClassInterface();
883 std::string RecName = CDecl->getName();
884 RecName += "_IMPL";
885 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
886 SourceLocation(), SourceLocation(),
887 &Context->Idents.get(RecName.c_str()));
888 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
889 unsigned UnsignedIntSize =
890 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
891 Expr *Zero = IntegerLiteral::Create(*Context,
892 llvm::APInt(UnsignedIntSize, 0),
893 Context->UnsignedIntTy, SourceLocation());
894 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
895 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
896 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000897 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000898 SourceLocation(),
899 &Context->Idents.get(D->getNameAsString()),
Craig Topper8ae12032014-05-07 06:21:57 +0000900 IvarT, nullptr,
901 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000902 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000903 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
904 FD->getType(), VK_LValue,
905 OK_Ordinary);
906 IvarT = Context->getDecltypeType(ME, ME->getType());
907 }
908 }
909 convertObjCTypeToCStyleType(IvarT);
910 QualType castT = Context->getPointerType(IvarT);
911 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
912 S += TypeString;
913 S += ")";
914
915 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
916 S += "((char *)self + ";
917 S += IvarOffsetName;
918 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000919 if (D->isBitField()) {
920 S += ".";
921 S += D->getNameAsString();
922 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000923 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000924 return S;
925}
926
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000927/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
928/// been found in the class implementation. In this case, it must be synthesized.
929static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
930 ObjCPropertyDecl *PD,
931 bool getter) {
932 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
933 : !IMP->getInstanceMethod(PD->getSetterName());
934
935}
936
Fariborz Jahanian11671902012-02-07 17:11:38 +0000937void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
938 ObjCImplementationDecl *IMD,
939 ObjCCategoryImplDecl *CID) {
940 static bool objcGetPropertyDefined = false;
941 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000942 SourceLocation startGetterSetterLoc;
943
944 if (PID->getLocStart().isValid()) {
945 SourceLocation startLoc = PID->getLocStart();
946 InsertText(startLoc, "// ");
947 const char *startBuf = SM->getCharacterData(startLoc);
948 assert((*startBuf == '@') && "bogus @synthesize location");
949 const char *semiBuf = strchr(startBuf, ';');
950 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
951 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
952 }
953 else
954 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000955
956 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
957 return; // FIXME: is this correct?
958
959 // Generate the 'getter' function.
960 ObjCPropertyDecl *PD = PID->getPropertyDecl();
961 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000962 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000963
Bill Wendling44426052012-12-20 19:22:21 +0000964 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000965 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000966 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
967 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000968 ObjCPropertyDecl::OBJC_PR_copy));
969 std::string Getr;
970 if (GenGetProperty && !objcGetPropertyDefined) {
971 objcGetPropertyDefined = true;
972 // FIXME. Is this attribute correct in all cases?
973 Getr = "\nextern \"C\" __declspec(dllimport) "
974 "id objc_getProperty(id, SEL, long, bool);\n";
975 }
976 RewriteObjCMethodDecl(OID->getContainingInterface(),
977 PD->getGetterMethodDecl(), Getr);
978 Getr += "{ ";
979 // Synthesize an explicit cast to gain access to the ivar.
980 // See objc-act.c:objc_synthesize_new_getter() for details.
981 if (GenGetProperty) {
982 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
983 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000984 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000985 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000986 FPRetType);
987 Getr += " _TYPE";
988 if (FPRetType) {
989 Getr += ")"; // close the precedence "scope" for "*".
990
991 // Now, emit the argument types (if any).
992 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
993 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000994 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000995 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 std::string ParamStr =
997 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000998 Getr += ParamStr;
999 }
1000 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001001 if (FT->getNumParams())
1002 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001003 Getr += "...";
1004 }
1005 Getr += ")";
1006 } else
1007 Getr += "()";
1008 }
1009 Getr += ";\n";
1010 Getr += "return (_TYPE)";
1011 Getr += "objc_getProperty(self, _cmd, ";
1012 RewriteIvarOffsetComputation(OID, Getr);
1013 Getr += ", 1)";
1014 }
1015 else
1016 Getr += "return " + getIvarAccessString(OID);
1017 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001018 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001019 }
1020
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001021 if (PD->isReadOnly() ||
1022 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001023 return;
1024
1025 // Generate the 'setter' function.
1026 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001027 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001028 ObjCPropertyDecl::OBJC_PR_copy);
1029 if (GenSetProperty && !objcSetPropertyDefined) {
1030 objcSetPropertyDefined = true;
1031 // FIXME. Is this attribute correct in all cases?
1032 Setr = "\nextern \"C\" __declspec(dllimport) "
1033 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1034 }
1035
1036 RewriteObjCMethodDecl(OID->getContainingInterface(),
1037 PD->getSetterMethodDecl(), Setr);
1038 Setr += "{ ";
1039 // Synthesize an explicit cast to initialize the ivar.
1040 // See objc-act.c:objc_synthesize_new_setter() for details.
1041 if (GenSetProperty) {
1042 Setr += "objc_setProperty (self, _cmd, ";
1043 RewriteIvarOffsetComputation(OID, Setr);
1044 Setr += ", (id)";
1045 Setr += PD->getName();
1046 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001047 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001048 Setr += "0, ";
1049 else
1050 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001051 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001052 Setr += "1)";
1053 else
1054 Setr += "0)";
1055 }
1056 else {
1057 Setr += getIvarAccessString(OID) + " = ";
1058 Setr += PD->getName();
1059 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001060 Setr += "; }\n";
1061 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001062}
1063
1064static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1065 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001066 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001067 typedefString += ForwardDecl->getNameAsString();
1068 typedefString += "\n";
1069 typedefString += "#define _REWRITER_typedef_";
1070 typedefString += ForwardDecl->getNameAsString();
1071 typedefString += "\n";
1072 typedefString += "typedef struct objc_object ";
1073 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001074 // typedef struct { } _objc_exc_Classname;
1075 typedefString += ";\ntypedef struct {} _objc_exc_";
1076 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001077 typedefString += ";\n#endif\n";
1078}
1079
1080void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1081 const std::string &typedefString) {
1082 SourceLocation startLoc = ClassDecl->getLocStart();
1083 const char *startBuf = SM->getCharacterData(startLoc);
1084 const char *semiPtr = strchr(startBuf, ';');
1085 // Replace the @class with typedefs corresponding to the classes.
1086 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1087}
1088
1089void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1090 std::string typedefString;
1091 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001092 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1093 if (I == D.begin()) {
1094 // Translate to typedef's that forward reference structs with the same name
1095 // as the class. As a convenience, we include the original declaration
1096 // as a comment.
1097 typedefString += "// @class ";
1098 typedefString += ForwardDecl->getNameAsString();
1099 typedefString += ";";
1100 }
1101 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001102 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001103 else
1104 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001105 }
1106 DeclGroupRef::iterator I = D.begin();
1107 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1108}
1109
1110void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001111 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001112 std::string typedefString;
1113 for (unsigned i = 0; i < D.size(); i++) {
1114 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1115 if (i == 0) {
1116 typedefString += "// @class ";
1117 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001118 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001119 }
1120 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1121 }
1122 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1123}
1124
1125void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1126 // When method is a synthesized one, such as a getter/setter there is
1127 // nothing to rewrite.
1128 if (Method->isImplicit())
1129 return;
1130 SourceLocation LocStart = Method->getLocStart();
1131 SourceLocation LocEnd = Method->getLocEnd();
1132
1133 if (SM->getExpansionLineNumber(LocEnd) >
1134 SM->getExpansionLineNumber(LocStart)) {
1135 InsertText(LocStart, "#if 0\n");
1136 ReplaceText(LocEnd, 1, ";\n#endif\n");
1137 } else {
1138 InsertText(LocStart, "// ");
1139 }
1140}
1141
1142void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1143 SourceLocation Loc = prop->getAtLoc();
1144
1145 ReplaceText(Loc, 0, "// ");
1146 // FIXME: handle properties that are declared across multiple lines.
1147}
1148
1149void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1150 SourceLocation LocStart = CatDecl->getLocStart();
1151
1152 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001153 if (CatDecl->getIvarRBraceLoc().isValid()) {
1154 ReplaceText(LocStart, 1, "/** ");
1155 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1156 }
1157 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001158 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001159 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001160
Aaron Ballmand174edf2014-03-13 19:11:50 +00001161 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001162 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001163
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001164 for (auto *I : CatDecl->instance_methods())
1165 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001166 for (auto *I : CatDecl->class_methods())
1167 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001168
1169 // Lastly, comment out the @end.
1170 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001171 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001172}
1173
1174void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1175 SourceLocation LocStart = PDecl->getLocStart();
1176 assert(PDecl->isThisDeclarationADefinition());
1177
1178 // FIXME: handle protocol headers that are declared across multiple lines.
1179 ReplaceText(LocStart, 0, "// ");
1180
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001181 for (auto *I : PDecl->instance_methods())
1182 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001183 for (auto *I : PDecl->class_methods())
1184 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001185 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001186 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001187
1188 // Lastly, comment out the @end.
1189 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001190 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001191
1192 // Must comment out @optional/@required
1193 const char *startBuf = SM->getCharacterData(LocStart);
1194 const char *endBuf = SM->getCharacterData(LocEnd);
1195 for (const char *p = startBuf; p < endBuf; p++) {
1196 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1197 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1198 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1199
1200 }
1201 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1202 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1203 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1204
1205 }
1206 }
1207}
1208
1209void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1210 SourceLocation LocStart = (*D.begin())->getLocStart();
1211 if (LocStart.isInvalid())
1212 llvm_unreachable("Invalid SourceLocation");
1213 // FIXME: handle forward protocol that are declared across multiple lines.
1214 ReplaceText(LocStart, 0, "// ");
1215}
1216
1217void
Craig Topper5603df42013-07-05 19:34:19 +00001218RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001219 SourceLocation LocStart = DG[0]->getLocStart();
1220 if (LocStart.isInvalid())
1221 llvm_unreachable("Invalid SourceLocation");
1222 // FIXME: handle forward protocol that are declared across multiple lines.
1223 ReplaceText(LocStart, 0, "// ");
1224}
1225
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001226void
1227RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1228 SourceLocation LocStart = LSD->getExternLoc();
1229 if (LocStart.isInvalid())
1230 llvm_unreachable("Invalid extern SourceLocation");
1231
1232 ReplaceText(LocStart, 0, "// ");
1233 if (!LSD->hasBraces())
1234 return;
1235 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1236 SourceLocation LocRBrace = LSD->getRBraceLoc();
1237 if (LocRBrace.isInvalid())
1238 llvm_unreachable("Invalid rbrace SourceLocation");
1239 ReplaceText(LocRBrace, 0, "// ");
1240}
1241
Fariborz Jahanian11671902012-02-07 17:11:38 +00001242void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1243 const FunctionType *&FPRetType) {
1244 if (T->isObjCQualifiedIdType())
1245 ResultStr += "id";
1246 else if (T->isFunctionPointerType() ||
1247 T->isBlockPointerType()) {
1248 // needs special handling, since pointer-to-functions have special
1249 // syntax (where a decaration models use).
1250 QualType retType = T;
1251 QualType PointeeTy;
1252 if (const PointerType* PT = retType->getAs<PointerType>())
1253 PointeeTy = PT->getPointeeType();
1254 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1255 PointeeTy = BPT->getPointeeType();
1256 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001257 ResultStr +=
1258 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001259 ResultStr += "(*";
1260 }
1261 } else
1262 ResultStr += T.getAsString(Context->getPrintingPolicy());
1263}
1264
1265void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1266 ObjCMethodDecl *OMD,
1267 std::string &ResultStr) {
1268 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001269 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001270 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001271 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001272 ResultStr += " ";
1273
1274 // Unique method name
1275 std::string NameStr;
1276
1277 if (OMD->isInstanceMethod())
1278 NameStr += "_I_";
1279 else
1280 NameStr += "_C_";
1281
1282 NameStr += IDecl->getNameAsString();
1283 NameStr += "_";
1284
1285 if (ObjCCategoryImplDecl *CID =
1286 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1287 NameStr += CID->getNameAsString();
1288 NameStr += "_";
1289 }
1290 // Append selector names, replacing ':' with '_'
1291 {
1292 std::string selString = OMD->getSelector().getAsString();
1293 int len = selString.size();
1294 for (int i = 0; i < len; i++)
1295 if (selString[i] == ':')
1296 selString[i] = '_';
1297 NameStr += selString;
1298 }
1299 // Remember this name for metadata emission
1300 MethodInternalNames[OMD] = NameStr;
1301 ResultStr += NameStr;
1302
1303 // Rewrite arguments
1304 ResultStr += "(";
1305
1306 // invisible arguments
1307 if (OMD->isInstanceMethod()) {
1308 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1309 selfTy = Context->getPointerType(selfTy);
1310 if (!LangOpts.MicrosoftExt) {
1311 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1312 ResultStr += "struct ";
1313 }
1314 // When rewriting for Microsoft, explicitly omit the structure name.
1315 ResultStr += IDecl->getNameAsString();
1316 ResultStr += " *";
1317 }
1318 else
1319 ResultStr += Context->getObjCClassType().getAsString(
1320 Context->getPrintingPolicy());
1321
1322 ResultStr += " self, ";
1323 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1324 ResultStr += " _cmd";
1325
1326 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001327 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001328 ResultStr += ", ";
1329 if (PDecl->getType()->isObjCQualifiedIdType()) {
1330 ResultStr += "id ";
1331 ResultStr += PDecl->getNameAsString();
1332 } else {
1333 std::string Name = PDecl->getNameAsString();
1334 QualType QT = PDecl->getType();
1335 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001336 (void)convertBlockPointerToFunctionPointer(QT);
1337 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001338 ResultStr += Name;
1339 }
1340 }
1341 if (OMD->isVariadic())
1342 ResultStr += ", ...";
1343 ResultStr += ") ";
1344
1345 if (FPRetType) {
1346 ResultStr += ")"; // close the precedence "scope" for "*".
1347
1348 // Now, emit the argument types (if any).
1349 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1350 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001351 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001352 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001353 std::string ParamStr =
1354 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001355 ResultStr += ParamStr;
1356 }
1357 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001358 if (FT->getNumParams())
1359 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001360 ResultStr += "...";
1361 }
1362 ResultStr += ")";
1363 } else {
1364 ResultStr += "()";
1365 }
1366 }
1367}
1368void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1369 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1370 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1371
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001372 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001373 if (IMD->getIvarRBraceLoc().isValid()) {
1374 ReplaceText(IMD->getLocStart(), 1, "/** ");
1375 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001376 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001377 else {
1378 InsertText(IMD->getLocStart(), "// ");
1379 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001380 }
1381 else
1382 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001383
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001384 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001385 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001386 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1387 SourceLocation LocStart = OMD->getLocStart();
1388 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1389
1390 const char *startBuf = SM->getCharacterData(LocStart);
1391 const char *endBuf = SM->getCharacterData(LocEnd);
1392 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1393 }
1394
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001395 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001396 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001397 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1398 SourceLocation LocStart = OMD->getLocStart();
1399 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1400
1401 const char *startBuf = SM->getCharacterData(LocStart);
1402 const char *endBuf = SM->getCharacterData(LocEnd);
1403 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1404 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001405 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1406 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001407
1408 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1409}
1410
1411void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001412 // Do not synthesize more than once.
1413 if (ObjCSynthesizedStructs.count(ClassDecl))
1414 return;
1415 // Make sure super class's are written before current class is written.
1416 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1417 while (SuperClass) {
1418 RewriteInterfaceDecl(SuperClass);
1419 SuperClass = SuperClass->getSuperClass();
1420 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001421 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001422 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001423 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001424 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001425 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1426
Fariborz Jahanianff513382012-02-15 22:01:47 +00001427 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001428 // Mark this typedef as having been written into its c++ equivalent.
1429 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001430
Aaron Ballmand174edf2014-03-13 19:11:50 +00001431 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001432 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001433 for (auto *I : ClassDecl->instance_methods())
1434 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001435 for (auto *I : ClassDecl->class_methods())
1436 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001437
Fariborz Jahanianff513382012-02-15 22:01:47 +00001438 // Lastly, comment out the @end.
1439 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001440 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001441 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001442}
1443
1444Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1445 SourceRange OldRange = PseudoOp->getSourceRange();
1446
1447 // We just magically know some things about the structure of this
1448 // expression.
1449 ObjCMessageExpr *OldMsg =
1450 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1451 PseudoOp->getNumSemanticExprs() - 1));
1452
1453 // Because the rewriter doesn't allow us to rewrite rewritten code,
1454 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001455 Expr *Base;
1456 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001457 {
1458 DisableReplaceStmtScope S(*this);
1459
1460 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001461 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001462 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1463 Base = OldMsg->getInstanceReceiver();
1464 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1465 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1466 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001467
1468 unsigned numArgs = OldMsg->getNumArgs();
1469 for (unsigned i = 0; i < numArgs; i++) {
1470 Expr *Arg = OldMsg->getArg(i);
1471 if (isa<OpaqueValueExpr>(Arg))
1472 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1473 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1474 Args.push_back(Arg);
1475 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001476 }
1477
1478 // TODO: avoid this copy.
1479 SmallVector<SourceLocation, 1> SelLocs;
1480 OldMsg->getSelectorLocs(SelLocs);
1481
Craig Topper8ae12032014-05-07 06:21:57 +00001482 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001483 switch (OldMsg->getReceiverKind()) {
1484 case ObjCMessageExpr::Class:
1485 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1486 OldMsg->getValueKind(),
1487 OldMsg->getLeftLoc(),
1488 OldMsg->getClassReceiverTypeInfo(),
1489 OldMsg->getSelector(),
1490 SelLocs,
1491 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001492 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001493 OldMsg->getRightLoc(),
1494 OldMsg->isImplicit());
1495 break;
1496
1497 case ObjCMessageExpr::Instance:
1498 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1499 OldMsg->getValueKind(),
1500 OldMsg->getLeftLoc(),
1501 Base,
1502 OldMsg->getSelector(),
1503 SelLocs,
1504 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001505 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001506 OldMsg->getRightLoc(),
1507 OldMsg->isImplicit());
1508 break;
1509
1510 case ObjCMessageExpr::SuperClass:
1511 case ObjCMessageExpr::SuperInstance:
1512 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1513 OldMsg->getValueKind(),
1514 OldMsg->getLeftLoc(),
1515 OldMsg->getSuperLoc(),
1516 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1517 OldMsg->getSuperType(),
1518 OldMsg->getSelector(),
1519 SelLocs,
1520 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001521 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001522 OldMsg->getRightLoc(),
1523 OldMsg->isImplicit());
1524 break;
1525 }
1526
1527 Stmt *Replacement = SynthMessageExpr(NewMsg);
1528 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1529 return Replacement;
1530}
1531
1532Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1533 SourceRange OldRange = PseudoOp->getSourceRange();
1534
1535 // We just magically know some things about the structure of this
1536 // expression.
1537 ObjCMessageExpr *OldMsg =
1538 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1539
1540 // Because the rewriter doesn't allow us to rewrite rewritten code,
1541 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001542 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001543 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001544 {
1545 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001546 // Rebuild the base expression if we have one.
1547 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1548 Base = OldMsg->getInstanceReceiver();
1549 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1550 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1551 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001552 unsigned numArgs = OldMsg->getNumArgs();
1553 for (unsigned i = 0; i < numArgs; i++) {
1554 Expr *Arg = OldMsg->getArg(i);
1555 if (isa<OpaqueValueExpr>(Arg))
1556 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1557 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1558 Args.push_back(Arg);
1559 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001560 }
1561
1562 // Intentionally empty.
1563 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001564
Craig Topper8ae12032014-05-07 06:21:57 +00001565 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001566 switch (OldMsg->getReceiverKind()) {
1567 case ObjCMessageExpr::Class:
1568 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1569 OldMsg->getValueKind(),
1570 OldMsg->getLeftLoc(),
1571 OldMsg->getClassReceiverTypeInfo(),
1572 OldMsg->getSelector(),
1573 SelLocs,
1574 OldMsg->getMethodDecl(),
1575 Args,
1576 OldMsg->getRightLoc(),
1577 OldMsg->isImplicit());
1578 break;
1579
1580 case ObjCMessageExpr::Instance:
1581 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1582 OldMsg->getValueKind(),
1583 OldMsg->getLeftLoc(),
1584 Base,
1585 OldMsg->getSelector(),
1586 SelLocs,
1587 OldMsg->getMethodDecl(),
1588 Args,
1589 OldMsg->getRightLoc(),
1590 OldMsg->isImplicit());
1591 break;
1592
1593 case ObjCMessageExpr::SuperClass:
1594 case ObjCMessageExpr::SuperInstance:
1595 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1596 OldMsg->getValueKind(),
1597 OldMsg->getLeftLoc(),
1598 OldMsg->getSuperLoc(),
1599 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1600 OldMsg->getSuperType(),
1601 OldMsg->getSelector(),
1602 SelLocs,
1603 OldMsg->getMethodDecl(),
1604 Args,
1605 OldMsg->getRightLoc(),
1606 OldMsg->isImplicit());
1607 break;
1608 }
1609
1610 Stmt *Replacement = SynthMessageExpr(NewMsg);
1611 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1612 return Replacement;
1613}
1614
1615/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001616/// ((NSUInteger (*)
1617/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001618/// (void *)objc_msgSend)((id)l_collection,
1619/// sel_registerName(
1620/// "countByEnumeratingWithState:objects:count:"),
1621/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001622/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001623///
1624void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001625 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1626 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001627 buf += "\n\t\t";
1628 buf += "((id)l_collection,\n\t\t";
1629 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1630 buf += "\n\t\t";
1631 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001632 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001633}
1634
1635/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1636/// statement to exit to its outer synthesized loop.
1637///
1638Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1639 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1640 return S;
1641 // replace break with goto __break_label
1642 std::string buf;
1643
1644 SourceLocation startLoc = S->getLocStart();
1645 buf = "goto __break_label_";
1646 buf += utostr(ObjCBcLabelNo.back());
1647 ReplaceText(startLoc, strlen("break"), buf);
1648
Craig Topper8ae12032014-05-07 06:21:57 +00001649 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001650}
1651
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001652void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1653 SourceLocation Loc,
1654 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001655 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001656 LineString += "\n#line ";
1657 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1658 LineString += utostr(PLoc.getLine());
1659 LineString += " \"";
1660 LineString += Lexer::Stringify(PLoc.getFilename());
1661 LineString += "\"\n";
1662 }
1663}
1664
Fariborz Jahanian11671902012-02-07 17:11:38 +00001665/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1666/// statement to continue with its inner synthesized loop.
1667///
1668Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1669 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1670 return S;
1671 // replace continue with goto __continue_label
1672 std::string buf;
1673
1674 SourceLocation startLoc = S->getLocStart();
1675 buf = "goto __continue_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 ReplaceText(startLoc, strlen("continue"), buf);
1678
Craig Topper8ae12032014-05-07 06:21:57 +00001679 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001680}
1681
1682/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1683/// It rewrites:
1684/// for ( type elem in collection) { stmts; }
1685
1686/// Into:
1687/// {
1688/// type elem;
1689/// struct __objcFastEnumerationState enumState = { 0 };
1690/// id __rw_items[16];
1691/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001692/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001693/// objects:__rw_items count:16];
1694/// if (limit) {
1695/// unsigned long startMutations = *enumState.mutationsPtr;
1696/// do {
1697/// unsigned long counter = 0;
1698/// do {
1699/// if (startMutations != *enumState.mutationsPtr)
1700/// objc_enumerationMutation(l_collection);
1701/// elem = (type)enumState.itemsPtr[counter++];
1702/// stmts;
1703/// __continue_label: ;
1704/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001705/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1706/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001707/// elem = nil;
1708/// __break_label: ;
1709/// }
1710/// else
1711/// elem = nil;
1712/// }
1713///
1714Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1715 SourceLocation OrigEnd) {
1716 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1717 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1718 "ObjCForCollectionStmt Statement stack mismatch");
1719 assert(!ObjCBcLabelNo.empty() &&
1720 "ObjCForCollectionStmt - Label No stack empty");
1721
1722 SourceLocation startLoc = S->getLocStart();
1723 const char *startBuf = SM->getCharacterData(startLoc);
1724 StringRef elementName;
1725 std::string elementTypeAsString;
1726 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001727 // line directive first.
1728 SourceLocation ForEachLoc = S->getForLoc();
1729 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1730 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001731 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1732 // type elem;
1733 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1734 QualType ElementType = cast<ValueDecl>(D)->getType();
1735 if (ElementType->isObjCQualifiedIdType() ||
1736 ElementType->isObjCQualifiedInterfaceType())
1737 // Simply use 'id' for all qualified types.
1738 elementTypeAsString = "id";
1739 else
1740 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1741 buf += elementTypeAsString;
1742 buf += " ";
1743 elementName = D->getName();
1744 buf += elementName;
1745 buf += ";\n\t";
1746 }
1747 else {
1748 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1749 elementName = DR->getDecl()->getName();
1750 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1751 if (VD->getType()->isObjCQualifiedIdType() ||
1752 VD->getType()->isObjCQualifiedInterfaceType())
1753 // Simply use 'id' for all qualified types.
1754 elementTypeAsString = "id";
1755 else
1756 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1757 }
1758
1759 // struct __objcFastEnumerationState enumState = { 0 };
1760 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1761 // id __rw_items[16];
1762 buf += "id __rw_items[16];\n\t";
1763 // id l_collection = (id)
1764 buf += "id l_collection = (id)";
1765 // Find start location of 'collection' the hard way!
1766 const char *startCollectionBuf = startBuf;
1767 startCollectionBuf += 3; // skip 'for'
1768 startCollectionBuf = strchr(startCollectionBuf, '(');
1769 startCollectionBuf++; // skip '('
1770 // find 'in' and skip it.
1771 while (*startCollectionBuf != ' ' ||
1772 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1773 (*(startCollectionBuf+3) != ' ' &&
1774 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1775 startCollectionBuf++;
1776 startCollectionBuf += 3;
1777
1778 // Replace: "for (type element in" with string constructed thus far.
1779 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1780 // Replace ')' in for '(' type elem in collection ')' with ';'
1781 SourceLocation rightParenLoc = S->getRParenLoc();
1782 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1783 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1784 buf = ";\n\t";
1785
1786 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1787 // objects:__rw_items count:16];
1788 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001789 // NSUInteger limit =
1790 // ((NSUInteger (*)
1791 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001792 // (void *)objc_msgSend)((id)l_collection,
1793 // sel_registerName(
1794 // "countByEnumeratingWithState:objects:count:"),
1795 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001796 // (id *)__rw_items, (NSUInteger)16);
1797 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001798 SynthCountByEnumWithState(buf);
1799 buf += ";\n\t";
1800 /// if (limit) {
1801 /// unsigned long startMutations = *enumState.mutationsPtr;
1802 /// do {
1803 /// unsigned long counter = 0;
1804 /// do {
1805 /// if (startMutations != *enumState.mutationsPtr)
1806 /// objc_enumerationMutation(l_collection);
1807 /// elem = (type)enumState.itemsPtr[counter++];
1808 buf += "if (limit) {\n\t";
1809 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1810 buf += "do {\n\t\t";
1811 buf += "unsigned long counter = 0;\n\t\t";
1812 buf += "do {\n\t\t\t";
1813 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1814 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1815 buf += elementName;
1816 buf += " = (";
1817 buf += elementTypeAsString;
1818 buf += ")enumState.itemsPtr[counter++];";
1819 // Replace ')' in for '(' type elem in collection ')' with all of these.
1820 ReplaceText(lparenLoc, 1, buf);
1821
1822 /// __continue_label: ;
1823 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001824 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1825 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001826 /// elem = nil;
1827 /// __break_label: ;
1828 /// }
1829 /// else
1830 /// elem = nil;
1831 /// }
1832 ///
1833 buf = ";\n\t";
1834 buf += "__continue_label_";
1835 buf += utostr(ObjCBcLabelNo.back());
1836 buf += ": ;";
1837 buf += "\n\t\t";
1838 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001839 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001840 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001841 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001842 buf += elementName;
1843 buf += " = ((";
1844 buf += elementTypeAsString;
1845 buf += ")0);\n\t";
1846 buf += "__break_label_";
1847 buf += utostr(ObjCBcLabelNo.back());
1848 buf += ": ;\n\t";
1849 buf += "}\n\t";
1850 buf += "else\n\t\t";
1851 buf += elementName;
1852 buf += " = ((";
1853 buf += elementTypeAsString;
1854 buf += ")0);\n\t";
1855 buf += "}\n";
1856
1857 // Insert all these *after* the statement body.
1858 // FIXME: If this should support Obj-C++, support CXXTryStmt
1859 if (isa<CompoundStmt>(S->getBody())) {
1860 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1861 InsertText(endBodyLoc, buf);
1862 } else {
1863 /* Need to treat single statements specially. For example:
1864 *
1865 * for (A *a in b) if (stuff()) break;
1866 * for (A *a in b) xxxyy;
1867 *
1868 * The following code simply scans ahead to the semi to find the actual end.
1869 */
1870 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1871 const char *semiBuf = strchr(stmtBuf, ';');
1872 assert(semiBuf && "Can't find ';'");
1873 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1874 InsertText(endBodyLoc, buf);
1875 }
1876 Stmts.pop_back();
1877 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001878 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001879}
1880
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001881static void Write_RethrowObject(std::string &buf) {
1882 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1883 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1884 buf += "\tid rethrow;\n";
1885 buf += "\t} _fin_force_rethow(_rethrow);";
1886}
1887
Fariborz Jahanian11671902012-02-07 17:11:38 +00001888/// RewriteObjCSynchronizedStmt -
1889/// This routine rewrites @synchronized(expr) stmt;
1890/// into:
1891/// objc_sync_enter(expr);
1892/// @try stmt @finally { objc_sync_exit(expr); }
1893///
1894Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1895 // Get the start location and compute the semi location.
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 assert((*startBuf == '@') && "bogus @synchronized location");
1900
1901 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001902 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1903 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001904 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001905
Fariborz Jahanian11671902012-02-07 17:11:38 +00001906 const char *lparenBuf = startBuf;
1907 while (*lparenBuf != '(') lparenBuf++;
1908 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001909
1910 buf = "; objc_sync_enter(_sync_obj);\n";
1911 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1912 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1913 buf += "\n\tid sync_exit;";
1914 buf += "\n\t} _sync_exit(_sync_obj);\n";
1915
1916 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1917 // the sync expression is typically a message expression that's already
1918 // been rewritten! (which implies the SourceLocation's are invalid).
1919 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1920 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1921 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1922 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1923
1924 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1925 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1926 assert (*LBraceLocBuf == '{');
1927 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001928
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001929 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001930 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1931 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001932
1933 buf = "} catch (id e) {_rethrow = e;}\n";
1934 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001935 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001936 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001937
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001938 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001939
Craig Topper8ae12032014-05-07 06:21:57 +00001940 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001941}
1942
1943void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1944{
1945 // Perform a bottom up traversal of all children.
1946 for (Stmt::child_range CI = S->children(); CI; ++CI)
1947 if (*CI)
1948 WarnAboutReturnGotoStmts(*CI);
1949
1950 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1951 Diags.Report(Context->getFullLoc(S->getLocStart()),
1952 TryFinallyContainsReturnDiag);
1953 }
1954 return;
1955}
1956
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001957Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1958 SourceLocation startLoc = S->getAtLoc();
1959 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001960 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1961 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001962
1963 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001964}
1965
Fariborz Jahanian11671902012-02-07 17:11:38 +00001966Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001967 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001968 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001969 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001970 SourceLocation TryLocation = S->getAtTryLoc();
1971 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001972
1973 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001974 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001975 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001976 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001977 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001978 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001979 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001980 // Get the start location and compute the semi location.
1981 SourceLocation startLoc = S->getLocStart();
1982 const char *startBuf = SM->getCharacterData(startLoc);
1983
1984 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001985 if (finalStmt)
1986 ReplaceText(startLoc, 1, buf);
1987 else
1988 // @try -> try
1989 ReplaceText(startLoc, 1, "");
1990
Fariborz Jahanian11671902012-02-07 17:11:38 +00001991 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1992 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001993 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001994
Fariborz Jahanian11671902012-02-07 17:11:38 +00001995 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001996 bool AtRemoved = false;
1997 if (catchDecl) {
1998 QualType t = catchDecl->getType();
1999 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2000 // Should be a pointer to a class.
2001 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2002 if (IDecl) {
2003 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002004 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2005
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002006 startBuf = SM->getCharacterData(startLoc);
2007 assert((*startBuf == '@') && "bogus @catch location");
2008 SourceLocation rParenLoc = Catch->getRParenLoc();
2009 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2010
2011 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002012 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002013 Result += " *_"; Result += catchDecl->getNameAsString();
2014 Result += ")";
2015 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2016 // Foo *e = (Foo *)_e;
2017 Result.clear();
2018 Result = "{ ";
2019 Result += IDecl->getNameAsString();
2020 Result += " *"; Result += catchDecl->getNameAsString();
2021 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2022 Result += "_"; Result += catchDecl->getNameAsString();
2023
2024 Result += "; ";
2025 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2026 ReplaceText(lBraceLoc, 1, Result);
2027 AtRemoved = true;
2028 }
2029 }
2030 }
2031 if (!AtRemoved)
2032 // @catch -> catch
2033 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002034
Fariborz Jahanian11671902012-02-07 17:11:38 +00002035 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002036 if (finalStmt) {
2037 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002038 SourceLocation FinallyLoc = finalStmt->getLocStart();
2039
2040 if (noCatch) {
2041 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2042 buf += "catch (id e) {_rethrow = e;}\n";
2043 }
2044 else {
2045 buf += "}\n";
2046 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2047 buf += "catch (id e) {_rethrow = e;}\n";
2048 }
2049
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002050 SourceLocation startFinalLoc = finalStmt->getLocStart();
2051 ReplaceText(startFinalLoc, 8, buf);
2052 Stmt *body = finalStmt->getFinallyBody();
2053 SourceLocation startFinalBodyLoc = body->getLocStart();
2054 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002055 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002056 ReplaceText(startFinalBodyLoc, 1, buf);
2057
2058 SourceLocation endFinalBodyLoc = body->getLocEnd();
2059 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002060 // Now check for any return/continue/go statements within the @try.
2061 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002062 }
2063
Craig Topper8ae12032014-05-07 06:21:57 +00002064 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002065}
2066
2067// This can't be done with ReplaceStmt(S, ThrowExpr), since
2068// the throw expression is typically a message expression that's already
2069// been rewritten! (which implies the SourceLocation's are invalid).
2070Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2071 // Get the start location and compute the semi location.
2072 SourceLocation startLoc = S->getLocStart();
2073 const char *startBuf = SM->getCharacterData(startLoc);
2074
2075 assert((*startBuf == '@') && "bogus @throw location");
2076
2077 std::string buf;
2078 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2079 if (S->getThrowExpr())
2080 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002081 else
2082 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002083
2084 // handle "@ throw" correctly.
2085 const char *wBuf = strchr(startBuf, 'w');
2086 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2087 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2088
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002089 SourceLocation endLoc = S->getLocEnd();
2090 const char *endBuf = SM->getCharacterData(endLoc);
2091 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002092 assert((*semiBuf == ';') && "@throw: can't find ';'");
2093 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002094 if (S->getThrowExpr())
2095 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002096 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002097}
2098
2099Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2100 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002101 std::string StrEncoding;
2102 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002103 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002104 ReplaceStmt(Exp, Replacement);
2105
2106 // Replace this subexpr in the parent.
2107 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2108 return Replacement;
2109}
2110
2111Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2112 if (!SelGetUidFunctionDecl)
2113 SynthSelGetUidFunctionDecl();
2114 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2115 // Create a call to sel_registerName("selName").
2116 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002117 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002118 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2119 &SelExprs[0], SelExprs.size());
2120 ReplaceStmt(Exp, SelExp);
2121 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2122 return SelExp;
2123}
2124
2125CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2126 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2127 SourceLocation EndLoc) {
2128 // Get the type, we will need to reference it in a couple spots.
2129 QualType msgSendType = FD->getType();
2130
2131 // Create a reference to the objc_msgSend() declaration.
2132 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002133 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002134
2135 // Now, we cast the reference to a pointer to the objc_msgSend type.
2136 QualType pToFunc = Context->getPointerType(msgSendType);
2137 ImplicitCastExpr *ICE =
2138 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002139 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002140
2141 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2142
2143 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002144 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002145 FT->getCallResultType(*Context),
2146 VK_RValue, EndLoc);
2147 return Exp;
2148}
2149
2150static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2151 const char *&startRef, const char *&endRef) {
2152 while (startBuf < endBuf) {
2153 if (*startBuf == '<')
2154 startRef = startBuf; // mark the start.
2155 if (*startBuf == '>') {
2156 if (startRef && *startRef == '<') {
2157 endRef = startBuf; // mark the end.
2158 return true;
2159 }
2160 return false;
2161 }
2162 startBuf++;
2163 }
2164 return false;
2165}
2166
2167static void scanToNextArgument(const char *&argRef) {
2168 int angle = 0;
2169 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2170 if (*argRef == '<')
2171 angle++;
2172 else if (*argRef == '>')
2173 angle--;
2174 argRef++;
2175 }
2176 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2177}
2178
2179bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2180 if (T->isObjCQualifiedIdType())
2181 return true;
2182 if (const PointerType *PT = T->getAs<PointerType>()) {
2183 if (PT->getPointeeType()->isObjCQualifiedIdType())
2184 return true;
2185 }
2186 if (T->isObjCObjectPointerType()) {
2187 T = T->getPointeeType();
2188 return T->isObjCQualifiedInterfaceType();
2189 }
2190 if (T->isArrayType()) {
2191 QualType ElemTy = Context->getBaseElementType(T);
2192 return needToScanForQualifiers(ElemTy);
2193 }
2194 return false;
2195}
2196
2197void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2198 QualType Type = E->getType();
2199 if (needToScanForQualifiers(Type)) {
2200 SourceLocation Loc, EndLoc;
2201
2202 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2203 Loc = ECE->getLParenLoc();
2204 EndLoc = ECE->getRParenLoc();
2205 } else {
2206 Loc = E->getLocStart();
2207 EndLoc = E->getLocEnd();
2208 }
2209 // This will defend against trying to rewrite synthesized expressions.
2210 if (Loc.isInvalid() || EndLoc.isInvalid())
2211 return;
2212
2213 const char *startBuf = SM->getCharacterData(Loc);
2214 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002215 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002216 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2217 // Get the locations of the startRef, endRef.
2218 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2219 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2220 // Comment out the protocol references.
2221 InsertText(LessLoc, "/*");
2222 InsertText(GreaterLoc, "*/");
2223 }
2224 }
2225}
2226
2227void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2228 SourceLocation Loc;
2229 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002230 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002231 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2232 Loc = VD->getLocation();
2233 Type = VD->getType();
2234 }
2235 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2236 Loc = FD->getLocation();
2237 // Check for ObjC 'id' and class types that have been adorned with protocol
2238 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2239 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2240 assert(funcType && "missing function type");
2241 proto = dyn_cast<FunctionProtoType>(funcType);
2242 if (!proto)
2243 return;
Alp Toker314cc812014-01-25 16:55:45 +00002244 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002245 }
2246 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2247 Loc = FD->getLocation();
2248 Type = FD->getType();
2249 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002250 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2251 Loc = TD->getLocation();
2252 Type = TD->getUnderlyingType();
2253 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002254 else
2255 return;
2256
2257 if (needToScanForQualifiers(Type)) {
2258 // Since types are unique, we need to scan the buffer.
2259
2260 const char *endBuf = SM->getCharacterData(Loc);
2261 const char *startBuf = endBuf;
2262 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2263 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002264 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002265 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2266 // Get the locations of the startRef, endRef.
2267 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2268 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2269 // Comment out the protocol references.
2270 InsertText(LessLoc, "/*");
2271 InsertText(GreaterLoc, "*/");
2272 }
2273 }
2274 if (!proto)
2275 return; // most likely, was a variable
2276 // Now check arguments.
2277 const char *startBuf = SM->getCharacterData(Loc);
2278 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002279 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2280 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002281 // Since types are unique, we need to scan the buffer.
2282
2283 const char *endBuf = startBuf;
2284 // scan forward (from the decl location) for argument types.
2285 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002286 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002287 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2288 // Get the locations of the startRef, endRef.
2289 SourceLocation LessLoc =
2290 Loc.getLocWithOffset(startRef-startFuncBuf);
2291 SourceLocation GreaterLoc =
2292 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2293 // Comment out the protocol references.
2294 InsertText(LessLoc, "/*");
2295 InsertText(GreaterLoc, "*/");
2296 }
2297 startBuf = ++endBuf;
2298 }
2299 else {
2300 // If the function name is derived from a macro expansion, then the
2301 // argument buffer will not follow the name. Need to speak with Chris.
2302 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2303 startBuf++; // scan forward (from the decl location) for argument types.
2304 startBuf++;
2305 }
2306 }
2307}
2308
2309void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2310 QualType QT = ND->getType();
2311 const Type* TypePtr = QT->getAs<Type>();
2312 if (!isa<TypeOfExprType>(TypePtr))
2313 return;
2314 while (isa<TypeOfExprType>(TypePtr)) {
2315 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2316 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2317 TypePtr = QT->getAs<Type>();
2318 }
2319 // FIXME. This will not work for multiple declarators; as in:
2320 // __typeof__(a) b,c,d;
2321 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2322 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2323 const char *startBuf = SM->getCharacterData(DeclLoc);
2324 if (ND->getInit()) {
2325 std::string Name(ND->getNameAsString());
2326 TypeAsString += " " + Name + " = ";
2327 Expr *E = ND->getInit();
2328 SourceLocation startLoc;
2329 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2330 startLoc = ECE->getLParenLoc();
2331 else
2332 startLoc = E->getLocStart();
2333 startLoc = SM->getExpansionLoc(startLoc);
2334 const char *endBuf = SM->getCharacterData(startLoc);
2335 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2336 }
2337 else {
2338 SourceLocation X = ND->getLocEnd();
2339 X = SM->getExpansionLoc(X);
2340 const char *endBuf = SM->getCharacterData(X);
2341 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2342 }
2343}
2344
2345// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2346void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2347 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2348 SmallVector<QualType, 16> ArgTys;
2349 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2350 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002351 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002352 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002353 SourceLocation(),
2354 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002355 SelGetUidIdent, getFuncType,
2356 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002357}
2358
2359void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2360 // declared in <objc/objc.h>
2361 if (FD->getIdentifier() &&
2362 FD->getName() == "sel_registerName") {
2363 SelGetUidFunctionDecl = FD;
2364 return;
2365 }
2366 RewriteObjCQualifiedInterfaceTypes(FD);
2367}
2368
2369void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2370 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2371 const char *argPtr = TypeString.c_str();
2372 if (!strchr(argPtr, '^')) {
2373 Str += TypeString;
2374 return;
2375 }
2376 while (*argPtr) {
2377 Str += (*argPtr == '^' ? '*' : *argPtr);
2378 argPtr++;
2379 }
2380}
2381
2382// FIXME. Consolidate this routine with RewriteBlockPointerType.
2383void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2384 ValueDecl *VD) {
2385 QualType Type = VD->getType();
2386 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2387 const char *argPtr = TypeString.c_str();
2388 int paren = 0;
2389 while (*argPtr) {
2390 switch (*argPtr) {
2391 case '(':
2392 Str += *argPtr;
2393 paren++;
2394 break;
2395 case ')':
2396 Str += *argPtr;
2397 paren--;
2398 break;
2399 case '^':
2400 Str += '*';
2401 if (paren == 1)
2402 Str += VD->getNameAsString();
2403 break;
2404 default:
2405 Str += *argPtr;
2406 break;
2407 }
2408 argPtr++;
2409 }
2410}
2411
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002412void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2413 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2414 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2415 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2416 if (!proto)
2417 return;
Alp Toker314cc812014-01-25 16:55:45 +00002418 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002419 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2420 FdStr += " ";
2421 FdStr += FD->getName();
2422 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002423 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002424 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002425 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002426 RewriteBlockPointerType(FdStr, ArgType);
2427 if (i+1 < numArgs)
2428 FdStr += ", ";
2429 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002430 if (FD->isVariadic()) {
2431 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2432 }
2433 else
2434 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002435 InsertText(FunLocStart, FdStr);
2436}
2437
Benjamin Kramer60509af2013-09-09 14:48:42 +00002438// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2439void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2440 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002441 return;
2442 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2443 SmallVector<QualType, 16> ArgTys;
2444 QualType argT = Context->getObjCIdType();
2445 assert(!argT.isNull() && "Can't find 'id' type");
2446 ArgTys.push_back(argT);
2447 ArgTys.push_back(argT);
2448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002449 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002450 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002451 SourceLocation(),
2452 SourceLocation(),
2453 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002454 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002455}
2456
2457// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002469 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002472 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002473 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002474}
2475
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002476// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002477void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2478 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002479 SmallVector<QualType, 2> ArgTys;
2480 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002481 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002482 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002484 SourceLocation(),
2485 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002486 msgSendIdent, msgSendType,
2487 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002488}
2489
2490// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2491void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2493 SmallVector<QualType, 16> ArgTys;
2494 QualType argT = Context->getObjCIdType();
2495 assert(!argT.isNull() && "Can't find 'id' type");
2496 ArgTys.push_back(argT);
2497 argT = Context->getObjCSelType();
2498 assert(!argT.isNull() && "Can't find 'SEL' type");
2499 ArgTys.push_back(argT);
2500 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002501 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002502 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002503 SourceLocation(),
2504 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002505 msgSendIdent, msgSendType,
2506 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002507}
2508
2509// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002510// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002511void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2512 IdentifierInfo *msgSendIdent =
2513 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002514 SmallVector<QualType, 2> ArgTys;
2515 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002516 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002517 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002518 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519 SourceLocation(),
2520 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002521 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002522 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002523 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002524}
2525
2526// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2527void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2528 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2529 SmallVector<QualType, 16> ArgTys;
2530 QualType argT = Context->getObjCIdType();
2531 assert(!argT.isNull() && "Can't find 'id' type");
2532 ArgTys.push_back(argT);
2533 argT = Context->getObjCSelType();
2534 assert(!argT.isNull() && "Can't find 'SEL' type");
2535 ArgTys.push_back(argT);
2536 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002537 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002538 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002539 SourceLocation(),
2540 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002541 msgSendIdent, msgSendType,
2542 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002543}
2544
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002545// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546void RewriteModernObjC::SynthGetClassFunctionDecl() {
2547 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2548 SmallVector<QualType, 16> ArgTys;
2549 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002550 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002551 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002552 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002553 SourceLocation(),
2554 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002555 getClassIdent, getClassType,
2556 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002557}
2558
2559// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2560void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2561 IdentifierInfo *getSuperClassIdent =
2562 &Context->Idents.get("class_getSuperclass");
2563 SmallVector<QualType, 16> ArgTys;
2564 ArgTys.push_back(Context->getObjCClassType());
2565 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002566 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002567 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2568 SourceLocation(),
2569 SourceLocation(),
2570 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002571 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002572 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002573}
2574
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002575// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002576void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2577 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2578 SmallVector<QualType, 16> ArgTys;
2579 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002580 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002581 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002582 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002583 SourceLocation(),
2584 SourceLocation(),
2585 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002586 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002587}
2588
2589Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002590 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002591 QualType strType = getConstantStringStructType();
2592
2593 std::string S = "__NSConstantStringImpl_";
2594
2595 std::string tmpName = InFileName;
2596 unsigned i;
2597 for (i=0; i < tmpName.length(); i++) {
2598 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002599 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002600 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002601 tmpName[i] = '_';
2602 }
2603 S += tmpName;
2604 S += "_";
2605 S += utostr(NumObjCStringLiterals++);
2606
2607 Preamble += "static __NSConstantStringImpl " + S;
2608 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2609 Preamble += "0x000007c8,"; // utf8_str
2610 // The pretty printer for StringLiteral handles escape characters properly.
2611 std::string prettyBufS;
2612 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002613 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002614 Preamble += prettyBuf.str();
2615 Preamble += ",";
2616 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2617
2618 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2619 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002620 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002621 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002622 SourceLocation());
2623 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2624 Context->getPointerType(DRE->getType()),
2625 VK_RValue, OK_Ordinary,
2626 SourceLocation());
2627 // cast to NSConstantString *
2628 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2629 CK_CPointerToObjCPointerCast, Unop);
2630 ReplaceStmt(Exp, cast);
2631 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2632 return cast;
2633}
2634
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002635Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2636 unsigned IntSize =
2637 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2638
2639 Expr *FlagExp = IntegerLiteral::Create(*Context,
2640 llvm::APInt(IntSize, Exp->getValue()),
2641 Context->IntTy, Exp->getLocation());
2642 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2643 CK_BitCast, FlagExp);
2644 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2645 cast);
2646 ReplaceStmt(Exp, PE);
2647 return PE;
2648}
2649
Patrick Beard0caa3942012-04-19 00:25:12 +00002650Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002651 // synthesize declaration of helper functions needed in this routine.
2652 if (!SelGetUidFunctionDecl)
2653 SynthSelGetUidFunctionDecl();
2654 // use objc_msgSend() for all.
2655 if (!MsgSendFunctionDecl)
2656 SynthMsgSendFunctionDecl();
2657 if (!GetClassFunctionDecl)
2658 SynthGetClassFunctionDecl();
2659
2660 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2661 SourceLocation StartLoc = Exp->getLocStart();
2662 SourceLocation EndLoc = Exp->getLocEnd();
2663
2664 // Synthesize a call to objc_msgSend().
2665 SmallVector<Expr*, 4> MsgExprs;
2666 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002667
Patrick Beard0caa3942012-04-19 00:25:12 +00002668 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2669 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2670 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002671
Patrick Beard0caa3942012-04-19 00:25:12 +00002672 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002673 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002674 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2675 &ClsExprs[0],
2676 ClsExprs.size(),
2677 StartLoc, EndLoc);
2678 MsgExprs.push_back(Cls);
2679
Patrick Beard0caa3942012-04-19 00:25:12 +00002680 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002681 // it will be the 2nd argument.
2682 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002683 SelExprs.push_back(
2684 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002685 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2686 &SelExprs[0], SelExprs.size(),
2687 StartLoc, EndLoc);
2688 MsgExprs.push_back(SelExp);
2689
Patrick Beard0caa3942012-04-19 00:25:12 +00002690 // User provided sub-expression is the 3rd, and last, argument.
2691 Expr *subExpr = Exp->getSubExpr();
2692 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002693 QualType type = ICE->getType();
2694 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2695 CastKind CK = CK_BitCast;
2696 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2697 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002698 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002699 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002700 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002701
2702 SmallVector<QualType, 4> ArgTypes;
2703 ArgTypes.push_back(Context->getObjCIdType());
2704 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002705 for (const auto PI : BoxingMethod->parameters())
2706 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002707
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002708 QualType returnType = Exp->getType();
2709 // Get the type, we will need to reference it in a couple spots.
2710 QualType msgSendType = MsgSendFlavor->getType();
2711
2712 // Create a reference to the objc_msgSend() declaration.
2713 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2714 VK_LValue, SourceLocation());
2715
2716 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002717 Context->getPointerType(Context->VoidTy),
2718 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002719
2720 // Now do the "normal" pointer to function cast.
2721 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002722 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002723 castType = Context->getPointerType(castType);
2724 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2725 cast);
2726
2727 // Don't forget the parens to enforce the proper binding.
2728 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2729
2730 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002731 CallExpr *CE = new (Context)
2732 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002733 ReplaceStmt(Exp, CE);
2734 return CE;
2735}
2736
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002737Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2738 // synthesize declaration of helper functions needed in this routine.
2739 if (!SelGetUidFunctionDecl)
2740 SynthSelGetUidFunctionDecl();
2741 // use objc_msgSend() for all.
2742 if (!MsgSendFunctionDecl)
2743 SynthMsgSendFunctionDecl();
2744 if (!GetClassFunctionDecl)
2745 SynthGetClassFunctionDecl();
2746
2747 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2748 SourceLocation StartLoc = Exp->getLocStart();
2749 SourceLocation EndLoc = Exp->getLocEnd();
2750
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002751 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002752 QualType IntQT = Context->IntTy;
2753 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002754 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002755 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002756 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2757 DeclRefExpr *NSArrayDRE =
2758 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2759 SourceLocation());
2760
2761 SmallVector<Expr*, 16> InitExprs;
2762 unsigned NumElements = Exp->getNumElements();
2763 unsigned UnsignedIntSize =
2764 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2765 Expr *count = IntegerLiteral::Create(*Context,
2766 llvm::APInt(UnsignedIntSize, NumElements),
2767 Context->UnsignedIntTy, SourceLocation());
2768 InitExprs.push_back(count);
2769 for (unsigned i = 0; i < NumElements; i++)
2770 InitExprs.push_back(Exp->getElement(i));
2771 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002772 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002773 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002774
2775 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002776 SourceLocation(),
2777 &Context->Idents.get("arr"),
Craig Topper8ae12032014-05-07 06:21:57 +00002778 Context->getPointerType(Context->VoidPtrTy),
2779 nullptr, /*BitWidth=*/nullptr,
2780 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002781 MemberExpr *ArrayLiteralME =
2782 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2783 SourceLocation(),
2784 ARRFD->getType(), VK_LValue,
2785 OK_Ordinary);
2786 QualType ConstIdT = Context->getObjCIdType().withConst();
2787 CStyleCastExpr * ArrayLiteralObjects =
2788 NoTypeInfoCStyleCastExpr(Context,
2789 Context->getPointerType(ConstIdT),
2790 CK_BitCast,
2791 ArrayLiteralME);
2792
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002793 // Synthesize a call to objc_msgSend().
2794 SmallVector<Expr*, 32> MsgExprs;
2795 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002796 QualType expType = Exp->getType();
2797
2798 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2799 ObjCInterfaceDecl *Class =
2800 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2801
2802 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002803 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002804 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2805 &ClsExprs[0],
2806 ClsExprs.size(),
2807 StartLoc, EndLoc);
2808 MsgExprs.push_back(Cls);
2809
2810 // Create a call to sel_registerName("arrayWithObjects:count:").
2811 // it will be the 2nd argument.
2812 SmallVector<Expr*, 4> SelExprs;
2813 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002814 SelExprs.push_back(
2815 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002816 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2817 &SelExprs[0], SelExprs.size(),
2818 StartLoc, EndLoc);
2819 MsgExprs.push_back(SelExp);
2820
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002821 // (const id [])objects
2822 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002823
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002824 // (NSUInteger)cnt
2825 Expr *cnt = IntegerLiteral::Create(*Context,
2826 llvm::APInt(UnsignedIntSize, NumElements),
2827 Context->UnsignedIntTy, SourceLocation());
2828 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002829
2830
2831 SmallVector<QualType, 4> ArgTypes;
2832 ArgTypes.push_back(Context->getObjCIdType());
2833 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002834 for (const auto *PI : ArrayMethod->params())
2835 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002836
2837 QualType returnType = Exp->getType();
2838 // Get the type, we will need to reference it in a couple spots.
2839 QualType msgSendType = MsgSendFlavor->getType();
2840
2841 // Create a reference to the objc_msgSend() declaration.
2842 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2843 VK_LValue, SourceLocation());
2844
2845 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2846 Context->getPointerType(Context->VoidTy),
2847 CK_BitCast, DRE);
2848
2849 // Now do the "normal" pointer to function cast.
2850 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002851 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002852 castType = Context->getPointerType(castType);
2853 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2854 cast);
2855
2856 // Don't forget the parens to enforce the proper binding.
2857 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2858
2859 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002860 CallExpr *CE = new (Context)
2861 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002862 ReplaceStmt(Exp, CE);
2863 return CE;
2864}
2865
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002866Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2867 // synthesize declaration of helper functions needed in this routine.
2868 if (!SelGetUidFunctionDecl)
2869 SynthSelGetUidFunctionDecl();
2870 // use objc_msgSend() for all.
2871 if (!MsgSendFunctionDecl)
2872 SynthMsgSendFunctionDecl();
2873 if (!GetClassFunctionDecl)
2874 SynthGetClassFunctionDecl();
2875
2876 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2877 SourceLocation StartLoc = Exp->getLocStart();
2878 SourceLocation EndLoc = Exp->getLocEnd();
2879
2880 // Build the expression: __NSContainer_literal(int, ...).arr
2881 QualType IntQT = Context->IntTy;
2882 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002883 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002884 std::string NSDictFName("__NSContainer_literal");
2885 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2886 DeclRefExpr *NSDictDRE =
2887 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2888 SourceLocation());
2889
2890 SmallVector<Expr*, 16> KeyExprs;
2891 SmallVector<Expr*, 16> ValueExprs;
2892
2893 unsigned NumElements = Exp->getNumElements();
2894 unsigned UnsignedIntSize =
2895 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2896 Expr *count = IntegerLiteral::Create(*Context,
2897 llvm::APInt(UnsignedIntSize, NumElements),
2898 Context->UnsignedIntTy, SourceLocation());
2899 KeyExprs.push_back(count);
2900 ValueExprs.push_back(count);
2901 for (unsigned i = 0; i < NumElements; i++) {
2902 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2903 KeyExprs.push_back(Element.Key);
2904 ValueExprs.push_back(Element.Value);
2905 }
2906
2907 // (const id [])objects
2908 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002909 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002910 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002911
2912 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002913 SourceLocation(),
2914 &Context->Idents.get("arr"),
Craig Topper8ae12032014-05-07 06:21:57 +00002915 Context->getPointerType(Context->VoidPtrTy),
2916 nullptr, /*BitWidth=*/nullptr,
2917 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 MemberExpr *DictLiteralValueME =
2919 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2920 SourceLocation(),
2921 ARRFD->getType(), VK_LValue,
2922 OK_Ordinary);
2923 QualType ConstIdT = Context->getObjCIdType().withConst();
2924 CStyleCastExpr * DictValueObjects =
2925 NoTypeInfoCStyleCastExpr(Context,
2926 Context->getPointerType(ConstIdT),
2927 CK_BitCast,
2928 DictLiteralValueME);
2929 // (const id <NSCopying> [])keys
2930 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002931 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002932 NSDictFType, VK_LValue, SourceLocation());
2933
2934 MemberExpr *DictLiteralKeyME =
2935 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2936 SourceLocation(),
2937 ARRFD->getType(), VK_LValue,
2938 OK_Ordinary);
2939
2940 CStyleCastExpr * DictKeyObjects =
2941 NoTypeInfoCStyleCastExpr(Context,
2942 Context->getPointerType(ConstIdT),
2943 CK_BitCast,
2944 DictLiteralKeyME);
2945
2946
2947
2948 // Synthesize a call to objc_msgSend().
2949 SmallVector<Expr*, 32> MsgExprs;
2950 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002951 QualType expType = Exp->getType();
2952
2953 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2954 ObjCInterfaceDecl *Class =
2955 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2956
2957 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002958 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002959 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2960 &ClsExprs[0],
2961 ClsExprs.size(),
2962 StartLoc, EndLoc);
2963 MsgExprs.push_back(Cls);
2964
2965 // Create a call to sel_registerName("arrayWithObjects:count:").
2966 // it will be the 2nd argument.
2967 SmallVector<Expr*, 4> SelExprs;
2968 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002969 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002970 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2971 &SelExprs[0], SelExprs.size(),
2972 StartLoc, EndLoc);
2973 MsgExprs.push_back(SelExp);
2974
2975 // (const id [])objects
2976 MsgExprs.push_back(DictValueObjects);
2977
2978 // (const id <NSCopying> [])keys
2979 MsgExprs.push_back(DictKeyObjects);
2980
2981 // (NSUInteger)cnt
2982 Expr *cnt = IntegerLiteral::Create(*Context,
2983 llvm::APInt(UnsignedIntSize, NumElements),
2984 Context->UnsignedIntTy, SourceLocation());
2985 MsgExprs.push_back(cnt);
2986
2987
2988 SmallVector<QualType, 8> ArgTypes;
2989 ArgTypes.push_back(Context->getObjCIdType());
2990 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002991 for (const auto *PI : DictMethod->params()) {
2992 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002993 if (const PointerType* PT = T->getAs<PointerType>()) {
2994 QualType PointeeTy = PT->getPointeeType();
2995 convertToUnqualifiedObjCType(PointeeTy);
2996 T = Context->getPointerType(PointeeTy);
2997 }
2998 ArgTypes.push_back(T);
2999 }
3000
3001 QualType returnType = Exp->getType();
3002 // Get the type, we will need to reference it in a couple spots.
3003 QualType msgSendType = MsgSendFlavor->getType();
3004
3005 // Create a reference to the objc_msgSend() declaration.
3006 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3007 VK_LValue, SourceLocation());
3008
3009 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3010 Context->getPointerType(Context->VoidTy),
3011 CK_BitCast, DRE);
3012
3013 // Now do the "normal" pointer to function cast.
3014 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003015 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003016 castType = Context->getPointerType(castType);
3017 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3018 cast);
3019
3020 // Don't forget the parens to enforce the proper binding.
3021 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3022
3023 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003024 CallExpr *CE = new (Context)
3025 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003026 ReplaceStmt(Exp, CE);
3027 return CE;
3028}
3029
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003030// struct __rw_objc_super {
3031// struct objc_object *object; struct objc_object *superClass;
3032// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003033QualType RewriteModernObjC::getSuperStructType() {
3034 if (!SuperStructDecl) {
3035 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3036 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003037 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003038 QualType FieldTypes[2];
3039
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003040 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003041 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003042 // struct objc_object *superClass;
3043 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003044
3045 // Create fields
3046 for (unsigned i = 0; i < 2; ++i) {
3047 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3048 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003049 SourceLocation(), nullptr,
3050 FieldTypes[i], nullptr,
3051 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003052 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003053 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003054 }
3055
3056 SuperStructDecl->completeDefinition();
3057 }
3058 return Context->getTagDeclType(SuperStructDecl);
3059}
3060
3061QualType RewriteModernObjC::getConstantStringStructType() {
3062 if (!ConstantStringDecl) {
3063 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3064 SourceLocation(), SourceLocation(),
3065 &Context->Idents.get("__NSConstantStringImpl"));
3066 QualType FieldTypes[4];
3067
3068 // struct objc_object *receiver;
3069 FieldTypes[0] = Context->getObjCIdType();
3070 // int flags;
3071 FieldTypes[1] = Context->IntTy;
3072 // char *str;
3073 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3074 // long length;
3075 FieldTypes[3] = Context->LongTy;
3076
3077 // Create fields
3078 for (unsigned i = 0; i < 4; ++i) {
3079 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3080 ConstantStringDecl,
3081 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003082 SourceLocation(), nullptr,
3083 FieldTypes[i], nullptr,
3084 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003085 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003086 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003087 }
3088
3089 ConstantStringDecl->completeDefinition();
3090 }
3091 return Context->getTagDeclType(ConstantStringDecl);
3092}
3093
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003094/// getFunctionSourceLocation - returns start location of a function
3095/// definition. Complication arises when function has declared as
3096/// extern "C" or extern "C" {...}
3097static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3098 FunctionDecl *FD) {
3099 if (FD->isExternC() && !FD->isMain()) {
3100 const DeclContext *DC = FD->getDeclContext();
3101 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3102 // if it is extern "C" {...}, return function decl's own location.
3103 if (!LSD->getRBraceLoc().isValid())
3104 return LSD->getExternLoc();
3105 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003106 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003107 R.RewriteBlockLiteralFunctionDecl(FD);
3108 return FD->getTypeSpecStartLoc();
3109}
3110
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003111void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3112
3113 SourceLocation Location = D->getLocation();
3114
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003115 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003116 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003117 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3118 LineString += utostr(PLoc.getLine());
3119 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003120 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003121 if (isa<ObjCMethodDecl>(D))
3122 LineString += "\"";
3123 else LineString += "\"\n";
3124
3125 Location = D->getLocStart();
3126 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3127 if (FD->isExternC() && !FD->isMain()) {
3128 const DeclContext *DC = FD->getDeclContext();
3129 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3130 // if it is extern "C" {...}, return function decl's own location.
3131 if (!LSD->getRBraceLoc().isValid())
3132 Location = LSD->getExternLoc();
3133 }
3134 }
3135 InsertText(Location, LineString);
3136 }
3137}
3138
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003139/// SynthMsgSendStretCallExpr - This routine translates message expression
3140/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3141/// nil check on receiver must be performed before calling objc_msgSend_stret.
3142/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3143/// msgSendType - function type of objc_msgSend_stret(...)
3144/// returnType - Result type of the method being synthesized.
3145/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3146/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3147/// starting with receiver.
3148/// Method - Method being rewritten.
3149Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003150 QualType returnType,
3151 SmallVectorImpl<QualType> &ArgTypes,
3152 SmallVectorImpl<Expr*> &MsgExprs,
3153 ObjCMethodDecl *Method) {
3154 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003155 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3156 Method ? Method->isVariadic()
3157 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003158 castType = Context->getPointerType(castType);
3159
3160 // build type for containing the objc_msgSend_stret object.
3161 static unsigned stretCount=0;
3162 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003163 std::string str =
3164 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003165 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003166 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003167 str += " {\n\t";
3168 str += name;
3169 str += "(id receiver, SEL sel";
3170 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003171 std::string ArgName = "arg"; ArgName += utostr(i);
3172 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3173 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003174 }
3175 // could be vararg.
3176 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003177 std::string ArgName = "arg"; ArgName += utostr(i);
3178 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3179 Context->getPrintingPolicy());
3180 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003181 }
3182
3183 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003184 str += "\t unsigned size = sizeof(";
3185 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3186
3187 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3188
3189 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3190 str += ")(void *)objc_msgSend)(receiver, sel";
3191 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3192 str += ", arg"; str += utostr(i);
3193 }
3194 // could be vararg.
3195 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3196 str += ", arg"; str += utostr(i);
3197 }
3198 str+= ");\n";
3199
3200 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003201 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3202 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003203
3204
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003205 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3206 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3207 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3208 str += ", arg"; str += utostr(i);
3209 }
3210 // could be vararg.
3211 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3212 str += ", arg"; str += utostr(i);
3213 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003214 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003215
3216
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003217 str += "\t}\n";
3218 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3219 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003220 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003221 SourceLocation FunLocStart;
3222 if (CurFunctionDef)
3223 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3224 else {
3225 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3226 FunLocStart = CurMethodDef->getLocStart();
3227 }
3228
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003229 InsertText(FunLocStart, str);
3230 ++stretCount;
3231
3232 // AST for __Stretn(receiver, args).s;
3233 IdentifierInfo *ID = &Context->Idents.get(name);
3234 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003235 SourceLocation(), ID, castType,
3236 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003237 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3238 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003239 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003240 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003241
3242 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003243 SourceLocation(),
3244 &Context->Idents.get("s"),
Craig Topper8ae12032014-05-07 06:21:57 +00003245 returnType, nullptr,
3246 /*BitWidth=*/nullptr,
3247 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003248 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3249 FieldD->getType(), VK_LValue,
3250 OK_Ordinary);
3251
3252 return ME;
3253}
3254
Fariborz Jahanian11671902012-02-07 17:11:38 +00003255Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3256 SourceLocation StartLoc,
3257 SourceLocation EndLoc) {
3258 if (!SelGetUidFunctionDecl)
3259 SynthSelGetUidFunctionDecl();
3260 if (!MsgSendFunctionDecl)
3261 SynthMsgSendFunctionDecl();
3262 if (!MsgSendSuperFunctionDecl)
3263 SynthMsgSendSuperFunctionDecl();
3264 if (!MsgSendStretFunctionDecl)
3265 SynthMsgSendStretFunctionDecl();
3266 if (!MsgSendSuperStretFunctionDecl)
3267 SynthMsgSendSuperStretFunctionDecl();
3268 if (!MsgSendFpretFunctionDecl)
3269 SynthMsgSendFpretFunctionDecl();
3270 if (!GetClassFunctionDecl)
3271 SynthGetClassFunctionDecl();
3272 if (!GetSuperClassFunctionDecl)
3273 SynthGetSuperClassFunctionDecl();
3274 if (!GetMetaClassFunctionDecl)
3275 SynthGetMetaClassFunctionDecl();
3276
3277 // default to objc_msgSend().
3278 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3279 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003280 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003281 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003282 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003283 if (resultType->isRecordType())
3284 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3285 else if (resultType->isRealFloatingType())
3286 MsgSendFlavor = MsgSendFpretFunctionDecl;
3287 }
3288
3289 // Synthesize a call to objc_msgSend().
3290 SmallVector<Expr*, 8> MsgExprs;
3291 switch (Exp->getReceiverKind()) {
3292 case ObjCMessageExpr::SuperClass: {
3293 MsgSendFlavor = MsgSendSuperFunctionDecl;
3294 if (MsgSendStretFlavor)
3295 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3296 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3297
3298 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3299
3300 SmallVector<Expr*, 4> InitExprs;
3301
3302 // set the receiver to self, the first argument to all methods.
3303 InitExprs.push_back(
3304 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3305 CK_BitCast,
3306 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003307 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003308 Context->getObjCIdType(),
3309 VK_RValue,
3310 SourceLocation()))
3311 ); // set the 'receiver'.
3312
3313 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3314 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003315 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003316 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003317 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3318 &ClsExprs[0],
3319 ClsExprs.size(),
3320 StartLoc,
3321 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003322 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003323 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003324 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3325 &ClsExprs[0], ClsExprs.size(),
3326 StartLoc, EndLoc);
3327
3328 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3329 // To turn off a warning, type-cast to 'id'
3330 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3331 NoTypeInfoCStyleCastExpr(Context,
3332 Context->getObjCIdType(),
3333 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003334 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003335 QualType superType = getSuperStructType();
3336 Expr *SuperRep;
3337
3338 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003339 SynthSuperConstructorFunctionDecl();
3340 // Simulate a constructor call...
3341 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003342 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003343 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003344 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003345 superType, VK_LValue,
3346 SourceLocation());
3347 // The code for super is a little tricky to prevent collision with
3348 // the structure definition in the header. The rewriter has it's own
3349 // internal definition (__rw_objc_super) that is uses. This is why
3350 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003351 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003352 //
3353 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3354 Context->getPointerType(SuperRep->getType()),
3355 VK_RValue, OK_Ordinary,
3356 SourceLocation());
3357 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3358 Context->getPointerType(superType),
3359 CK_BitCast, SuperRep);
3360 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003361 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003362 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003363 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003364 SourceLocation());
3365 TypeSourceInfo *superTInfo
3366 = Context->getTrivialTypeSourceInfo(superType);
3367 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3368 superType, VK_LValue,
3369 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003370 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003371 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3372 Context->getPointerType(SuperRep->getType()),
3373 VK_RValue, OK_Ordinary,
3374 SourceLocation());
3375 }
3376 MsgExprs.push_back(SuperRep);
3377 break;
3378 }
3379
3380 case ObjCMessageExpr::Class: {
3381 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003382 ObjCInterfaceDecl *Class
3383 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3384 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003385 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003386 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3387 &ClsExprs[0],
3388 ClsExprs.size(),
3389 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003390 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3391 Context->getObjCIdType(),
3392 CK_BitCast, Cls);
3393 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003394 break;
3395 }
3396
3397 case ObjCMessageExpr::SuperInstance:{
3398 MsgSendFlavor = MsgSendSuperFunctionDecl;
3399 if (MsgSendStretFlavor)
3400 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3401 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3402 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3403 SmallVector<Expr*, 4> InitExprs;
3404
3405 InitExprs.push_back(
3406 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3407 CK_BitCast,
3408 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003409 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003410 Context->getObjCIdType(),
3411 VK_RValue, SourceLocation()))
3412 ); // set the 'receiver'.
3413
3414 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3415 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003416 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003417 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003418 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3419 &ClsExprs[0],
3420 ClsExprs.size(),
3421 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003422 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003423 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003424 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3425 &ClsExprs[0], ClsExprs.size(),
3426 StartLoc, EndLoc);
3427
3428 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3429 // To turn off a warning, type-cast to 'id'
3430 InitExprs.push_back(
3431 // set 'super class', using class_getSuperclass().
3432 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3433 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003434 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003435 QualType superType = getSuperStructType();
3436 Expr *SuperRep;
3437
3438 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003439 SynthSuperConstructorFunctionDecl();
3440 // Simulate a constructor call...
3441 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003442 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003443 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003444 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003445 superType, VK_LValue, SourceLocation());
3446 // The code for super is a little tricky to prevent collision with
3447 // the structure definition in the header. The rewriter has it's own
3448 // internal definition (__rw_objc_super) that is uses. This is why
3449 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003450 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003451 //
3452 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3453 Context->getPointerType(SuperRep->getType()),
3454 VK_RValue, OK_Ordinary,
3455 SourceLocation());
3456 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3457 Context->getPointerType(superType),
3458 CK_BitCast, SuperRep);
3459 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003460 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003461 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003462 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003463 SourceLocation());
3464 TypeSourceInfo *superTInfo
3465 = Context->getTrivialTypeSourceInfo(superType);
3466 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3467 superType, VK_RValue, ILE,
3468 false);
3469 }
3470 MsgExprs.push_back(SuperRep);
3471 break;
3472 }
3473
3474 case ObjCMessageExpr::Instance: {
3475 // Remove all type-casts because it may contain objc-style types; e.g.
3476 // Foo<Proto> *.
3477 Expr *recExpr = Exp->getInstanceReceiver();
3478 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3479 recExpr = CE->getSubExpr();
3480 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3481 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3482 ? CK_BlockPointerToObjCPointerCast
3483 : CK_CPointerToObjCPointerCast;
3484
3485 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3486 CK, recExpr);
3487 MsgExprs.push_back(recExpr);
3488 break;
3489 }
3490 }
3491
3492 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3493 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003494 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003495 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3496 &SelExprs[0], SelExprs.size(),
3497 StartLoc,
3498 EndLoc);
3499 MsgExprs.push_back(SelExp);
3500
3501 // Now push any user supplied arguments.
3502 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3503 Expr *userExpr = Exp->getArg(i);
3504 // Make all implicit casts explicit...ICE comes in handy:-)
3505 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3506 // Reuse the ICE type, it is exactly what the doctor ordered.
3507 QualType type = ICE->getType();
3508 if (needToScanForQualifiers(type))
3509 type = Context->getObjCIdType();
3510 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3511 (void)convertBlockPointerToFunctionPointer(type);
3512 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3513 CastKind CK;
3514 if (SubExpr->getType()->isIntegralType(*Context) &&
3515 type->isBooleanType()) {
3516 CK = CK_IntegralToBoolean;
3517 } else if (type->isObjCObjectPointerType()) {
3518 if (SubExpr->getType()->isBlockPointerType()) {
3519 CK = CK_BlockPointerToObjCPointerCast;
3520 } else if (SubExpr->getType()->isPointerType()) {
3521 CK = CK_CPointerToObjCPointerCast;
3522 } else {
3523 CK = CK_BitCast;
3524 }
3525 } else {
3526 CK = CK_BitCast;
3527 }
3528
3529 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3530 }
3531 // Make id<P...> cast into an 'id' cast.
3532 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3533 if (CE->getType()->isObjCQualifiedIdType()) {
3534 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3535 userExpr = CE->getSubExpr();
3536 CastKind CK;
3537 if (userExpr->getType()->isIntegralType(*Context)) {
3538 CK = CK_IntegralToPointer;
3539 } else if (userExpr->getType()->isBlockPointerType()) {
3540 CK = CK_BlockPointerToObjCPointerCast;
3541 } else if (userExpr->getType()->isPointerType()) {
3542 CK = CK_CPointerToObjCPointerCast;
3543 } else {
3544 CK = CK_BitCast;
3545 }
3546 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3547 CK, userExpr);
3548 }
3549 }
3550 MsgExprs.push_back(userExpr);
3551 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3552 // out the argument in the original expression (since we aren't deleting
3553 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3554 //Exp->setArg(i, 0);
3555 }
3556 // Generate the funky cast.
3557 CastExpr *cast;
3558 SmallVector<QualType, 8> ArgTypes;
3559 QualType returnType;
3560
3561 // Push 'id' and 'SEL', the 2 implicit arguments.
3562 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3563 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3564 else
3565 ArgTypes.push_back(Context->getObjCIdType());
3566 ArgTypes.push_back(Context->getObjCSelType());
3567 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3568 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003569 for (const auto *PI : OMD->params()) {
3570 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003571 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003572 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003573 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3574 (void)convertBlockPointerToFunctionPointer(t);
3575 ArgTypes.push_back(t);
3576 }
3577 returnType = Exp->getType();
3578 convertToUnqualifiedObjCType(returnType);
3579 (void)convertBlockPointerToFunctionPointer(returnType);
3580 } else {
3581 returnType = Context->getObjCIdType();
3582 }
3583 // Get the type, we will need to reference it in a couple spots.
3584 QualType msgSendType = MsgSendFlavor->getType();
3585
3586 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003587 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003588 VK_LValue, SourceLocation());
3589
3590 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3591 // If we don't do this cast, we get the following bizarre warning/note:
3592 // xx.m:13: warning: function called through a non-compatible type
3593 // xx.m:13: note: if this code is reached, the program will abort
3594 cast = NoTypeInfoCStyleCastExpr(Context,
3595 Context->getPointerType(Context->VoidTy),
3596 CK_BitCast, DRE);
3597
3598 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003599 // If we don't have a method decl, force a variadic cast.
3600 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003601 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003602 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003603 castType = Context->getPointerType(castType);
3604 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3605 cast);
3606
3607 // Don't forget the parens to enforce the proper binding.
3608 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3609
3610 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003611 CallExpr *CE = new (Context)
3612 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003613 Stmt *ReplacingStmt = CE;
3614 if (MsgSendStretFlavor) {
3615 // We have the method which returns a struct/union. Must also generate
3616 // call to objc_msgSend_stret and hang both varieties on a conditional
3617 // expression which dictate which one to envoke depending on size of
3618 // method's return type.
3619
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003620 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3621 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003622 ArgTypes, MsgExprs,
3623 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003624 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003625 }
3626 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3627 return ReplacingStmt;
3628}
3629
3630Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3631 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3632 Exp->getLocEnd());
3633
3634 // Now do the actual rewrite.
3635 ReplaceStmt(Exp, ReplacingStmt);
3636
3637 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3638 return ReplacingStmt;
3639}
3640
3641// typedef struct objc_object Protocol;
3642QualType RewriteModernObjC::getProtocolType() {
3643 if (!ProtocolTypeDecl) {
3644 TypeSourceInfo *TInfo
3645 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3646 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3647 SourceLocation(), SourceLocation(),
3648 &Context->Idents.get("Protocol"),
3649 TInfo);
3650 }
3651 return Context->getTypeDeclType(ProtocolTypeDecl);
3652}
3653
3654/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3655/// a synthesized/forward data reference (to the protocol's metadata).
3656/// The forward references (and metadata) are generated in
3657/// RewriteModernObjC::HandleTranslationUnit().
3658Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003659 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3660 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003661 IdentifierInfo *ID = &Context->Idents.get(Name);
3662 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003663 SourceLocation(), ID, getProtocolType(),
3664 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003665 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3666 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003667 CastExpr *castExpr =
3668 NoTypeInfoCStyleCastExpr(
3669 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003670 ReplaceStmt(Exp, castExpr);
3671 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3672 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3673 return castExpr;
3674
3675}
3676
3677bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3678 const char *endBuf) {
3679 while (startBuf < endBuf) {
3680 if (*startBuf == '#') {
3681 // Skip whitespace.
3682 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3683 ;
3684 if (!strncmp(startBuf, "if", strlen("if")) ||
3685 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3686 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3687 !strncmp(startBuf, "define", strlen("define")) ||
3688 !strncmp(startBuf, "undef", strlen("undef")) ||
3689 !strncmp(startBuf, "else", strlen("else")) ||
3690 !strncmp(startBuf, "elif", strlen("elif")) ||
3691 !strncmp(startBuf, "endif", strlen("endif")) ||
3692 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3693 !strncmp(startBuf, "include", strlen("include")) ||
3694 !strncmp(startBuf, "import", strlen("import")) ||
3695 !strncmp(startBuf, "include_next", strlen("include_next")))
3696 return true;
3697 }
3698 startBuf++;
3699 }
3700 return false;
3701}
3702
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003703/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3704/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003705bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003706 TagDecl *Tag,
3707 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003708 if (!IDecl)
3709 return false;
3710 SourceLocation TagLocation;
3711 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3712 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003713 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003714 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003715 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003716 TagLocation = RD->getLocation();
3717 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003718 IDecl->getLocation(), TagLocation);
3719 }
3720 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3721 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3722 return false;
3723 IsNamedDefinition = true;
3724 TagLocation = ED->getLocation();
3725 return Context->getSourceManager().isBeforeInTranslationUnit(
3726 IDecl->getLocation(), TagLocation);
3727
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003728 }
3729 return false;
3730}
3731
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003732/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003733/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003734bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3735 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003736 if (isa<TypedefType>(Type)) {
3737 Result += "\t";
3738 return false;
3739 }
3740
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003741 if (Type->isArrayType()) {
3742 QualType ElemTy = Context->getBaseElementType(Type);
3743 return RewriteObjCFieldDeclType(ElemTy, Result);
3744 }
3745 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003746 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3747 if (RD->isCompleteDefinition()) {
3748 if (RD->isStruct())
3749 Result += "\n\tstruct ";
3750 else if (RD->isUnion())
3751 Result += "\n\tunion ";
3752 else
3753 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003754
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003755 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003756 if (GlobalDefinedTags.count(RD)) {
3757 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003758 Result += " ";
3759 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003760 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003761 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003762 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003763 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003764 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003765 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003766 }
3767 }
3768 else if (Type->isEnumeralType()) {
3769 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3770 if (ED->isCompleteDefinition()) {
3771 Result += "\n\tenum ";
3772 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003773 if (GlobalDefinedTags.count(ED)) {
3774 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003775 Result += " ";
3776 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003777 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003778
3779 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003780 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003781 Result += "\t"; Result += EC->getName(); Result += " = ";
3782 llvm::APSInt Val = EC->getInitVal();
3783 Result += Val.toString(10);
3784 Result += ",\n";
3785 }
3786 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003787 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003788 }
3789 }
3790
3791 Result += "\t";
3792 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003793 return false;
3794}
3795
3796
3797/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3798/// It handles elaborated types, as well as enum types in the process.
3799void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3800 std::string &Result) {
3801 QualType Type = fieldDecl->getType();
3802 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003803
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003804 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3805 if (!EleboratedType)
3806 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003807 Result += Name;
3808 if (fieldDecl->isBitField()) {
3809 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3810 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003811 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003812 const ArrayType *AT = Context->getAsArrayType(Type);
3813 do {
3814 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003815 Result += "[";
3816 llvm::APInt Dim = CAT->getSize();
3817 Result += utostr(Dim.getZExtValue());
3818 Result += "]";
3819 }
Eli Friedman07bab732012-12-13 01:43:21 +00003820 AT = Context->getAsArrayType(AT->getElementType());
3821 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003822 }
3823
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003824 Result += ";\n";
3825}
3826
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003827/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3828/// named aggregate types into the input buffer.
3829void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3830 std::string &Result) {
3831 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003832 if (isa<TypedefType>(Type))
3833 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003834 if (Type->isArrayType())
3835 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003836 ObjCContainerDecl *IDecl =
3837 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003838
3839 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003840 if (Type->isRecordType()) {
3841 TD = Type->getAs<RecordType>()->getDecl();
3842 }
3843 else if (Type->isEnumeralType()) {
3844 TD = Type->getAs<EnumType>()->getDecl();
3845 }
3846
3847 if (TD) {
3848 if (GlobalDefinedTags.count(TD))
3849 return;
3850
3851 bool IsNamedDefinition = false;
3852 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3853 RewriteObjCFieldDeclType(Type, Result);
3854 Result += ";";
3855 }
3856 if (IsNamedDefinition)
3857 GlobalDefinedTags.insert(TD);
3858 }
3859
3860}
3861
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003862unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3863 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3864 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3865 return IvarGroupNumber[IV];
3866 }
3867 unsigned GroupNo = 0;
3868 SmallVector<const ObjCIvarDecl *, 8> IVars;
3869 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3870 IVD; IVD = IVD->getNextIvar())
3871 IVars.push_back(IVD);
3872
3873 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3874 if (IVars[i]->isBitField()) {
3875 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3876 while (i < e && IVars[i]->isBitField())
3877 IvarGroupNumber[IVars[i++]] = GroupNo;
3878 if (i < e)
3879 --i;
3880 }
3881
3882 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3883 return IvarGroupNumber[IV];
3884}
3885
3886QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3887 ObjCIvarDecl *IV,
3888 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3889 std::string StructTagName;
3890 ObjCIvarBitfieldGroupType(IV, StructTagName);
3891 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3892 Context->getTranslationUnitDecl(),
3893 SourceLocation(), SourceLocation(),
3894 &Context->Idents.get(StructTagName));
3895 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3896 ObjCIvarDecl *Ivar = IVars[i];
3897 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3898 &Context->Idents.get(Ivar->getName()),
3899 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003900 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3901 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003902 }
3903 RD->completeDefinition();
3904 return Context->getTagDeclType(RD);
3905}
3906
3907QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3908 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3909 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3910 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3911 if (GroupRecordType.count(tuple))
3912 return GroupRecordType[tuple];
3913
3914 SmallVector<ObjCIvarDecl *, 8> IVars;
3915 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3916 IVD; IVD = IVD->getNextIvar()) {
3917 if (IVD->isBitField())
3918 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3919 else {
3920 if (!IVars.empty()) {
3921 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3922 // Generate the struct type for this group of bitfield ivars.
3923 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3924 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3925 IVars.clear();
3926 }
3927 }
3928 }
3929 if (!IVars.empty()) {
3930 // Do the last one.
3931 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3932 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3933 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3934 }
3935 QualType RetQT = GroupRecordType[tuple];
3936 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3937
3938 return RetQT;
3939}
3940
3941/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3942/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3943void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3944 std::string &Result) {
3945 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3946 Result += CDecl->getName();
3947 Result += "__GRBF_";
3948 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3949 Result += utostr(GroupNo);
3950 return;
3951}
3952
3953/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3954/// Name of the struct would be: classname__T_n where n is the group number for
3955/// this ivar.
3956void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3957 std::string &Result) {
3958 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3959 Result += CDecl->getName();
3960 Result += "__T_";
3961 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3962 Result += utostr(GroupNo);
3963 return;
3964}
3965
3966/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3967/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3968/// this ivar.
3969void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3970 std::string &Result) {
3971 Result += "OBJC_IVAR_$_";
3972 ObjCIvarBitfieldGroupDecl(IV, Result);
3973}
3974
3975#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3976 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3977 ++IX; \
3978 if (IX < ENDIX) \
3979 --IX; \
3980}
3981
Fariborz Jahanian11671902012-02-07 17:11:38 +00003982/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3983/// an objective-c class with ivars.
3984void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3985 std::string &Result) {
3986 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3987 assert(CDecl->getName() != "" &&
3988 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003989 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003990 SmallVector<ObjCIvarDecl *, 8> IVars;
3991 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003992 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003993 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003994
Fariborz Jahanian11671902012-02-07 17:11:38 +00003995 SourceLocation LocStart = CDecl->getLocStart();
3996 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003997
Fariborz Jahanian11671902012-02-07 17:11:38 +00003998 const char *startBuf = SM->getCharacterData(LocStart);
3999 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004000
Fariborz Jahanian11671902012-02-07 17:11:38 +00004001 // If no ivars and no root or if its root, directly or indirectly,
4002 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004003 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004004 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4005 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4006 ReplaceText(LocStart, endBuf-startBuf, Result);
4007 return;
4008 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004009
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004010 // Insert named struct/union definitions inside class to
4011 // outer scope. This follows semantics of locally defined
4012 // struct/unions in objective-c classes.
4013 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4014 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004015
4016 // Insert named structs which are syntheized to group ivar bitfields
4017 // to outer scope as well.
4018 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4019 if (IVars[i]->isBitField()) {
4020 ObjCIvarDecl *IV = IVars[i];
4021 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4022 RewriteObjCFieldDeclType(QT, Result);
4023 Result += ";";
4024 // skip over ivar bitfields in this group.
4025 SKIP_BITFIELDS(i , e, IVars);
4026 }
4027
Fariborz Jahanian11671902012-02-07 17:11:38 +00004028 Result += "\nstruct ";
4029 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004030 Result += "_IMPL {\n";
4031
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004032 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004033 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4034 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4035 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004036 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004037
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004038 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4039 if (IVars[i]->isBitField()) {
4040 ObjCIvarDecl *IV = IVars[i];
4041 Result += "\tstruct ";
4042 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4043 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4044 // skip over ivar bitfields in this group.
4045 SKIP_BITFIELDS(i , e, IVars);
4046 }
4047 else
4048 RewriteObjCFieldDecl(IVars[i], Result);
4049 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004050
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004051 Result += "};\n";
4052 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4053 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004054 // Mark this struct as having been generated.
4055 if (!ObjCSynthesizedStructs.insert(CDecl))
4056 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004057}
4058
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004059/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4060/// have been referenced in an ivar access expression.
4061void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4062 std::string &Result) {
4063 // write out ivar offset symbols which have been referenced in an ivar
4064 // access expression.
4065 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4066 if (Ivars.empty())
4067 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004068
4069 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004070 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4071 e = Ivars.end(); i != e; i++) {
4072 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004073 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4074 unsigned GroupNo = 0;
4075 if (IvarDecl->isBitField()) {
4076 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4077 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4078 continue;
4079 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004080 Result += "\n";
4081 if (LangOpts.MicrosoftExt)
4082 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004083 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004084 if (LangOpts.MicrosoftExt &&
4085 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004086 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4087 Result += "__declspec(dllimport) ";
4088
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004089 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004090 if (IvarDecl->isBitField()) {
4091 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4092 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4093 }
4094 else
4095 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004096 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004097 }
4098}
4099
Fariborz Jahanian11671902012-02-07 17:11:38 +00004100//===----------------------------------------------------------------------===//
4101// Meta Data Emission
4102//===----------------------------------------------------------------------===//
4103
4104
4105/// RewriteImplementations - This routine rewrites all method implementations
4106/// and emits meta-data.
4107
4108void RewriteModernObjC::RewriteImplementations() {
4109 int ClsDefCount = ClassImplementation.size();
4110 int CatDefCount = CategoryImplementation.size();
4111
4112 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004113 for (int i = 0; i < ClsDefCount; i++) {
4114 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4115 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4116 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004117 assert(false &&
4118 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004119 RewriteImplementationDecl(OIMP);
4120 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004121
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004122 for (int i = 0; i < CatDefCount; i++) {
4123 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4124 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4125 if (CDecl->isImplicitInterfaceDecl())
4126 assert(false &&
4127 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004128 RewriteImplementationDecl(CIMP);
4129 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004130}
4131
4132void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4133 const std::string &Name,
4134 ValueDecl *VD, bool def) {
4135 assert(BlockByRefDeclNo.count(VD) &&
4136 "RewriteByRefString: ByRef decl missing");
4137 if (def)
4138 ResultStr += "struct ";
4139 ResultStr += "__Block_byref_" + Name +
4140 "_" + utostr(BlockByRefDeclNo[VD]) ;
4141}
4142
4143static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4144 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4145 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4146 return false;
4147}
4148
4149std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4150 StringRef funcName,
4151 std::string Tag) {
4152 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004153 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004154 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004155 SourceLocation BlockLoc = CE->getExprLoc();
4156 std::string S;
4157 ConvertSourceLocationToLineDirective(BlockLoc, S);
4158
4159 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4160 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004161
4162 BlockDecl *BD = CE->getBlockDecl();
4163
4164 if (isa<FunctionNoProtoType>(AFT)) {
4165 // No user-supplied arguments. Still need to pass in a pointer to the
4166 // block (to reference imported block decl refs).
4167 S += "(" + StructRef + " *__cself)";
4168 } else if (BD->param_empty()) {
4169 S += "(" + StructRef + " *__cself)";
4170 } else {
4171 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4172 assert(FT && "SynthesizeBlockFunc: No function proto");
4173 S += '(';
4174 // first add the implicit argument.
4175 S += StructRef + " *__cself, ";
4176 std::string ParamStr;
4177 for (BlockDecl::param_iterator AI = BD->param_begin(),
4178 E = BD->param_end(); AI != E; ++AI) {
4179 if (AI != BD->param_begin()) S += ", ";
4180 ParamStr = (*AI)->getNameAsString();
4181 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004182 (void)convertBlockPointerToFunctionPointer(QT);
4183 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004184 S += ParamStr;
4185 }
4186 if (FT->isVariadic()) {
4187 if (!BD->param_empty()) S += ", ";
4188 S += "...";
4189 }
4190 S += ')';
4191 }
4192 S += " {\n";
4193
4194 // Create local declarations to avoid rewriting all closure decl ref exprs.
4195 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004196 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004197 E = BlockByRefDecls.end(); I != E; ++I) {
4198 S += " ";
4199 std::string Name = (*I)->getNameAsString();
4200 std::string TypeString;
4201 RewriteByRefString(TypeString, Name, (*I));
4202 TypeString += " *";
4203 Name = TypeString + Name;
4204 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4205 }
4206 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004207 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004208 E = BlockByCopyDecls.end(); I != E; ++I) {
4209 S += " ";
4210 // Handle nested closure invocation. For example:
4211 //
4212 // void (^myImportedClosure)(void);
4213 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4214 //
4215 // void (^anotherClosure)(void);
4216 // anotherClosure = ^(void) {
4217 // myImportedClosure(); // import and invoke the closure
4218 // };
4219 //
4220 if (isTopLevelBlockPointerType((*I)->getType())) {
4221 RewriteBlockPointerTypeVariable(S, (*I));
4222 S += " = (";
4223 RewriteBlockPointerType(S, (*I)->getType());
4224 S += ")";
4225 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4226 }
4227 else {
4228 std::string Name = (*I)->getNameAsString();
4229 QualType QT = (*I)->getType();
4230 if (HasLocalVariableExternalStorage(*I))
4231 QT = Context->getPointerType(QT);
4232 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4233 S += Name + " = __cself->" +
4234 (*I)->getNameAsString() + "; // bound by copy\n";
4235 }
4236 }
4237 std::string RewrittenStr = RewrittenBlockExprs[CE];
4238 const char *cstr = RewrittenStr.c_str();
4239 while (*cstr++ != '{') ;
4240 S += cstr;
4241 S += "\n";
4242 return S;
4243}
4244
4245std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4246 StringRef funcName,
4247 std::string Tag) {
4248 std::string StructRef = "struct " + Tag;
4249 std::string S = "static void __";
4250
4251 S += funcName;
4252 S += "_block_copy_" + utostr(i);
4253 S += "(" + StructRef;
4254 S += "*dst, " + StructRef;
4255 S += "*src) {";
4256 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4257 E = ImportedBlockDecls.end(); I != E; ++I) {
4258 ValueDecl *VD = (*I);
4259 S += "_Block_object_assign((void*)&dst->";
4260 S += (*I)->getNameAsString();
4261 S += ", (void*)src->";
4262 S += (*I)->getNameAsString();
4263 if (BlockByRefDeclsPtrSet.count((*I)))
4264 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4265 else if (VD->getType()->isBlockPointerType())
4266 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4267 else
4268 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4269 }
4270 S += "}\n";
4271
4272 S += "\nstatic void __";
4273 S += funcName;
4274 S += "_block_dispose_" + utostr(i);
4275 S += "(" + StructRef;
4276 S += "*src) {";
4277 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4278 E = ImportedBlockDecls.end(); I != E; ++I) {
4279 ValueDecl *VD = (*I);
4280 S += "_Block_object_dispose((void*)src->";
4281 S += (*I)->getNameAsString();
4282 if (BlockByRefDeclsPtrSet.count((*I)))
4283 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4284 else if (VD->getType()->isBlockPointerType())
4285 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4286 else
4287 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4288 }
4289 S += "}\n";
4290 return S;
4291}
4292
4293std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4294 std::string Desc) {
4295 std::string S = "\nstruct " + Tag;
4296 std::string Constructor = " " + Tag;
4297
4298 S += " {\n struct __block_impl impl;\n";
4299 S += " struct " + Desc;
4300 S += "* Desc;\n";
4301
4302 Constructor += "(void *fp, "; // Invoke function pointer.
4303 Constructor += "struct " + Desc; // Descriptor pointer.
4304 Constructor += " *desc";
4305
4306 if (BlockDeclRefs.size()) {
4307 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004308 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004309 E = BlockByCopyDecls.end(); I != E; ++I) {
4310 S += " ";
4311 std::string FieldName = (*I)->getNameAsString();
4312 std::string ArgName = "_" + FieldName;
4313 // Handle nested closure invocation. For example:
4314 //
4315 // void (^myImportedBlock)(void);
4316 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4317 //
4318 // void (^anotherBlock)(void);
4319 // anotherBlock = ^(void) {
4320 // myImportedBlock(); // import and invoke the closure
4321 // };
4322 //
4323 if (isTopLevelBlockPointerType((*I)->getType())) {
4324 S += "struct __block_impl *";
4325 Constructor += ", void *" + ArgName;
4326 } else {
4327 QualType QT = (*I)->getType();
4328 if (HasLocalVariableExternalStorage(*I))
4329 QT = Context->getPointerType(QT);
4330 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4331 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4332 Constructor += ", " + ArgName;
4333 }
4334 S += FieldName + ";\n";
4335 }
4336 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004337 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004338 E = BlockByRefDecls.end(); I != E; ++I) {
4339 S += " ";
4340 std::string FieldName = (*I)->getNameAsString();
4341 std::string ArgName = "_" + FieldName;
4342 {
4343 std::string TypeString;
4344 RewriteByRefString(TypeString, FieldName, (*I));
4345 TypeString += " *";
4346 FieldName = TypeString + FieldName;
4347 ArgName = TypeString + ArgName;
4348 Constructor += ", " + ArgName;
4349 }
4350 S += FieldName + "; // by ref\n";
4351 }
4352 // Finish writing the constructor.
4353 Constructor += ", int flags=0)";
4354 // Initialize all "by copy" arguments.
4355 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004356 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004357 E = BlockByCopyDecls.end(); I != E; ++I) {
4358 std::string Name = (*I)->getNameAsString();
4359 if (firsTime) {
4360 Constructor += " : ";
4361 firsTime = false;
4362 }
4363 else
4364 Constructor += ", ";
4365 if (isTopLevelBlockPointerType((*I)->getType()))
4366 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4367 else
4368 Constructor += Name + "(_" + Name + ")";
4369 }
4370 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004371 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004372 E = BlockByRefDecls.end(); I != E; ++I) {
4373 std::string Name = (*I)->getNameAsString();
4374 if (firsTime) {
4375 Constructor += " : ";
4376 firsTime = false;
4377 }
4378 else
4379 Constructor += ", ";
4380 Constructor += Name + "(_" + Name + "->__forwarding)";
4381 }
4382
4383 Constructor += " {\n";
4384 if (GlobalVarDecl)
4385 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4386 else
4387 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4388 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4389
4390 Constructor += " Desc = desc;\n";
4391 } else {
4392 // Finish writing the constructor.
4393 Constructor += ", int flags=0) {\n";
4394 if (GlobalVarDecl)
4395 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4396 else
4397 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4398 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4399 Constructor += " Desc = desc;\n";
4400 }
4401 Constructor += " ";
4402 Constructor += "}\n";
4403 S += Constructor;
4404 S += "};\n";
4405 return S;
4406}
4407
4408std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4409 std::string ImplTag, int i,
4410 StringRef FunName,
4411 unsigned hasCopy) {
4412 std::string S = "\nstatic struct " + DescTag;
4413
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004414 S += " {\n size_t reserved;\n";
4415 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004416 if (hasCopy) {
4417 S += " void (*copy)(struct ";
4418 S += ImplTag; S += "*, struct ";
4419 S += ImplTag; S += "*);\n";
4420
4421 S += " void (*dispose)(struct ";
4422 S += ImplTag; S += "*);\n";
4423 }
4424 S += "} ";
4425
4426 S += DescTag + "_DATA = { 0, sizeof(struct ";
4427 S += ImplTag + ")";
4428 if (hasCopy) {
4429 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4430 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4431 }
4432 S += "};\n";
4433 return S;
4434}
4435
4436void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4437 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004438 bool RewriteSC = (GlobalVarDecl &&
4439 !Blocks.empty() &&
4440 GlobalVarDecl->getStorageClass() == SC_Static &&
4441 GlobalVarDecl->getType().getCVRQualifiers());
4442 if (RewriteSC) {
4443 std::string SC(" void __");
4444 SC += GlobalVarDecl->getNameAsString();
4445 SC += "() {}";
4446 InsertText(FunLocStart, SC);
4447 }
4448
4449 // Insert closures that were part of the function.
4450 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4451 CollectBlockDeclRefInfo(Blocks[i]);
4452 // Need to copy-in the inner copied-in variables not actually used in this
4453 // block.
4454 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004455 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004456 ValueDecl *VD = Exp->getDecl();
4457 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004458 if (!VD->hasAttr<BlocksAttr>()) {
4459 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4460 BlockByCopyDeclsPtrSet.insert(VD);
4461 BlockByCopyDecls.push_back(VD);
4462 }
4463 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004464 }
John McCall113bee02012-03-10 09:33:50 +00004465
4466 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004467 BlockByRefDeclsPtrSet.insert(VD);
4468 BlockByRefDecls.push_back(VD);
4469 }
John McCall113bee02012-03-10 09:33:50 +00004470
Fariborz Jahanian11671902012-02-07 17:11:38 +00004471 // imported objects in the inner blocks not used in the outer
4472 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004473 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004474 VD->getType()->isBlockPointerType())
4475 ImportedBlockDecls.insert(VD);
4476 }
4477
4478 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4479 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4480
4481 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4482
4483 InsertText(FunLocStart, CI);
4484
4485 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4486
4487 InsertText(FunLocStart, CF);
4488
4489 if (ImportedBlockDecls.size()) {
4490 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4491 InsertText(FunLocStart, HF);
4492 }
4493 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4494 ImportedBlockDecls.size() > 0);
4495 InsertText(FunLocStart, BD);
4496
4497 BlockDeclRefs.clear();
4498 BlockByRefDecls.clear();
4499 BlockByRefDeclsPtrSet.clear();
4500 BlockByCopyDecls.clear();
4501 BlockByCopyDeclsPtrSet.clear();
4502 ImportedBlockDecls.clear();
4503 }
4504 if (RewriteSC) {
4505 // Must insert any 'const/volatile/static here. Since it has been
4506 // removed as result of rewriting of block literals.
4507 std::string SC;
4508 if (GlobalVarDecl->getStorageClass() == SC_Static)
4509 SC = "static ";
4510 if (GlobalVarDecl->getType().isConstQualified())
4511 SC += "const ";
4512 if (GlobalVarDecl->getType().isVolatileQualified())
4513 SC += "volatile ";
4514 if (GlobalVarDecl->getType().isRestrictQualified())
4515 SC += "restrict ";
4516 InsertText(FunLocStart, SC);
4517 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004518 if (GlobalConstructionExp) {
4519 // extra fancy dance for global literal expression.
4520
4521 // Always the latest block expression on the block stack.
4522 std::string Tag = "__";
4523 Tag += FunName;
4524 Tag += "_block_impl_";
4525 Tag += utostr(Blocks.size()-1);
4526 std::string globalBuf = "static ";
4527 globalBuf += Tag; globalBuf += " ";
4528 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004529
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004530 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004531 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4532 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004533 globalBuf += constructorExprBuf.str();
4534 globalBuf += ";\n";
4535 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004536 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004537 }
4538
Fariborz Jahanian11671902012-02-07 17:11:38 +00004539 Blocks.clear();
4540 InnerDeclRefsCount.clear();
4541 InnerDeclRefs.clear();
4542 RewrittenBlockExprs.clear();
4543}
4544
4545void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004546 SourceLocation FunLocStart =
4547 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4548 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004549 StringRef FuncName = FD->getName();
4550
4551 SynthesizeBlockLiterals(FunLocStart, FuncName);
4552}
4553
4554static void BuildUniqueMethodName(std::string &Name,
4555 ObjCMethodDecl *MD) {
4556 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4557 Name = IFace->getName();
4558 Name += "__" + MD->getSelector().getAsString();
4559 // Convert colons to underscores.
4560 std::string::size_type loc = 0;
4561 while ((loc = Name.find(":", loc)) != std::string::npos)
4562 Name.replace(loc, 1, "_");
4563}
4564
4565void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4566 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4567 //SourceLocation FunLocStart = MD->getLocStart();
4568 SourceLocation FunLocStart = MD->getLocStart();
4569 std::string FuncName;
4570 BuildUniqueMethodName(FuncName, MD);
4571 SynthesizeBlockLiterals(FunLocStart, FuncName);
4572}
4573
4574void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4575 for (Stmt::child_range CI = S->children(); CI; ++CI)
4576 if (*CI) {
4577 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4578 GetBlockDeclRefExprs(CBE->getBody());
4579 else
4580 GetBlockDeclRefExprs(*CI);
4581 }
4582 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4584 if (DRE->refersToEnclosingLocal()) {
4585 // FIXME: Handle enums.
4586 if (!isa<FunctionDecl>(DRE->getDecl()))
4587 BlockDeclRefs.push_back(DRE);
4588 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4589 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004590 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004591 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004592
4593 return;
4594}
4595
Craig Topper5603df42013-07-05 19:34:19 +00004596void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4597 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004598 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4599 for (Stmt::child_range CI = S->children(); CI; ++CI)
4600 if (*CI) {
4601 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4602 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4603 GetInnerBlockDeclRefExprs(CBE->getBody(),
4604 InnerBlockDeclRefs,
4605 InnerContexts);
4606 }
4607 else
4608 GetInnerBlockDeclRefExprs(*CI,
4609 InnerBlockDeclRefs,
4610 InnerContexts);
4611
4612 }
4613 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4615 if (DRE->refersToEnclosingLocal()) {
4616 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4617 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4618 InnerBlockDeclRefs.push_back(DRE);
4619 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4620 if (Var->isFunctionOrMethodVarDecl())
4621 ImportedLocalExternalDecls.insert(Var);
4622 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004623 }
4624
4625 return;
4626}
4627
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004628/// convertObjCTypeToCStyleType - This routine converts such objc types
4629/// as qualified objects, and blocks to their closest c/c++ types that
4630/// it can. It returns true if input type was modified.
4631bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4632 QualType oldT = T;
4633 convertBlockPointerToFunctionPointer(T);
4634 if (T->isFunctionPointerType()) {
4635 QualType PointeeTy;
4636 if (const PointerType* PT = T->getAs<PointerType>()) {
4637 PointeeTy = PT->getPointeeType();
4638 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4639 T = convertFunctionTypeOfBlocks(FT);
4640 T = Context->getPointerType(T);
4641 }
4642 }
4643 }
4644
4645 convertToUnqualifiedObjCType(T);
4646 return T != oldT;
4647}
4648
Fariborz Jahanian11671902012-02-07 17:11:38 +00004649/// convertFunctionTypeOfBlocks - This routine converts a function type
4650/// whose result type may be a block pointer or whose argument type(s)
4651/// might be block pointers to an equivalent function type replacing
4652/// all block pointers to function pointers.
4653QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4654 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4655 // FTP will be null for closures that don't take arguments.
4656 // Generate a funky cast.
4657 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004658 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004659 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004660
4661 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004662 for (auto &I : FTP->param_types()) {
4663 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004664 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004665 if (convertObjCTypeToCStyleType(t))
4666 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004667 ArgTypes.push_back(t);
4668 }
4669 }
4670 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004671 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004672 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004673 else FuncType = QualType(FT, 0);
4674 return FuncType;
4675}
4676
4677Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4678 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004679 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004680
4681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4682 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004683 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4684 CPT = MExpr->getType()->getAs<BlockPointerType>();
4685 }
4686 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4687 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4688 }
4689 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4690 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4691 else if (const ConditionalOperator *CEXPR =
4692 dyn_cast<ConditionalOperator>(BlockExp)) {
4693 Expr *LHSExp = CEXPR->getLHS();
4694 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4695 Expr *RHSExp = CEXPR->getRHS();
4696 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4697 Expr *CONDExp = CEXPR->getCond();
4698 ConditionalOperator *CondExpr =
4699 new (Context) ConditionalOperator(CONDExp,
4700 SourceLocation(), cast<Expr>(LHSStmt),
4701 SourceLocation(), cast<Expr>(RHSStmt),
4702 Exp->getType(), VK_RValue, OK_Ordinary);
4703 return CondExpr;
4704 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4705 CPT = IRE->getType()->getAs<BlockPointerType>();
4706 } else if (const PseudoObjectExpr *POE
4707 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4708 CPT = POE->getType()->castAs<BlockPointerType>();
4709 } else {
4710 assert(1 && "RewriteBlockClass: Bad type");
4711 }
4712 assert(CPT && "RewriteBlockClass: Bad type");
4713 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4714 assert(FT && "RewriteBlockClass: Bad type");
4715 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4716 // FTP will be null for closures that don't take arguments.
4717
4718 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4719 SourceLocation(), SourceLocation(),
4720 &Context->Idents.get("__block_impl"));
4721 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4722
4723 // Generate a funky cast.
4724 SmallVector<QualType, 8> ArgTypes;
4725
4726 // Push the block argument type.
4727 ArgTypes.push_back(PtrBlock);
4728 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004729 for (auto &I : FTP->param_types()) {
4730 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004731 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4732 if (!convertBlockPointerToFunctionPointer(t))
4733 convertToUnqualifiedObjCType(t);
4734 ArgTypes.push_back(t);
4735 }
4736 }
4737 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004738 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004739
4740 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4741
4742 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4743 CK_BitCast,
4744 const_cast<Expr*>(BlockExp));
4745 // Don't forget the parens to enforce the proper binding.
4746 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4747 BlkCast);
4748 //PE->dump();
4749
Craig Topper8ae12032014-05-07 06:21:57 +00004750 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004751 SourceLocation(),
4752 &Context->Idents.get("FuncPtr"),
Craig Topper8ae12032014-05-07 06:21:57 +00004753 Context->VoidPtrTy, nullptr,
4754 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004755 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004756 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4757 FD->getType(), VK_LValue,
4758 OK_Ordinary);
4759
4760
4761 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4762 CK_BitCast, ME);
4763 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4764
4765 SmallVector<Expr*, 8> BlkExprs;
4766 // Add the implicit argument.
4767 BlkExprs.push_back(BlkCast);
4768 // Add the user arguments.
4769 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4770 E = Exp->arg_end(); I != E; ++I) {
4771 BlkExprs.push_back(*I);
4772 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004773 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004774 Exp->getType(), VK_RValue,
4775 SourceLocation());
4776 return CE;
4777}
4778
4779// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004780// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004781// For example:
4782//
4783// int main() {
4784// __block Foo *f;
4785// __block int i;
4786//
4787// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004788// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004789// i = 77;
4790// };
4791//}
John McCall113bee02012-03-10 09:33:50 +00004792Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004793 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4794 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004795 ValueDecl *VD = DeclRefExp->getDecl();
4796 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Craig Topper8ae12032014-05-07 06:21:57 +00004797
4798 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004799 SourceLocation(),
4800 &Context->Idents.get("__forwarding"),
Craig Topper8ae12032014-05-07 06:21:57 +00004801 Context->VoidPtrTy, nullptr,
4802 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004803 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004804 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4805 FD, SourceLocation(),
4806 FD->getType(), VK_LValue,
4807 OK_Ordinary);
4808
4809 StringRef Name = VD->getName();
Craig Topper8ae12032014-05-07 06:21:57 +00004810 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004811 &Context->Idents.get(Name),
Craig Topper8ae12032014-05-07 06:21:57 +00004812 Context->VoidPtrTy, nullptr,
4813 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004814 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004815 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4816 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4817
4818
4819
4820 // Need parens to enforce precedence.
4821 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4822 DeclRefExp->getExprLoc(),
4823 ME);
4824 ReplaceStmt(DeclRefExp, PE);
4825 return PE;
4826}
4827
4828// Rewrites the imported local variable V with external storage
4829// (static, extern, etc.) as *V
4830//
4831Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4832 ValueDecl *VD = DRE->getDecl();
4833 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4834 if (!ImportedLocalExternalDecls.count(Var))
4835 return DRE;
4836 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4837 VK_LValue, OK_Ordinary,
4838 DRE->getLocation());
4839 // Need parens to enforce precedence.
4840 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4841 Exp);
4842 ReplaceStmt(DRE, PE);
4843 return PE;
4844}
4845
4846void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4847 SourceLocation LocStart = CE->getLParenLoc();
4848 SourceLocation LocEnd = CE->getRParenLoc();
4849
4850 // Need to avoid trying to rewrite synthesized casts.
4851 if (LocStart.isInvalid())
4852 return;
4853 // Need to avoid trying to rewrite casts contained in macros.
4854 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4855 return;
4856
4857 const char *startBuf = SM->getCharacterData(LocStart);
4858 const char *endBuf = SM->getCharacterData(LocEnd);
4859 QualType QT = CE->getType();
4860 const Type* TypePtr = QT->getAs<Type>();
4861 if (isa<TypeOfExprType>(TypePtr)) {
4862 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4863 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4864 std::string TypeAsString = "(";
4865 RewriteBlockPointerType(TypeAsString, QT);
4866 TypeAsString += ")";
4867 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4868 return;
4869 }
4870 // advance the location to startArgList.
4871 const char *argPtr = startBuf;
4872
4873 while (*argPtr++ && (argPtr < endBuf)) {
4874 switch (*argPtr) {
4875 case '^':
4876 // Replace the '^' with '*'.
4877 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4878 ReplaceText(LocStart, 1, "*");
4879 break;
4880 }
4881 }
4882 return;
4883}
4884
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004885void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4886 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004887 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4888 CastKind != CK_AnyPointerToBlockPointerCast)
4889 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004890
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004891 QualType QT = IC->getType();
4892 (void)convertBlockPointerToFunctionPointer(QT);
4893 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4894 std::string Str = "(";
4895 Str += TypeString;
4896 Str += ")";
4897 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4898
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004899 return;
4900}
4901
Fariborz Jahanian11671902012-02-07 17:11:38 +00004902void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4903 SourceLocation DeclLoc = FD->getLocation();
4904 unsigned parenCount = 0;
4905
4906 // We have 1 or more arguments that have closure pointers.
4907 const char *startBuf = SM->getCharacterData(DeclLoc);
4908 const char *startArgList = strchr(startBuf, '(');
4909
4910 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4911
4912 parenCount++;
4913 // advance the location to startArgList.
4914 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4915 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4916
4917 const char *argPtr = startArgList;
4918
4919 while (*argPtr++ && parenCount) {
4920 switch (*argPtr) {
4921 case '^':
4922 // Replace the '^' with '*'.
4923 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4924 ReplaceText(DeclLoc, 1, "*");
4925 break;
4926 case '(':
4927 parenCount++;
4928 break;
4929 case ')':
4930 parenCount--;
4931 break;
4932 }
4933 }
4934 return;
4935}
4936
4937bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4938 const FunctionProtoType *FTP;
4939 const PointerType *PT = QT->getAs<PointerType>();
4940 if (PT) {
4941 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4942 } else {
4943 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4944 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4945 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4946 }
4947 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004948 for (const auto &I : FTP->param_types())
4949 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004950 return true;
4951 }
4952 return false;
4953}
4954
4955bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4956 const FunctionProtoType *FTP;
4957 const PointerType *PT = QT->getAs<PointerType>();
4958 if (PT) {
4959 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4960 } else {
4961 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4962 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4963 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4964 }
4965 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004966 for (const auto &I : FTP->param_types()) {
4967 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004968 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004969 if (I->isObjCObjectPointerType() &&
4970 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004971 return true;
4972 }
4973
4974 }
4975 return false;
4976}
4977
4978void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4979 const char *&RParen) {
4980 const char *argPtr = strchr(Name, '(');
4981 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4982
4983 LParen = argPtr; // output the start.
4984 argPtr++; // skip past the left paren.
4985 unsigned parenCount = 1;
4986
4987 while (*argPtr && parenCount) {
4988 switch (*argPtr) {
4989 case '(': parenCount++; break;
4990 case ')': parenCount--; break;
4991 default: break;
4992 }
4993 if (parenCount) argPtr++;
4994 }
4995 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4996 RParen = argPtr; // output the end
4997}
4998
4999void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5000 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5001 RewriteBlockPointerFunctionArgs(FD);
5002 return;
5003 }
5004 // Handle Variables and Typedefs.
5005 SourceLocation DeclLoc = ND->getLocation();
5006 QualType DeclT;
5007 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5008 DeclT = VD->getType();
5009 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5010 DeclT = TDD->getUnderlyingType();
5011 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5012 DeclT = FD->getType();
5013 else
5014 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5015
5016 const char *startBuf = SM->getCharacterData(DeclLoc);
5017 const char *endBuf = startBuf;
5018 // scan backward (from the decl location) for the end of the previous decl.
5019 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5020 startBuf--;
5021 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5022 std::string buf;
5023 unsigned OrigLength=0;
5024 // *startBuf != '^' if we are dealing with a pointer to function that
5025 // may take block argument types (which will be handled below).
5026 if (*startBuf == '^') {
5027 // Replace the '^' with '*', computing a negative offset.
5028 buf = '*';
5029 startBuf++;
5030 OrigLength++;
5031 }
5032 while (*startBuf != ')') {
5033 buf += *startBuf;
5034 startBuf++;
5035 OrigLength++;
5036 }
5037 buf += ')';
5038 OrigLength++;
5039
5040 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5041 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5042 // Replace the '^' with '*' for arguments.
5043 // Replace id<P> with id/*<>*/
5044 DeclLoc = ND->getLocation();
5045 startBuf = SM->getCharacterData(DeclLoc);
5046 const char *argListBegin, *argListEnd;
5047 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5048 while (argListBegin < argListEnd) {
5049 if (*argListBegin == '^')
5050 buf += '*';
5051 else if (*argListBegin == '<') {
5052 buf += "/*";
5053 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005054 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005055 while (*argListBegin != '>') {
5056 buf += *argListBegin++;
5057 OrigLength++;
5058 }
5059 buf += *argListBegin;
5060 buf += "*/";
5061 }
5062 else
5063 buf += *argListBegin;
5064 argListBegin++;
5065 OrigLength++;
5066 }
5067 buf += ')';
5068 OrigLength++;
5069 }
5070 ReplaceText(Start, OrigLength, buf);
5071
5072 return;
5073}
5074
5075
5076/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5077/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5078/// struct Block_byref_id_object *src) {
5079/// _Block_object_assign (&_dest->object, _src->object,
5080/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5081/// [|BLOCK_FIELD_IS_WEAK]) // object
5082/// _Block_object_assign(&_dest->object, _src->object,
5083/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5084/// [|BLOCK_FIELD_IS_WEAK]) // block
5085/// }
5086/// And:
5087/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5088/// _Block_object_dispose(_src->object,
5089/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5090/// [|BLOCK_FIELD_IS_WEAK]) // object
5091/// _Block_object_dispose(_src->object,
5092/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5093/// [|BLOCK_FIELD_IS_WEAK]) // block
5094/// }
5095
5096std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5097 int flag) {
5098 std::string S;
5099 if (CopyDestroyCache.count(flag))
5100 return S;
5101 CopyDestroyCache.insert(flag);
5102 S = "static void __Block_byref_id_object_copy_";
5103 S += utostr(flag);
5104 S += "(void *dst, void *src) {\n";
5105
5106 // offset into the object pointer is computed as:
5107 // void * + void* + int + int + void* + void *
5108 unsigned IntSize =
5109 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5110 unsigned VoidPtrSize =
5111 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5112
5113 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5114 S += " _Block_object_assign((char*)dst + ";
5115 S += utostr(offset);
5116 S += ", *(void * *) ((char*)src + ";
5117 S += utostr(offset);
5118 S += "), ";
5119 S += utostr(flag);
5120 S += ");\n}\n";
5121
5122 S += "static void __Block_byref_id_object_dispose_";
5123 S += utostr(flag);
5124 S += "(void *src) {\n";
5125 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5126 S += utostr(offset);
5127 S += "), ";
5128 S += utostr(flag);
5129 S += ");\n}\n";
5130 return S;
5131}
5132
5133/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5134/// the declaration into:
5135/// struct __Block_byref_ND {
5136/// void *__isa; // NULL for everything except __weak pointers
5137/// struct __Block_byref_ND *__forwarding;
5138/// int32_t __flags;
5139/// int32_t __size;
5140/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5141/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5142/// typex ND;
5143/// };
5144///
5145/// It then replaces declaration of ND variable with:
5146/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5147/// __size=sizeof(struct __Block_byref_ND),
5148/// ND=initializer-if-any};
5149///
5150///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005151void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5152 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005153 int flag = 0;
5154 int isa = 0;
5155 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5156 if (DeclLoc.isInvalid())
5157 // If type location is missing, it is because of missing type (a warning).
5158 // Use variable's location which is good for this case.
5159 DeclLoc = ND->getLocation();
5160 const char *startBuf = SM->getCharacterData(DeclLoc);
5161 SourceLocation X = ND->getLocEnd();
5162 X = SM->getExpansionLoc(X);
5163 const char *endBuf = SM->getCharacterData(X);
5164 std::string Name(ND->getNameAsString());
5165 std::string ByrefType;
5166 RewriteByRefString(ByrefType, Name, ND, true);
5167 ByrefType += " {\n";
5168 ByrefType += " void *__isa;\n";
5169 RewriteByRefString(ByrefType, Name, ND);
5170 ByrefType += " *__forwarding;\n";
5171 ByrefType += " int __flags;\n";
5172 ByrefType += " int __size;\n";
5173 // Add void *__Block_byref_id_object_copy;
5174 // void *__Block_byref_id_object_dispose; if needed.
5175 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005176 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005177 if (HasCopyAndDispose) {
5178 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5179 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5180 }
5181
5182 QualType T = Ty;
5183 (void)convertBlockPointerToFunctionPointer(T);
5184 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5185
5186 ByrefType += " " + Name + ";\n";
5187 ByrefType += "};\n";
5188 // Insert this type in global scope. It is needed by helper function.
5189 SourceLocation FunLocStart;
5190 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005191 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005192 else {
5193 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5194 FunLocStart = CurMethodDef->getLocStart();
5195 }
5196 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005197
Fariborz Jahanian11671902012-02-07 17:11:38 +00005198 if (Ty.isObjCGCWeak()) {
5199 flag |= BLOCK_FIELD_IS_WEAK;
5200 isa = 1;
5201 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005202 if (HasCopyAndDispose) {
5203 flag = BLOCK_BYREF_CALLER;
5204 QualType Ty = ND->getType();
5205 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5206 if (Ty->isBlockPointerType())
5207 flag |= BLOCK_FIELD_IS_BLOCK;
5208 else
5209 flag |= BLOCK_FIELD_IS_OBJECT;
5210 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5211 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005212 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005213 }
5214
5215 // struct __Block_byref_ND ND =
5216 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5217 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005218 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005219 // FIXME. rewriter does not support __block c++ objects which
5220 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005221 if (hasInit)
5222 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5223 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5224 if (CXXDecl && CXXDecl->isDefaultConstructor())
5225 hasInit = false;
5226 }
5227
Fariborz Jahanian11671902012-02-07 17:11:38 +00005228 unsigned flags = 0;
5229 if (HasCopyAndDispose)
5230 flags |= BLOCK_HAS_COPY_DISPOSE;
5231 Name = ND->getNameAsString();
5232 ByrefType.clear();
5233 RewriteByRefString(ByrefType, Name, ND);
5234 std::string ForwardingCastType("(");
5235 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005236 ByrefType += " " + Name + " = {(void*)";
5237 ByrefType += utostr(isa);
5238 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5239 ByrefType += utostr(flags);
5240 ByrefType += ", ";
5241 ByrefType += "sizeof(";
5242 RewriteByRefString(ByrefType, Name, ND);
5243 ByrefType += ")";
5244 if (HasCopyAndDispose) {
5245 ByrefType += ", __Block_byref_id_object_copy_";
5246 ByrefType += utostr(flag);
5247 ByrefType += ", __Block_byref_id_object_dispose_";
5248 ByrefType += utostr(flag);
5249 }
5250
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005251 if (!firstDecl) {
5252 // In multiple __block declarations, and for all but 1st declaration,
5253 // find location of the separating comma. This would be start location
5254 // where new text is to be inserted.
5255 DeclLoc = ND->getLocation();
5256 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5257 const char *commaBuf = startDeclBuf;
5258 while (*commaBuf != ',')
5259 commaBuf--;
5260 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5261 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5262 startBuf = commaBuf;
5263 }
5264
Fariborz Jahanian11671902012-02-07 17:11:38 +00005265 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005266 ByrefType += "};\n";
5267 unsigned nameSize = Name.size();
5268 // for block or function pointer declaration. Name is aleady
5269 // part of the declaration.
5270 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5271 nameSize = 1;
5272 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5273 }
5274 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005275 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005276 SourceLocation startLoc;
5277 Expr *E = ND->getInit();
5278 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5279 startLoc = ECE->getLParenLoc();
5280 else
5281 startLoc = E->getLocStart();
5282 startLoc = SM->getExpansionLoc(startLoc);
5283 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005284 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005285
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005286 const char separator = lastDecl ? ';' : ',';
5287 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5288 const char *separatorBuf = strchr(startInitializerBuf, separator);
5289 assert((*separatorBuf == separator) &&
5290 "RewriteByRefVar: can't find ';' or ','");
5291 SourceLocation separatorLoc =
5292 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5293
5294 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005295 }
5296 return;
5297}
5298
5299void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5300 // Add initializers for any closure decl refs.
5301 GetBlockDeclRefExprs(Exp->getBody());
5302 if (BlockDeclRefs.size()) {
5303 // Unique all "by copy" declarations.
5304 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005305 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005306 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5307 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5308 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5309 }
5310 }
5311 // Unique all "by ref" declarations.
5312 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005313 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005314 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5315 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5316 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5317 }
5318 }
5319 // Find any imported blocks...they will need special attention.
5320 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005321 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005322 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5323 BlockDeclRefs[i]->getType()->isBlockPointerType())
5324 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5325 }
5326}
5327
5328FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5329 IdentifierInfo *ID = &Context->Idents.get(name);
5330 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5331 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005332 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005333 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005334}
5335
5336Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005337 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005338
Fariborz Jahanian11671902012-02-07 17:11:38 +00005339 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005340
Fariborz Jahanian11671902012-02-07 17:11:38 +00005341 Blocks.push_back(Exp);
5342
5343 CollectBlockDeclRefInfo(Exp);
5344
5345 // Add inner imported variables now used in current block.
5346 int countOfInnerDecls = 0;
5347 if (!InnerBlockDeclRefs.empty()) {
5348 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005349 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005350 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005351 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005352 // We need to save the copied-in variables in nested
5353 // blocks because it is needed at the end for some of the API generations.
5354 // See SynthesizeBlockLiterals routine.
5355 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5356 BlockDeclRefs.push_back(Exp);
5357 BlockByCopyDeclsPtrSet.insert(VD);
5358 BlockByCopyDecls.push_back(VD);
5359 }
John McCall113bee02012-03-10 09:33:50 +00005360 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5362 BlockDeclRefs.push_back(Exp);
5363 BlockByRefDeclsPtrSet.insert(VD);
5364 BlockByRefDecls.push_back(VD);
5365 }
5366 }
5367 // Find any imported blocks...they will need special attention.
5368 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005369 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005370 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5371 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5372 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5373 }
5374 InnerDeclRefsCount.push_back(countOfInnerDecls);
5375
5376 std::string FuncName;
5377
5378 if (CurFunctionDef)
5379 FuncName = CurFunctionDef->getNameAsString();
5380 else if (CurMethodDef)
5381 BuildUniqueMethodName(FuncName, CurMethodDef);
5382 else if (GlobalVarDecl)
5383 FuncName = std::string(GlobalVarDecl->getNameAsString());
5384
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005385 bool GlobalBlockExpr =
5386 block->getDeclContext()->getRedeclContext()->isFileContext();
5387
5388 if (GlobalBlockExpr && !GlobalVarDecl) {
5389 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5390 GlobalBlockExpr = false;
5391 }
5392
Fariborz Jahanian11671902012-02-07 17:11:38 +00005393 std::string BlockNumber = utostr(Blocks.size()-1);
5394
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5396
5397 // Get a pointer to the function type so we can cast appropriately.
5398 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5399 QualType FType = Context->getPointerType(BFT);
5400
5401 FunctionDecl *FD;
5402 Expr *NewRep;
5403
Benjamin Kramer60509af2013-09-09 14:48:42 +00005404 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005405 std::string Tag;
5406
5407 if (GlobalBlockExpr)
5408 Tag = "__global_";
5409 else
5410 Tag = "__";
5411 Tag += FuncName + "_block_impl_" + BlockNumber;
5412
Fariborz Jahanian11671902012-02-07 17:11:38 +00005413 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005414 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005415 SourceLocation());
5416
5417 SmallVector<Expr*, 4> InitExprs;
5418
5419 // Initialize the block function.
5420 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005421 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5422 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005423 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5424 CK_BitCast, Arg);
5425 InitExprs.push_back(castExpr);
5426
5427 // Initialize the block descriptor.
5428 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5429
5430 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5431 SourceLocation(), SourceLocation(),
5432 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005433 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005434 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005435 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005436 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005437 Context->VoidPtrTy,
5438 VK_LValue,
5439 SourceLocation()),
5440 UO_AddrOf,
5441 Context->getPointerType(Context->VoidPtrTy),
5442 VK_RValue, OK_Ordinary,
5443 SourceLocation());
5444 InitExprs.push_back(DescRefExpr);
5445
5446 // Add initializers for any closure decl refs.
5447 if (BlockDeclRefs.size()) {
5448 Expr *Exp;
5449 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005450 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005451 E = BlockByCopyDecls.end(); I != E; ++I) {
5452 if (isObjCType((*I)->getType())) {
5453 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5454 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005455 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5456 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005457 if (HasLocalVariableExternalStorage(*I)) {
5458 QualType QT = (*I)->getType();
5459 QT = Context->getPointerType(QT);
5460 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5461 OK_Ordinary, SourceLocation());
5462 }
5463 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5464 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005465 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5466 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005467 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5468 CK_BitCast, Arg);
5469 } else {
5470 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005471 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5472 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005473 if (HasLocalVariableExternalStorage(*I)) {
5474 QualType QT = (*I)->getType();
5475 QT = Context->getPointerType(QT);
5476 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5477 OK_Ordinary, SourceLocation());
5478 }
5479
5480 }
5481 InitExprs.push_back(Exp);
5482 }
5483 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005484 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005485 E = BlockByRefDecls.end(); I != E; ++I) {
5486 ValueDecl *ND = (*I);
5487 std::string Name(ND->getNameAsString());
5488 std::string RecName;
5489 RewriteByRefString(RecName, Name, ND, true);
5490 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5491 + sizeof("struct"));
5492 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5493 SourceLocation(), SourceLocation(),
5494 II);
5495 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5496 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5497
5498 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005499 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005500 SourceLocation());
5501 bool isNestedCapturedVar = false;
5502 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005503 for (const auto &CI : block->captures()) {
5504 const VarDecl *variable = CI.getVariable();
5505 if (variable == ND && CI.isNested()) {
5506 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005507 "SynthBlockInitExpr - captured block variable is not byref");
5508 isNestedCapturedVar = true;
5509 break;
5510 }
5511 }
5512 // captured nested byref variable has its address passed. Do not take
5513 // its address again.
5514 if (!isNestedCapturedVar)
5515 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5516 Context->getPointerType(Exp->getType()),
5517 VK_RValue, OK_Ordinary, SourceLocation());
5518 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5519 InitExprs.push_back(Exp);
5520 }
5521 }
5522 if (ImportedBlockDecls.size()) {
5523 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5524 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5525 unsigned IntSize =
5526 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5527 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5528 Context->IntTy, SourceLocation());
5529 InitExprs.push_back(FlagExp);
5530 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005531 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005532 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005533
5534 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005535 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005536 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5537 GlobalConstructionExp = NewRep;
5538 NewRep = DRE;
5539 }
5540
Fariborz Jahanian11671902012-02-07 17:11:38 +00005541 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5542 Context->getPointerType(NewRep->getType()),
5543 VK_RValue, OK_Ordinary, SourceLocation());
5544 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5545 NewRep);
5546 BlockDeclRefs.clear();
5547 BlockByRefDecls.clear();
5548 BlockByRefDeclsPtrSet.clear();
5549 BlockByCopyDecls.clear();
5550 BlockByCopyDeclsPtrSet.clear();
5551 ImportedBlockDecls.clear();
5552 return NewRep;
5553}
5554
5555bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5556 if (const ObjCForCollectionStmt * CS =
5557 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5558 return CS->getElement() == DS;
5559 return false;
5560}
5561
5562//===----------------------------------------------------------------------===//
5563// Function Body / Expression rewriting
5564//===----------------------------------------------------------------------===//
5565
5566Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5567 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5568 isa<DoStmt>(S) || isa<ForStmt>(S))
5569 Stmts.push_back(S);
5570 else if (isa<ObjCForCollectionStmt>(S)) {
5571 Stmts.push_back(S);
5572 ObjCBcLabelNo.push_back(++BcLabelCount);
5573 }
5574
5575 // Pseudo-object operations and ivar references need special
5576 // treatment because we're going to recursively rewrite them.
5577 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5578 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5579 return RewritePropertyOrImplicitSetter(PseudoOp);
5580 } else {
5581 return RewritePropertyOrImplicitGetter(PseudoOp);
5582 }
5583 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5584 return RewriteObjCIvarRefExpr(IvarRefExpr);
5585 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005586 else if (isa<OpaqueValueExpr>(S))
5587 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005588
5589 SourceRange OrigStmtRange = S->getSourceRange();
5590
5591 // Perform a bottom up rewrite of all children.
5592 for (Stmt::child_range CI = S->children(); CI; ++CI)
5593 if (*CI) {
5594 Stmt *childStmt = (*CI);
5595 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5596 if (newStmt) {
5597 *CI = newStmt;
5598 }
5599 }
5600
5601 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005602 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005603 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5604 InnerContexts.insert(BE->getBlockDecl());
5605 ImportedLocalExternalDecls.clear();
5606 GetInnerBlockDeclRefExprs(BE->getBody(),
5607 InnerBlockDeclRefs, InnerContexts);
5608 // Rewrite the block body in place.
5609 Stmt *SaveCurrentBody = CurrentBody;
5610 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005611 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005612 // block literal on rhs of a property-dot-sytax assignment
5613 // must be replaced by its synthesize ast so getRewrittenText
5614 // works as expected. In this case, what actually ends up on RHS
5615 // is the blockTranscribed which is the helper function for the
5616 // block literal; as in: self.c = ^() {[ace ARR];};
5617 bool saveDisableReplaceStmt = DisableReplaceStmt;
5618 DisableReplaceStmt = false;
5619 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5620 DisableReplaceStmt = saveDisableReplaceStmt;
5621 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005622 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005623 ImportedLocalExternalDecls.clear();
5624 // Now we snarf the rewritten text and stash it away for later use.
5625 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5626 RewrittenBlockExprs[BE] = Str;
5627
5628 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5629
5630 //blockTranscribed->dump();
5631 ReplaceStmt(S, blockTranscribed);
5632 return blockTranscribed;
5633 }
5634 // Handle specific things.
5635 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5636 return RewriteAtEncode(AtEncode);
5637
5638 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5639 return RewriteAtSelector(AtSelector);
5640
5641 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5642 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005643
5644 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5645 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005646
Patrick Beard0caa3942012-04-19 00:25:12 +00005647 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5648 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005649
5650 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5651 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005652
5653 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5654 dyn_cast<ObjCDictionaryLiteral>(S))
5655 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005656
5657 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5658#if 0
5659 // Before we rewrite it, put the original message expression in a comment.
5660 SourceLocation startLoc = MessExpr->getLocStart();
5661 SourceLocation endLoc = MessExpr->getLocEnd();
5662
5663 const char *startBuf = SM->getCharacterData(startLoc);
5664 const char *endBuf = SM->getCharacterData(endLoc);
5665
5666 std::string messString;
5667 messString += "// ";
5668 messString.append(startBuf, endBuf-startBuf+1);
5669 messString += "\n";
5670
5671 // FIXME: Missing definition of
5672 // InsertText(clang::SourceLocation, char const*, unsigned int).
5673 // InsertText(startLoc, messString.c_str(), messString.size());
5674 // Tried this, but it didn't work either...
5675 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5676#endif
5677 return RewriteMessageExpr(MessExpr);
5678 }
5679
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005680 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5681 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5682 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5683 }
5684
Fariborz Jahanian11671902012-02-07 17:11:38 +00005685 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5686 return RewriteObjCTryStmt(StmtTry);
5687
5688 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5689 return RewriteObjCSynchronizedStmt(StmtTry);
5690
5691 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5692 return RewriteObjCThrowStmt(StmtThrow);
5693
5694 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5695 return RewriteObjCProtocolExpr(ProtocolExp);
5696
5697 if (ObjCForCollectionStmt *StmtForCollection =
5698 dyn_cast<ObjCForCollectionStmt>(S))
5699 return RewriteObjCForCollectionStmt(StmtForCollection,
5700 OrigStmtRange.getEnd());
5701 if (BreakStmt *StmtBreakStmt =
5702 dyn_cast<BreakStmt>(S))
5703 return RewriteBreakStmt(StmtBreakStmt);
5704 if (ContinueStmt *StmtContinueStmt =
5705 dyn_cast<ContinueStmt>(S))
5706 return RewriteContinueStmt(StmtContinueStmt);
5707
5708 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5709 // and cast exprs.
5710 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5711 // FIXME: What we're doing here is modifying the type-specifier that
5712 // precedes the first Decl. In the future the DeclGroup should have
5713 // a separate type-specifier that we can rewrite.
5714 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5715 // the context of an ObjCForCollectionStmt. For example:
5716 // NSArray *someArray;
5717 // for (id <FooProtocol> index in someArray) ;
5718 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5719 // and it depends on the original text locations/positions.
5720 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5721 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5722
5723 // Blocks rewrite rules.
5724 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5725 DI != DE; ++DI) {
5726 Decl *SD = *DI;
5727 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5728 if (isTopLevelBlockPointerType(ND->getType()))
5729 RewriteBlockPointerDecl(ND);
5730 else if (ND->getType()->isFunctionPointerType())
5731 CheckFunctionPointerDecl(ND->getType(), ND);
5732 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5733 if (VD->hasAttr<BlocksAttr>()) {
5734 static unsigned uniqueByrefDeclCount = 0;
5735 assert(!BlockByRefDeclNo.count(ND) &&
5736 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5737 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005738 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005739 }
5740 else
5741 RewriteTypeOfDecl(VD);
5742 }
5743 }
5744 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5745 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5746 RewriteBlockPointerDecl(TD);
5747 else if (TD->getUnderlyingType()->isFunctionPointerType())
5748 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5749 }
5750 }
5751 }
5752
5753 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5754 RewriteObjCQualifiedInterfaceTypes(CE);
5755
5756 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5757 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5758 assert(!Stmts.empty() && "Statement stack is empty");
5759 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5760 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5761 && "Statement stack mismatch");
5762 Stmts.pop_back();
5763 }
5764 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5766 ValueDecl *VD = DRE->getDecl();
5767 if (VD->hasAttr<BlocksAttr>())
5768 return RewriteBlockDeclRefExpr(DRE);
5769 if (HasLocalVariableExternalStorage(VD))
5770 return RewriteLocalVariableExternalStorage(DRE);
5771 }
5772
5773 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5774 if (CE->getCallee()->getType()->isBlockPointerType()) {
5775 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5776 ReplaceStmt(S, BlockCall);
5777 return BlockCall;
5778 }
5779 }
5780 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5781 RewriteCastExpr(CE);
5782 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5784 RewriteImplicitCastObjCExpr(ICE);
5785 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005786#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005787
Fariborz Jahanian11671902012-02-07 17:11:38 +00005788 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5789 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5790 ICE->getSubExpr(),
5791 SourceLocation());
5792 // Get the new text.
5793 std::string SStr;
5794 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005795 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005796 const std::string &Str = Buf.str();
5797
5798 printf("CAST = %s\n", &Str[0]);
5799 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5800 delete S;
5801 return Replacement;
5802 }
5803#endif
5804 // Return this stmt unmodified.
5805 return S;
5806}
5807
5808void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005809 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005810 if (isTopLevelBlockPointerType(FD->getType()))
5811 RewriteBlockPointerDecl(FD);
5812 if (FD->getType()->isObjCQualifiedIdType() ||
5813 FD->getType()->isObjCQualifiedInterfaceType())
5814 RewriteObjCQualifiedInterfaceTypes(FD);
5815 }
5816}
5817
5818/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5819/// main file of the input.
5820void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5821 switch (D->getKind()) {
5822 case Decl::Function: {
5823 FunctionDecl *FD = cast<FunctionDecl>(D);
5824 if (FD->isOverloadedOperator())
5825 return;
5826
5827 // Since function prototypes don't have ParmDecl's, we check the function
5828 // prototype. This enables us to rewrite function declarations and
5829 // definitions using the same code.
5830 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5831
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005832 if (!FD->isThisDeclarationADefinition())
5833 break;
5834
Fariborz Jahanian11671902012-02-07 17:11:38 +00005835 // FIXME: If this should support Obj-C++, support CXXTryStmt
5836 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5837 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005838 CurrentBody = Body;
5839 Body =
5840 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5841 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005842 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005843 if (PropParentMap) {
5844 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005845 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005846 }
5847 // This synthesizes and inserts the block "impl" struct, invoke function,
5848 // and any copy/dispose helper functions.
5849 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005850 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005851 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005852 }
5853 break;
5854 }
5855 case Decl::ObjCMethod: {
5856 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5857 if (CompoundStmt *Body = MD->getCompoundBody()) {
5858 CurMethodDef = MD;
5859 CurrentBody = Body;
5860 Body =
5861 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5862 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005863 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005864 if (PropParentMap) {
5865 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005866 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005867 }
5868 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005869 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005870 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005871 }
5872 break;
5873 }
5874 case Decl::ObjCImplementation: {
5875 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5876 ClassImplementation.push_back(CI);
5877 break;
5878 }
5879 case Decl::ObjCCategoryImpl: {
5880 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5881 CategoryImplementation.push_back(CI);
5882 break;
5883 }
5884 case Decl::Var: {
5885 VarDecl *VD = cast<VarDecl>(D);
5886 RewriteObjCQualifiedInterfaceTypes(VD);
5887 if (isTopLevelBlockPointerType(VD->getType()))
5888 RewriteBlockPointerDecl(VD);
5889 else if (VD->getType()->isFunctionPointerType()) {
5890 CheckFunctionPointerDecl(VD->getType(), VD);
5891 if (VD->getInit()) {
5892 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5893 RewriteCastExpr(CE);
5894 }
5895 }
5896 } else if (VD->getType()->isRecordType()) {
5897 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5898 if (RD->isCompleteDefinition())
5899 RewriteRecordBody(RD);
5900 }
5901 if (VD->getInit()) {
5902 GlobalVarDecl = VD;
5903 CurrentBody = VD->getInit();
5904 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005905 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005906 if (PropParentMap) {
5907 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005908 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005909 }
5910 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005911 GlobalVarDecl = nullptr;
5912
Fariborz Jahanian11671902012-02-07 17:11:38 +00005913 // This is needed for blocks.
5914 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5915 RewriteCastExpr(CE);
5916 }
5917 }
5918 break;
5919 }
5920 case Decl::TypeAlias:
5921 case Decl::Typedef: {
5922 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5923 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5924 RewriteBlockPointerDecl(TD);
5925 else if (TD->getUnderlyingType()->isFunctionPointerType())
5926 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005927 else
5928 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005929 }
5930 break;
5931 }
5932 case Decl::CXXRecord:
5933 case Decl::Record: {
5934 RecordDecl *RD = cast<RecordDecl>(D);
5935 if (RD->isCompleteDefinition())
5936 RewriteRecordBody(RD);
5937 break;
5938 }
5939 default:
5940 break;
5941 }
5942 // Nothing yet.
5943}
5944
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005945/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5946/// protocol reference symbols in the for of:
5947/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5948static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5949 ObjCProtocolDecl *PDecl,
5950 std::string &Result) {
5951 // Also output .objc_protorefs$B section and its meta-data.
5952 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005953 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005954 Result += "struct _protocol_t *";
5955 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5956 Result += PDecl->getNameAsString();
5957 Result += " = &";
5958 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5959 Result += ";\n";
5960}
5961
Fariborz Jahanian11671902012-02-07 17:11:38 +00005962void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5963 if (Diags.hasErrorOccurred())
5964 return;
5965
5966 RewriteInclude();
5967
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005968 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005969 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005970 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005971 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005972 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5973 HandleTopLevelSingleDecl(FDecl);
5974 }
5975
Fariborz Jahanian11671902012-02-07 17:11:38 +00005976 // Here's a great place to add any extra declarations that may be needed.
5977 // Write out meta data for each @protocol(<expr>).
5978 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005979 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00005980 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005981 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5982 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005983
5984 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005985
5986 if (ClassImplementation.size() || CategoryImplementation.size())
5987 RewriteImplementations();
5988
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005989 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5990 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5991 // Write struct declaration for the class matching its ivar declarations.
5992 // Note that for modern abi, this is postponed until the end of TU
5993 // because class extensions and the implementation might declare their own
5994 // private ivars.
5995 RewriteInterfaceDecl(CDecl);
5996 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005997
Fariborz Jahanian11671902012-02-07 17:11:38 +00005998 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5999 // we are done.
6000 if (const RewriteBuffer *RewriteBuf =
6001 Rewrite.getRewriteBufferFor(MainFileID)) {
6002 //printf("Changed:\n");
6003 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6004 } else {
6005 llvm::errs() << "No changes\n";
6006 }
6007
6008 if (ClassImplementation.size() || CategoryImplementation.size() ||
6009 ProtocolExprDecls.size()) {
6010 // Rewrite Objective-c meta data*
6011 std::string ResultStr;
6012 RewriteMetaDataIntoBuffer(ResultStr);
6013 // Emit metadata.
6014 *OutFile << ResultStr;
6015 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006016 // Emit ImageInfo;
6017 {
6018 std::string ResultStr;
6019 WriteImageInfo(ResultStr);
6020 *OutFile << ResultStr;
6021 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006022 OutFile->flush();
6023}
6024
6025void RewriteModernObjC::Initialize(ASTContext &context) {
6026 InitializeCommon(context);
6027
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006028 Preamble += "#ifndef __OBJC2__\n";
6029 Preamble += "#define __OBJC2__\n";
6030 Preamble += "#endif\n";
6031
Fariborz Jahanian11671902012-02-07 17:11:38 +00006032 // declaring objc_selector outside the parameter list removes a silly
6033 // scope related warning...
6034 if (IsHeader)
6035 Preamble = "#pragma once\n";
6036 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006037 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6038 Preamble += "\n\tstruct objc_object *superClass; ";
6039 // Add a constructor for creating temporary objects.
6040 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6041 Preamble += ": object(o), superClass(s) {} ";
6042 Preamble += "\n};\n";
6043
Fariborz Jahanian11671902012-02-07 17:11:38 +00006044 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006045 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006046 // These are currently generated.
6047 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006048 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006049 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006050 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6051 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006052 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006053 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006054 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6055 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006056 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006057
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006058 // These need be generated for performance. Currently they are not,
6059 // using API calls instead.
6060 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6061 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6062 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6063
Fariborz Jahanian11671902012-02-07 17:11:38 +00006064 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006065 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6066 Preamble += "typedef struct objc_object Protocol;\n";
6067 Preamble += "#define _REWRITER_typedef_Protocol\n";
6068 Preamble += "#endif\n";
6069 if (LangOpts.MicrosoftExt) {
6070 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6071 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006072 }
6073 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006074 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006075
6076 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6077 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6078 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6079 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6080 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6081
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006082 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006083 Preamble += "(const char *);\n";
6084 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6085 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006086 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006087 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006088 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006089 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006090 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6091 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006092 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006093 Preamble += "#ifdef _WIN64\n";
6094 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6095 Preamble += "#else\n";
6096 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6097 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006098 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6099 Preamble += "struct __objcFastEnumerationState {\n\t";
6100 Preamble += "unsigned long state;\n\t";
6101 Preamble += "void **itemsPtr;\n\t";
6102 Preamble += "unsigned long *mutationsPtr;\n\t";
6103 Preamble += "unsigned long extra[5];\n};\n";
6104 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6105 Preamble += "#define __FASTENUMERATIONSTATE\n";
6106 Preamble += "#endif\n";
6107 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6108 Preamble += "struct __NSConstantStringImpl {\n";
6109 Preamble += " int *isa;\n";
6110 Preamble += " int flags;\n";
6111 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00006112 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006113 Preamble += " long long length;\n";
6114 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006115 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006116 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006117 Preamble += "};\n";
6118 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6119 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6120 Preamble += "#else\n";
6121 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6122 Preamble += "#endif\n";
6123 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6124 Preamble += "#endif\n";
6125 // Blocks preamble.
6126 Preamble += "#ifndef BLOCK_IMPL\n";
6127 Preamble += "#define BLOCK_IMPL\n";
6128 Preamble += "struct __block_impl {\n";
6129 Preamble += " void *isa;\n";
6130 Preamble += " int Flags;\n";
6131 Preamble += " int Reserved;\n";
6132 Preamble += " void *FuncPtr;\n";
6133 Preamble += "};\n";
6134 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6135 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6136 Preamble += "extern \"C\" __declspec(dllexport) "
6137 "void _Block_object_assign(void *, const void *, const int);\n";
6138 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6139 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6140 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6141 Preamble += "#else\n";
6142 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6143 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6144 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6145 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6146 Preamble += "#endif\n";
6147 Preamble += "#endif\n";
6148 if (LangOpts.MicrosoftExt) {
6149 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6150 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6151 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6152 Preamble += "#define __attribute__(X)\n";
6153 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006154 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006155 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006156 Preamble += "#endif\n";
6157 Preamble += "#ifndef __block\n";
6158 Preamble += "#define __block\n";
6159 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006160 }
6161 else {
6162 Preamble += "#define __block\n";
6163 Preamble += "#define __weak\n";
6164 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006165
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006166 // Declarations required for modern objective-c array and dictionary literals.
6167 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006168 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006169 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006170 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006171 Preamble += "\tva_list marker;\n";
6172 Preamble += "\tva_start(marker, count);\n";
6173 Preamble += "\tarr = new void *[count];\n";
6174 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6175 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6176 Preamble += "\tva_end( marker );\n";
6177 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006178 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006179 Preamble += "\tdelete[] arr;\n";
6180 Preamble += " }\n";
6181 Preamble += "};\n";
6182
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006183 // Declaration required for implementation of @autoreleasepool statement.
6184 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6185 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6186 Preamble += "struct __AtAutoreleasePool {\n";
6187 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6188 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6189 Preamble += " void * atautoreleasepoolobj;\n";
6190 Preamble += "};\n";
6191
Fariborz Jahanian11671902012-02-07 17:11:38 +00006192 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6193 // as this avoids warning in any 64bit/32bit compilation model.
6194 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6195}
6196
6197/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6198/// ivar offset.
6199void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6200 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006201 Result += "__OFFSETOFIVAR__(struct ";
6202 Result += ivar->getContainingInterface()->getNameAsString();
6203 if (LangOpts.MicrosoftExt)
6204 Result += "_IMPL";
6205 Result += ", ";
6206 if (ivar->isBitField())
6207 ObjCIvarBitfieldGroupDecl(ivar, Result);
6208 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006209 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006210 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006211}
6212
6213/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6214/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006215/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006216/// char *attributes;
6217/// }
6218
6219/// struct _prop_list_t {
6220/// uint32_t entsize; // sizeof(struct _prop_t)
6221/// uint32_t count_of_properties;
6222/// struct _prop_t prop_list[count_of_properties];
6223/// }
6224
6225/// struct _protocol_t;
6226
6227/// struct _protocol_list_t {
6228/// long protocol_count; // Note, this is 32/64 bit
6229/// struct _protocol_t * protocol_list[protocol_count];
6230/// }
6231
6232/// struct _objc_method {
6233/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006234/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006235/// char *_imp;
6236/// }
6237
6238/// struct _method_list_t {
6239/// uint32_t entsize; // sizeof(struct _objc_method)
6240/// uint32_t method_count;
6241/// struct _objc_method method_list[method_count];
6242/// }
6243
6244/// struct _protocol_t {
6245/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006246/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006247/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006248/// const struct method_list_t *instance_methods;
6249/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006250/// const struct method_list_t *optionalInstanceMethods;
6251/// const struct method_list_t *optionalClassMethods;
6252/// const struct _prop_list_t * properties;
6253/// const uint32_t size; // sizeof(struct _protocol_t)
6254/// const uint32_t flags; // = 0
6255/// const char ** extendedMethodTypes;
6256/// }
6257
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006258/// struct _ivar_t {
6259/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006260/// const char *name;
6261/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006262/// uint32_t alignment;
6263/// uint32_t size;
6264/// }
6265
6266/// struct _ivar_list_t {
6267/// uint32 entsize; // sizeof(struct _ivar_t)
6268/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006269/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006270/// }
6271
6272/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006273/// uint32_t flags;
6274/// uint32_t instanceStart;
6275/// uint32_t instanceSize;
6276/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006277/// const uint8_t *ivarLayout;
6278/// const char *name;
6279/// const struct _method_list_t *baseMethods;
6280/// const struct _protocol_list_t *baseProtocols;
6281/// const struct _ivar_list_t *ivars;
6282/// const uint8_t *weakIvarLayout;
6283/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006284/// }
6285
6286/// struct _class_t {
6287/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006288/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006289/// void *cache;
6290/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006291/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006292/// }
6293
6294/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006295/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006296/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006297/// const struct _method_list_t *instance_methods;
6298/// const struct _method_list_t *class_methods;
6299/// const struct _protocol_list_t *protocols;
6300/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006301/// }
6302
6303/// MessageRefTy - LLVM for:
6304/// struct _message_ref_t {
6305/// IMP messenger;
6306/// SEL name;
6307/// };
6308
6309/// SuperMessageRefTy - LLVM for:
6310/// struct _super_message_ref_t {
6311/// SUPER_IMP messenger;
6312/// SEL name;
6313/// };
6314
Fariborz Jahanian45489622012-03-14 18:09:23 +00006315static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006316 static bool meta_data_declared = false;
6317 if (meta_data_declared)
6318 return;
6319
6320 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006321 Result += "\tconst char *name;\n";
6322 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006323 Result += "};\n";
6324
6325 Result += "\nstruct _protocol_t;\n";
6326
Fariborz Jahanian11671902012-02-07 17:11:38 +00006327 Result += "\nstruct _objc_method {\n";
6328 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006329 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006330 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006331 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006332
6333 Result += "\nstruct _protocol_t {\n";
6334 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006335 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006336 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006337 Result += "\tconst struct method_list_t *instance_methods;\n";
6338 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006339 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6340 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6341 Result += "\tconst struct _prop_list_t * properties;\n";
6342 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6343 Result += "\tconst unsigned int flags; // = 0\n";
6344 Result += "\tconst char ** extendedMethodTypes;\n";
6345 Result += "};\n";
6346
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006347 Result += "\nstruct _ivar_t {\n";
6348 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006349 Result += "\tconst char *name;\n";
6350 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006351 Result += "\tunsigned int alignment;\n";
6352 Result += "\tunsigned int size;\n";
6353 Result += "};\n";
6354
6355 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006356 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006357 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006358 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006359 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6360 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006361 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006362 Result += "\tconst unsigned char *ivarLayout;\n";
6363 Result += "\tconst char *name;\n";
6364 Result += "\tconst struct _method_list_t *baseMethods;\n";
6365 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6366 Result += "\tconst struct _ivar_list_t *ivars;\n";
6367 Result += "\tconst unsigned char *weakIvarLayout;\n";
6368 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006369 Result += "};\n";
6370
6371 Result += "\nstruct _class_t {\n";
6372 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006373 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006374 Result += "\tvoid *cache;\n";
6375 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006376 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006377 Result += "};\n";
6378
6379 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006380 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006381 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006382 Result += "\tconst struct _method_list_t *instance_methods;\n";
6383 Result += "\tconst struct _method_list_t *class_methods;\n";
6384 Result += "\tconst struct _protocol_list_t *protocols;\n";
6385 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006386 Result += "};\n";
6387
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006388 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006389 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006390 meta_data_declared = true;
6391}
6392
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006393static void Write_protocol_list_t_TypeDecl(std::string &Result,
6394 long super_protocol_count) {
6395 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6396 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6397 Result += "\tstruct _protocol_t *super_protocols[";
6398 Result += utostr(super_protocol_count); Result += "];\n";
6399 Result += "}";
6400}
6401
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006402static void Write_method_list_t_TypeDecl(std::string &Result,
6403 unsigned int method_count) {
6404 Result += "struct /*_method_list_t*/"; Result += " {\n";
6405 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6406 Result += "\tunsigned int method_count;\n";
6407 Result += "\tstruct _objc_method method_list[";
6408 Result += utostr(method_count); Result += "];\n";
6409 Result += "}";
6410}
6411
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006412static void Write__prop_list_t_TypeDecl(std::string &Result,
6413 unsigned int property_count) {
6414 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6415 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6416 Result += "\tunsigned int count_of_properties;\n";
6417 Result += "\tstruct _prop_t prop_list[";
6418 Result += utostr(property_count); Result += "];\n";
6419 Result += "}";
6420}
6421
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006422static void Write__ivar_list_t_TypeDecl(std::string &Result,
6423 unsigned int ivar_count) {
6424 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6425 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6426 Result += "\tunsigned int count;\n";
6427 Result += "\tstruct _ivar_t ivar_list[";
6428 Result += utostr(ivar_count); Result += "];\n";
6429 Result += "}";
6430}
6431
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006432static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6433 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6434 StringRef VarName,
6435 StringRef ProtocolName) {
6436 if (SuperProtocols.size() > 0) {
6437 Result += "\nstatic ";
6438 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6439 Result += " "; Result += VarName;
6440 Result += ProtocolName;
6441 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6442 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6443 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6444 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6445 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6446 Result += SuperPD->getNameAsString();
6447 if (i == e-1)
6448 Result += "\n};\n";
6449 else
6450 Result += ",\n";
6451 }
6452 }
6453}
6454
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006455static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6456 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006457 ArrayRef<ObjCMethodDecl *> Methods,
6458 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006459 StringRef TopLevelDeclName,
6460 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006461 if (Methods.size() > 0) {
6462 Result += "\nstatic ";
6463 Write_method_list_t_TypeDecl(Result, Methods.size());
6464 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006465 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006466 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6467 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6468 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6469 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6470 ObjCMethodDecl *MD = Methods[i];
6471 if (i == 0)
6472 Result += "\t{{(struct objc_selector *)\"";
6473 else
6474 Result += "\t{(struct objc_selector *)\"";
6475 Result += (MD)->getSelector().getAsString(); Result += "\"";
6476 Result += ", ";
6477 std::string MethodTypeString;
6478 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6479 Result += "\""; Result += MethodTypeString; Result += "\"";
6480 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006481 if (!MethodImpl)
6482 Result += "0";
6483 else {
6484 Result += "(void *)";
6485 Result += RewriteObj.MethodInternalNames[MD];
6486 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006487 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006488 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006489 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006490 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006491 }
6492 Result += "};\n";
6493 }
6494}
6495
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006496static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006497 ASTContext *Context, std::string &Result,
6498 ArrayRef<ObjCPropertyDecl *> Properties,
6499 const Decl *Container,
6500 StringRef VarName,
6501 StringRef ProtocolName) {
6502 if (Properties.size() > 0) {
6503 Result += "\nstatic ";
6504 Write__prop_list_t_TypeDecl(Result, Properties.size());
6505 Result += " "; Result += VarName;
6506 Result += ProtocolName;
6507 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6508 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6509 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6510 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6511 ObjCPropertyDecl *PropDecl = Properties[i];
6512 if (i == 0)
6513 Result += "\t{{\"";
6514 else
6515 Result += "\t{\"";
6516 Result += PropDecl->getName(); Result += "\",";
6517 std::string PropertyTypeString, QuotePropertyTypeString;
6518 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6519 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6520 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6521 if (i == e-1)
6522 Result += "}}\n";
6523 else
6524 Result += "},\n";
6525 }
6526 Result += "};\n";
6527 }
6528}
6529
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006530// Metadata flags
6531enum MetaDataDlags {
6532 CLS = 0x0,
6533 CLS_META = 0x1,
6534 CLS_ROOT = 0x2,
6535 OBJC2_CLS_HIDDEN = 0x10,
6536 CLS_EXCEPTION = 0x20,
6537
6538 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6539 CLS_HAS_IVAR_RELEASER = 0x40,
6540 /// class was compiled with -fobjc-arr
6541 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6542};
6543
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006544static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6545 unsigned int flags,
6546 const std::string &InstanceStart,
6547 const std::string &InstanceSize,
6548 ArrayRef<ObjCMethodDecl *>baseMethods,
6549 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6550 ArrayRef<ObjCIvarDecl *>ivars,
6551 ArrayRef<ObjCPropertyDecl *>Properties,
6552 StringRef VarName,
6553 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006554 Result += "\nstatic struct _class_ro_t ";
6555 Result += VarName; Result += ClassName;
6556 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6557 Result += "\t";
6558 Result += llvm::utostr(flags); Result += ", ";
6559 Result += InstanceStart; Result += ", ";
6560 Result += InstanceSize; Result += ", \n";
6561 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006562 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6563 if (Triple.getArch() == llvm::Triple::x86_64)
6564 // uint32_t const reserved; // only when building for 64bit targets
6565 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006566 // const uint8_t * const ivarLayout;
6567 Result += "0, \n\t";
6568 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006569 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006570 if (baseMethods.size() > 0) {
6571 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006572 if (metaclass)
6573 Result += "_OBJC_$_CLASS_METHODS_";
6574 else
6575 Result += "_OBJC_$_INSTANCE_METHODS_";
6576 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006577 Result += ",\n\t";
6578 }
6579 else
6580 Result += "0, \n\t";
6581
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006582 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006583 Result += "(const struct _objc_protocol_list *)&";
6584 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6585 Result += ",\n\t";
6586 }
6587 else
6588 Result += "0, \n\t";
6589
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006590 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006591 Result += "(const struct _ivar_list_t *)&";
6592 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6593 Result += ",\n\t";
6594 }
6595 else
6596 Result += "0, \n\t";
6597
6598 // weakIvarLayout
6599 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006600 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006601 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006602 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006603 Result += ",\n";
6604 }
6605 else
6606 Result += "0, \n";
6607
6608 Result += "};\n";
6609}
6610
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006611static void Write_class_t(ASTContext *Context, std::string &Result,
6612 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006613 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6614 bool rootClass = (!CDecl->getSuperClass());
6615 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006616
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006617 if (!rootClass) {
6618 // Find the Root class
6619 RootClass = CDecl->getSuperClass();
6620 while (RootClass->getSuperClass()) {
6621 RootClass = RootClass->getSuperClass();
6622 }
6623 }
6624
6625 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006626 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006627 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006628 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006629 if (CDecl->getImplementation())
6630 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006631 else
6632 Result += "__declspec(dllimport) ";
6633
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006634 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006635 Result += CDecl->getNameAsString();
6636 Result += ";\n";
6637 }
6638 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006639 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006640 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006641 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006642 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006643 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006644 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006645 else
6646 Result += "__declspec(dllimport) ";
6647
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006648 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006649 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006650 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006651 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006652
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006653 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006654 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006655 if (RootClass->getImplementation())
6656 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006657 else
6658 Result += "__declspec(dllimport) ";
6659
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006660 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006661 Result += VarName;
6662 Result += RootClass->getNameAsString();
6663 Result += ";\n";
6664 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006665 }
6666
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006667 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6668 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006669 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6670 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006671 if (metaclass) {
6672 if (!rootClass) {
6673 Result += "0, // &"; Result += VarName;
6674 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006675 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006676 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006677 Result += CDecl->getSuperClass()->getNameAsString();
6678 Result += ",\n\t";
6679 }
6680 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006681 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006682 Result += CDecl->getNameAsString();
6683 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006684 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006685 Result += ",\n\t";
6686 }
6687 }
6688 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006689 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006690 Result += CDecl->getNameAsString();
6691 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006692 if (!rootClass) {
6693 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006694 Result += CDecl->getSuperClass()->getNameAsString();
6695 Result += ",\n\t";
6696 }
6697 else
6698 Result += "0,\n\t";
6699 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006700 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6701 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6702 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006703 Result += "&_OBJC_METACLASS_RO_$_";
6704 else
6705 Result += "&_OBJC_CLASS_RO_$_";
6706 Result += CDecl->getNameAsString();
6707 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006708
6709 // Add static function to initialize some of the meta-data fields.
6710 // avoid doing it twice.
6711 if (metaclass)
6712 return;
6713
6714 const ObjCInterfaceDecl *SuperClass =
6715 rootClass ? CDecl : CDecl->getSuperClass();
6716
6717 Result += "static void OBJC_CLASS_SETUP_$_";
6718 Result += CDecl->getNameAsString();
6719 Result += "(void ) {\n";
6720 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6721 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006722 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006723
6724 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006725 Result += ".superclass = ";
6726 if (rootClass)
6727 Result += "&OBJC_CLASS_$_";
6728 else
6729 Result += "&OBJC_METACLASS_$_";
6730
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006731 Result += SuperClass->getNameAsString(); Result += ";\n";
6732
6733 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6734 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6735
6736 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6737 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6738 Result += CDecl->getNameAsString(); Result += ";\n";
6739
6740 if (!rootClass) {
6741 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6742 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6743 Result += SuperClass->getNameAsString(); Result += ";\n";
6744 }
6745
6746 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6747 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6748 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006749}
6750
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006751static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6752 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006753 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006754 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006755 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6756 ArrayRef<ObjCMethodDecl *> ClassMethods,
6757 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6758 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006759 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006760 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006761 // must declare an extern class object in case this class is not implemented
6762 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006763 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006764 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006765 if (ClassDecl->getImplementation())
6766 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006767 else
6768 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006769
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006770 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006771 Result += "OBJC_CLASS_$_"; Result += ClassName;
6772 Result += ";\n";
6773
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006774 Result += "\nstatic struct _category_t ";
6775 Result += "_OBJC_$_CATEGORY_";
6776 Result += ClassName; Result += "_$_"; Result += CatName;
6777 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6778 Result += "{\n";
6779 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006780 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006781 Result += ",\n";
6782 if (InstanceMethods.size() > 0) {
6783 Result += "\t(const struct _method_list_t *)&";
6784 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6785 Result += ClassName; Result += "_$_"; Result += CatName;
6786 Result += ",\n";
6787 }
6788 else
6789 Result += "\t0,\n";
6790
6791 if (ClassMethods.size() > 0) {
6792 Result += "\t(const struct _method_list_t *)&";
6793 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6794 Result += ClassName; Result += "_$_"; Result += CatName;
6795 Result += ",\n";
6796 }
6797 else
6798 Result += "\t0,\n";
6799
6800 if (RefedProtocols.size() > 0) {
6801 Result += "\t(const struct _protocol_list_t *)&";
6802 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6803 Result += ClassName; Result += "_$_"; Result += CatName;
6804 Result += ",\n";
6805 }
6806 else
6807 Result += "\t0,\n";
6808
6809 if (ClassProperties.size() > 0) {
6810 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6811 Result += ClassName; Result += "_$_"; Result += CatName;
6812 Result += ",\n";
6813 }
6814 else
6815 Result += "\t0,\n";
6816
6817 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006818
6819 // Add static function to initialize the class pointer in the category structure.
6820 Result += "static void OBJC_CATEGORY_SETUP_$_";
6821 Result += ClassDecl->getNameAsString();
6822 Result += "_$_";
6823 Result += CatName;
6824 Result += "(void ) {\n";
6825 Result += "\t_OBJC_$_CATEGORY_";
6826 Result += ClassDecl->getNameAsString();
6827 Result += "_$_";
6828 Result += CatName;
6829 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6830 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006831}
6832
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006833static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6834 ASTContext *Context, std::string &Result,
6835 ArrayRef<ObjCMethodDecl *> Methods,
6836 StringRef VarName,
6837 StringRef ProtocolName) {
6838 if (Methods.size() == 0)
6839 return;
6840
6841 Result += "\nstatic const char *";
6842 Result += VarName; Result += ProtocolName;
6843 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6844 Result += "{\n";
6845 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6846 ObjCMethodDecl *MD = Methods[i];
6847 std::string MethodTypeString, QuoteMethodTypeString;
6848 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6849 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6850 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6851 if (i == e-1)
6852 Result += "\n};\n";
6853 else {
6854 Result += ",\n";
6855 }
6856 }
6857}
6858
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006859static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6860 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006861 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006862 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006863 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006864 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6865 // this is what happens:
6866 /**
6867 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6868 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6869 Class->getVisibility() == HiddenVisibility)
6870 Visibility shoud be: HiddenVisibility;
6871 else
6872 Visibility shoud be: DefaultVisibility;
6873 */
6874
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006875 Result += "\n";
6876 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6877 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006878 if (Context->getLangOpts().MicrosoftExt)
6879 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6880
6881 if (!Context->getLangOpts().MicrosoftExt ||
6882 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006883 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006884 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006885 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006886 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006887 if (Ivars[i]->isBitField())
6888 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6889 else
6890 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006891 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6892 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006893 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6894 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006895 if (Ivars[i]->isBitField()) {
6896 // skip over rest of the ivar bitfields.
6897 SKIP_BITFIELDS(i , e, Ivars);
6898 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006899 }
6900}
6901
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006902static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6903 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006904 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006905 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006906 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006907 if (OriginalIvars.size() > 0) {
6908 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6909 SmallVector<ObjCIvarDecl *, 8> Ivars;
6910 // strip off all but the first ivar bitfield from each group of ivars.
6911 // Such ivars in the ivar list table will be replaced by their grouping struct
6912 // 'ivar'.
6913 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6914 if (OriginalIvars[i]->isBitField()) {
6915 Ivars.push_back(OriginalIvars[i]);
6916 // skip over rest of the ivar bitfields.
6917 SKIP_BITFIELDS(i , e, OriginalIvars);
6918 }
6919 else
6920 Ivars.push_back(OriginalIvars[i]);
6921 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006922
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006923 Result += "\nstatic ";
6924 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6925 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006926 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006927 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6928 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6929 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6930 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6931 ObjCIvarDecl *IvarDecl = Ivars[i];
6932 if (i == 0)
6933 Result += "\t{{";
6934 else
6935 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006936 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006937 if (Ivars[i]->isBitField())
6938 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6939 else
6940 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006941 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006942
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006943 Result += "\"";
6944 if (Ivars[i]->isBitField())
6945 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6946 else
6947 Result += IvarDecl->getName();
6948 Result += "\", ";
6949
6950 QualType IVQT = IvarDecl->getType();
6951 if (IvarDecl->isBitField())
6952 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6953
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006954 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006955 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006956 IvarDecl);
6957 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6958 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6959
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006960 // FIXME. this alignment represents the host alignment and need be changed to
6961 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006962 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006963 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006964 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006965 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006966 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006967 if (i == e-1)
6968 Result += "}}\n";
6969 else
6970 Result += "},\n";
6971 }
6972 Result += "};\n";
6973 }
6974}
6975
Fariborz Jahanian11671902012-02-07 17:11:38 +00006976/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006977void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6978 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006979
Fariborz Jahanian11671902012-02-07 17:11:38 +00006980 // Do not synthesize the protocol more than once.
6981 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6982 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006983 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006984
6985 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6986 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006987 // Must write out all protocol definitions in current qualifier list,
6988 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006989 for (auto *I : PDecl->protocols())
6990 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006991
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006992 // Construct method lists.
6993 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6994 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006995 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006996 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6997 OptInstanceMethods.push_back(MD);
6998 } else {
6999 InstanceMethods.push_back(MD);
7000 }
7001 }
7002
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007003 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007004 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7005 OptClassMethods.push_back(MD);
7006 } else {
7007 ClassMethods.push_back(MD);
7008 }
7009 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007010 std::vector<ObjCMethodDecl *> AllMethods;
7011 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7012 AllMethods.push_back(InstanceMethods[i]);
7013 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7014 AllMethods.push_back(ClassMethods[i]);
7015 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7016 AllMethods.push_back(OptInstanceMethods[i]);
7017 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7018 AllMethods.push_back(OptClassMethods[i]);
7019
7020 Write__extendedMethodTypes_initializer(*this, Context, Result,
7021 AllMethods,
7022 "_OBJC_PROTOCOL_METHOD_TYPES_",
7023 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007024 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007025 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007026 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7027 "_OBJC_PROTOCOL_REFS_",
7028 PDecl->getNameAsString());
7029
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007030 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007031 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007032 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007033
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007034 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007035 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007036 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007037
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007038 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007039 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007040 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007041
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007043 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007044 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007045
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007046 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007047 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007048 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00007049 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007050 "_OBJC_PROTOCOL_PROPERTIES_",
7051 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00007052
Fariborz Jahanian48985802012-02-08 00:50:52 +00007053 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007054 Result += "\n";
7055 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007056 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007057 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007058 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007059 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7060 Result += "\t0,\n"; // id is; is null
7061 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007062 if (SuperProtocols.size() > 0) {
7063 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7064 Result += PDecl->getNameAsString(); Result += ",\n";
7065 }
7066 else
7067 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007068 if (InstanceMethods.size() > 0) {
7069 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7070 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007071 }
7072 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007073 Result += "\t0,\n";
7074
7075 if (ClassMethods.size() > 0) {
7076 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7077 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007078 }
7079 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007080 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007081
Fariborz Jahanian48985802012-02-08 00:50:52 +00007082 if (OptInstanceMethods.size() > 0) {
7083 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7084 Result += PDecl->getNameAsString(); Result += ",\n";
7085 }
7086 else
7087 Result += "\t0,\n";
7088
7089 if (OptClassMethods.size() > 0) {
7090 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7091 Result += PDecl->getNameAsString(); Result += ",\n";
7092 }
7093 else
7094 Result += "\t0,\n";
7095
7096 if (ProtocolProperties.size() > 0) {
7097 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7098 Result += PDecl->getNameAsString(); Result += ",\n";
7099 }
7100 else
7101 Result += "\t0,\n";
7102
7103 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7104 Result += "\t0,\n";
7105
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007106 if (AllMethods.size() > 0) {
7107 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7108 Result += PDecl->getNameAsString();
7109 Result += "\n};\n";
7110 }
7111 else
7112 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007113
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007114 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007115 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007116 Result += "struct _protocol_t *";
7117 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7118 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7119 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007120
Fariborz Jahanian11671902012-02-07 17:11:38 +00007121 // Mark this protocol as having been generated.
7122 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7123 llvm_unreachable("protocol already synthesized");
7124
7125}
7126
7127void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7128 const ObjCList<ObjCProtocolDecl> &Protocols,
7129 StringRef prefix, StringRef ClassName,
7130 std::string &Result) {
7131 if (Protocols.empty()) return;
7132
7133 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007134 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007135
7136 // Output the top lovel protocol meta-data for the class.
7137 /* struct _objc_protocol_list {
7138 struct _objc_protocol_list *next;
7139 int protocol_count;
7140 struct _objc_protocol *class_protocols[];
7141 }
7142 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007143 Result += "\n";
7144 if (LangOpts.MicrosoftExt)
7145 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7146 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007147 Result += "\tstruct _objc_protocol_list *next;\n";
7148 Result += "\tint protocol_count;\n";
7149 Result += "\tstruct _objc_protocol *class_protocols[";
7150 Result += utostr(Protocols.size());
7151 Result += "];\n} _OBJC_";
7152 Result += prefix;
7153 Result += "_PROTOCOLS_";
7154 Result += ClassName;
7155 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7156 "{\n\t0, ";
7157 Result += utostr(Protocols.size());
7158 Result += "\n";
7159
7160 Result += "\t,{&_OBJC_PROTOCOL_";
7161 Result += Protocols[0]->getNameAsString();
7162 Result += " \n";
7163
7164 for (unsigned i = 1; i != Protocols.size(); i++) {
7165 Result += "\t ,&_OBJC_PROTOCOL_";
7166 Result += Protocols[i]->getNameAsString();
7167 Result += "\n";
7168 }
7169 Result += "\t }\n};\n";
7170}
7171
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007172/// hasObjCExceptionAttribute - Return true if this class or any super
7173/// class has the __objc_exception__ attribute.
7174/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7175static bool hasObjCExceptionAttribute(ASTContext &Context,
7176 const ObjCInterfaceDecl *OID) {
7177 if (OID->hasAttr<ObjCExceptionAttr>())
7178 return true;
7179 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7180 return hasObjCExceptionAttribute(Context, Super);
7181 return false;
7182}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007183
Fariborz Jahanian11671902012-02-07 17:11:38 +00007184void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7185 std::string &Result) {
7186 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7187
7188 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007189 if (CDecl->isImplicitInterfaceDecl())
7190 assert(false &&
7191 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007192
Fariborz Jahanian45489622012-03-14 18:09:23 +00007193 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007194 SmallVector<ObjCIvarDecl *, 8> IVars;
7195
7196 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7197 IVD; IVD = IVD->getNextIvar()) {
7198 // Ignore unnamed bit-fields.
7199 if (!IVD->getDeclName())
7200 continue;
7201 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007202 }
7203
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007204 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007205 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007206 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007207
7208 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007209 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007210
7211 // If any of our property implementations have associated getters or
7212 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007213 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007214 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007215 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007216 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007217 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007218 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007219 if (!PD)
7220 continue;
7221 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007222 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007223 InstanceMethods.push_back(Getter);
7224 if (PD->isReadOnly())
7225 continue;
7226 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007227 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007228 InstanceMethods.push_back(Setter);
7229 }
7230
7231 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7232 "_OBJC_$_INSTANCE_METHODS_",
7233 IDecl->getNameAsString(), true);
7234
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007235 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007236
7237 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7238 "_OBJC_$_CLASS_METHODS_",
7239 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007240
7241 // Protocols referenced in class declaration?
7242 // Protocol's super protocol list
7243 std::vector<ObjCProtocolDecl *> RefedProtocols;
7244 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7245 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7246 E = Protocols.end();
7247 I != E; ++I) {
7248 RefedProtocols.push_back(*I);
7249 // Must write out all protocol definitions in current qualifier list,
7250 // and in their nested qualifiers before writing out current definition.
7251 RewriteObjCProtocolMetaData(*I, Result);
7252 }
7253
7254 Write_protocol_list_initializer(Context, Result,
7255 RefedProtocols,
7256 "_OBJC_CLASS_PROTOCOLS_$_",
7257 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007258
7259 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007260 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007261 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007262 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007263 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007264 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007265
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007266
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007267 // Data for initializing _class_ro_t metaclass meta-data
7268 uint32_t flags = CLS_META;
7269 std::string InstanceSize;
7270 std::string InstanceStart;
7271
7272
7273 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7274 if (classIsHidden)
7275 flags |= OBJC2_CLS_HIDDEN;
7276
7277 if (!CDecl->getSuperClass())
7278 // class is root
7279 flags |= CLS_ROOT;
7280 InstanceSize = "sizeof(struct _class_t)";
7281 InstanceStart = InstanceSize;
7282 Write__class_ro_t_initializer(Context, Result, flags,
7283 InstanceStart, InstanceSize,
7284 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007285 nullptr,
7286 nullptr,
7287 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007288 "_OBJC_METACLASS_RO_$_",
7289 CDecl->getNameAsString());
7290
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007291 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007292 flags = CLS;
7293 if (classIsHidden)
7294 flags |= OBJC2_CLS_HIDDEN;
7295
7296 if (hasObjCExceptionAttribute(*Context, CDecl))
7297 flags |= CLS_EXCEPTION;
7298
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007299 if (!CDecl->getSuperClass())
7300 // class is root
7301 flags |= CLS_ROOT;
7302
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007303 InstanceSize.clear();
7304 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007305 if (!ObjCSynthesizedStructs.count(CDecl)) {
7306 InstanceSize = "0";
7307 InstanceStart = "0";
7308 }
7309 else {
7310 InstanceSize = "sizeof(struct ";
7311 InstanceSize += CDecl->getNameAsString();
7312 InstanceSize += "_IMPL)";
7313
7314 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7315 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007316 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007317 }
7318 else
7319 InstanceStart = InstanceSize;
7320 }
7321 Write__class_ro_t_initializer(Context, Result, flags,
7322 InstanceStart, InstanceSize,
7323 InstanceMethods,
7324 RefedProtocols,
7325 IVars,
7326 ClassProperties,
7327 "_OBJC_CLASS_RO_$_",
7328 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007329
7330 Write_class_t(Context, Result,
7331 "OBJC_METACLASS_$_",
7332 CDecl, /*metaclass*/true);
7333
7334 Write_class_t(Context, Result,
7335 "OBJC_CLASS_$_",
7336 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007337
7338 if (ImplementationIsNonLazy(IDecl))
7339 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007340
Fariborz Jahanian11671902012-02-07 17:11:38 +00007341}
7342
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007343void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7344 int ClsDefCount = ClassImplementation.size();
7345 if (!ClsDefCount)
7346 return;
7347 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7348 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7349 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7350 for (int i = 0; i < ClsDefCount; i++) {
7351 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7352 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7353 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7354 Result += CDecl->getName(); Result += ",\n";
7355 }
7356 Result += "};\n";
7357}
7358
Fariborz Jahanian11671902012-02-07 17:11:38 +00007359void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7360 int ClsDefCount = ClassImplementation.size();
7361 int CatDefCount = CategoryImplementation.size();
7362
7363 // For each implemented class, write out all its meta data.
7364 for (int i = 0; i < ClsDefCount; i++)
7365 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7366
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007367 RewriteClassSetupInitHook(Result);
7368
Fariborz Jahanian11671902012-02-07 17:11:38 +00007369 // For each implemented category, write out all its meta data.
7370 for (int i = 0; i < CatDefCount; i++)
7371 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7372
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007373 RewriteCategorySetupInitHook(Result);
7374
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007375 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007376 if (LangOpts.MicrosoftExt)
7377 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007378 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7379 Result += llvm::utostr(ClsDefCount); Result += "]";
7380 Result +=
7381 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7382 "regular,no_dead_strip\")))= {\n";
7383 for (int i = 0; i < ClsDefCount; i++) {
7384 Result += "\t&OBJC_CLASS_$_";
7385 Result += ClassImplementation[i]->getNameAsString();
7386 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007387 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007388 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007389
7390 if (!DefinedNonLazyClasses.empty()) {
7391 if (LangOpts.MicrosoftExt)
7392 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7393 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7394 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7395 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7396 Result += ",\n";
7397 }
7398 Result += "};\n";
7399 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007400 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007401
7402 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007403 if (LangOpts.MicrosoftExt)
7404 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007405 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7406 Result += llvm::utostr(CatDefCount); Result += "]";
7407 Result +=
7408 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7409 "regular,no_dead_strip\")))= {\n";
7410 for (int i = 0; i < CatDefCount; i++) {
7411 Result += "\t&_OBJC_$_CATEGORY_";
7412 Result +=
7413 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7414 Result += "_$_";
7415 Result += CategoryImplementation[i]->getNameAsString();
7416 Result += ",\n";
7417 }
7418 Result += "};\n";
7419 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007420
7421 if (!DefinedNonLazyCategories.empty()) {
7422 if (LangOpts.MicrosoftExt)
7423 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7424 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7425 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7426 Result += "\t&_OBJC_$_CATEGORY_";
7427 Result +=
7428 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7429 Result += "_$_";
7430 Result += DefinedNonLazyCategories[i]->getNameAsString();
7431 Result += ",\n";
7432 }
7433 Result += "};\n";
7434 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007435}
7436
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007437void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7438 if (LangOpts.MicrosoftExt)
7439 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7440
7441 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7442 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007443 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007444}
7445
Fariborz Jahanian11671902012-02-07 17:11:38 +00007446/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7447/// implementation.
7448void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7449 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007450 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007451 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7452 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007453 ObjCCategoryDecl *CDecl
7454 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007455
7456 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007457 FullCategoryName += "_$_";
7458 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007459
7460 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007461 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007462
7463 // If any of our property implementations have associated getters or
7464 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007465 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007466 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007467 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007468 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007469 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007470 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007471 if (!PD)
7472 continue;
7473 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7474 InstanceMethods.push_back(Getter);
7475 if (PD->isReadOnly())
7476 continue;
7477 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7478 InstanceMethods.push_back(Setter);
7479 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007480
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007481 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7482 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7483 FullCategoryName, true);
7484
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007485 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007486
7487 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7488 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7489 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007490
7491 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007492 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007493 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7494 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007495 // Must write out all protocol definitions in current qualifier list,
7496 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007497 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007498
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007499 Write_protocol_list_initializer(Context, Result,
7500 RefedProtocols,
7501 "_OBJC_CATEGORY_PROTOCOLS_$_",
7502 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007503
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007504 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007505 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007506 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007507 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007508 "_OBJC_$_PROP_LIST_",
7509 FullCategoryName);
7510
7511 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007512 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007513 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007514 InstanceMethods,
7515 ClassMethods,
7516 RefedProtocols,
7517 ClassProperties);
7518
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007519 // Determine if this category is also "non-lazy".
7520 if (ImplementationIsNonLazy(IDecl))
7521 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007522
7523}
7524
7525void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7526 int CatDefCount = CategoryImplementation.size();
7527 if (!CatDefCount)
7528 return;
7529 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7530 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7531 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7532 for (int i = 0; i < CatDefCount; i++) {
7533 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7534 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7535 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7536 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7537 Result += ClassDecl->getName();
7538 Result += "_$_";
7539 Result += CatDecl->getName();
7540 Result += ",\n";
7541 }
7542 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007543}
7544
7545// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7546/// class methods.
7547template<typename MethodIterator>
7548void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7549 MethodIterator MethodEnd,
7550 bool IsInstanceMethod,
7551 StringRef prefix,
7552 StringRef ClassName,
7553 std::string &Result) {
7554 if (MethodBegin == MethodEnd) return;
7555
7556 if (!objc_impl_method) {
7557 /* struct _objc_method {
7558 SEL _cmd;
7559 char *method_types;
7560 void *_imp;
7561 }
7562 */
7563 Result += "\nstruct _objc_method {\n";
7564 Result += "\tSEL _cmd;\n";
7565 Result += "\tchar *method_types;\n";
7566 Result += "\tvoid *_imp;\n";
7567 Result += "};\n";
7568
7569 objc_impl_method = true;
7570 }
7571
7572 // Build _objc_method_list for class's methods if needed
7573
7574 /* struct {
7575 struct _objc_method_list *next_method;
7576 int method_count;
7577 struct _objc_method method_list[];
7578 }
7579 */
7580 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007581 Result += "\n";
7582 if (LangOpts.MicrosoftExt) {
7583 if (IsInstanceMethod)
7584 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7585 else
7586 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7587 }
7588 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007589 Result += "\tstruct _objc_method_list *next_method;\n";
7590 Result += "\tint method_count;\n";
7591 Result += "\tstruct _objc_method method_list[";
7592 Result += utostr(NumMethods);
7593 Result += "];\n} _OBJC_";
7594 Result += prefix;
7595 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7596 Result += "_METHODS_";
7597 Result += ClassName;
7598 Result += " __attribute__ ((used, section (\"__OBJC, __";
7599 Result += IsInstanceMethod ? "inst" : "cls";
7600 Result += "_meth\")))= ";
7601 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7602
7603 Result += "\t,{{(SEL)\"";
7604 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7605 std::string MethodTypeString;
7606 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7607 Result += "\", \"";
7608 Result += MethodTypeString;
7609 Result += "\", (void *)";
7610 Result += MethodInternalNames[*MethodBegin];
7611 Result += "}\n";
7612 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7613 Result += "\t ,{(SEL)\"";
7614 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7615 std::string MethodTypeString;
7616 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7617 Result += "\", \"";
7618 Result += MethodTypeString;
7619 Result += "\", (void *)";
7620 Result += MethodInternalNames[*MethodBegin];
7621 Result += "}\n";
7622 }
7623 Result += "\t }\n};\n";
7624}
7625
7626Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7627 SourceRange OldRange = IV->getSourceRange();
7628 Expr *BaseExpr = IV->getBase();
7629
7630 // Rewrite the base, but without actually doing replaces.
7631 {
7632 DisableReplaceStmtScope S(*this);
7633 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7634 IV->setBase(BaseExpr);
7635 }
7636
7637 ObjCIvarDecl *D = IV->getDecl();
7638
7639 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007640
Fariborz Jahanian11671902012-02-07 17:11:38 +00007641 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7642 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007643 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007644 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7645 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007646 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007647 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7648 clsDeclared);
7649 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7650
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007651 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007652 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007653 if (D->isBitField())
7654 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7655 else
7656 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007657
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007658 ReferencedIvars[clsDeclared].insert(D);
7659
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007660 // cast offset to "char *".
7661 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7662 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007663 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007664 BaseExpr);
7665 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7666 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007667 Context->UnsignedLongTy, nullptr,
7668 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007669 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7670 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007671 SourceLocation());
7672 BinaryOperator *addExpr =
7673 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7674 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007675 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007676 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007677 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7678 SourceLocation(),
7679 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007680 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007681 if (D->isBitField())
7682 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007683
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007684 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007685 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007686 RD = RD->getDefinition();
7687 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007688 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007689 ObjCContainerDecl *CDecl =
7690 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7691 // ivar in class extensions requires special treatment.
7692 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7693 CDecl = CatDecl->getClassInterface();
7694 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007695 RecName += "_IMPL";
7696 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7697 SourceLocation(), SourceLocation(),
7698 &Context->Idents.get(RecName.c_str()));
7699 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7700 unsigned UnsignedIntSize =
7701 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7702 Expr *Zero = IntegerLiteral::Create(*Context,
7703 llvm::APInt(UnsignedIntSize, 0),
7704 Context->UnsignedIntTy, SourceLocation());
7705 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7706 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7707 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007708 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007709 SourceLocation(),
7710 &Context->Idents.get(D->getNameAsString()),
Craig Topper8ae12032014-05-07 06:21:57 +00007711 IvarT, nullptr,
7712 /*BitWidth=*/nullptr,
7713 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007714 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7715 FD->getType(), VK_LValue,
7716 OK_Ordinary);
7717 IvarT = Context->getDecltypeType(ME, ME->getType());
7718 }
7719 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007720 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007721 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007722
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007723 castExpr = NoTypeInfoCStyleCastExpr(Context,
7724 castT,
7725 CK_BitCast,
7726 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007727
7728
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007729 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007730 VK_LValue, OK_Ordinary,
7731 SourceLocation());
7732 PE = new (Context) ParenExpr(OldRange.getBegin(),
7733 OldRange.getEnd(),
7734 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007735
7736 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007737 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007738 SourceLocation(),
7739 &Context->Idents.get(D->getNameAsString()),
Craig Topper8ae12032014-05-07 06:21:57 +00007740 D->getType(), nullptr,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007741 /*BitWidth=*/D->getBitWidth(),
Craig Topper8ae12032014-05-07 06:21:57 +00007742 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007743 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7744 FD->getType(), VK_LValue,
7745 OK_Ordinary);
7746 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007747
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007748 }
7749 else
7750 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007751 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007752
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007753 ReplaceStmtWithRange(IV, Replacement, OldRange);
7754 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007755}
Alp Toker0621cb22014-07-16 16:48:33 +00007756
7757#endif