blob: 3936727910a67d14eaf5eb9a30b465410c021312 [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,
Craig Topper4dd9b432014-08-17 23:49:53 +0000511 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000512
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 Blaikie6beb6aa2014-08-10 19:56:51 +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;
Craig Topperc6914d02014-08-25 04:15:02 +00004070 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004071 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4072 unsigned GroupNo = 0;
4073 if (IvarDecl->isBitField()) {
4074 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4075 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4076 continue;
4077 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004078 Result += "\n";
4079 if (LangOpts.MicrosoftExt)
4080 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004081 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004082 if (LangOpts.MicrosoftExt &&
4083 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004084 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4085 Result += "__declspec(dllimport) ";
4086
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004087 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004088 if (IvarDecl->isBitField()) {
4089 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4090 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4091 }
4092 else
4093 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004094 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004095 }
4096}
4097
Fariborz Jahanian11671902012-02-07 17:11:38 +00004098//===----------------------------------------------------------------------===//
4099// Meta Data Emission
4100//===----------------------------------------------------------------------===//
4101
4102
4103/// RewriteImplementations - This routine rewrites all method implementations
4104/// and emits meta-data.
4105
4106void RewriteModernObjC::RewriteImplementations() {
4107 int ClsDefCount = ClassImplementation.size();
4108 int CatDefCount = CategoryImplementation.size();
4109
4110 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004111 for (int i = 0; i < ClsDefCount; i++) {
4112 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4113 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4114 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004115 assert(false &&
4116 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004117 RewriteImplementationDecl(OIMP);
4118 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004119
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004120 for (int i = 0; i < CatDefCount; i++) {
4121 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4122 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4123 if (CDecl->isImplicitInterfaceDecl())
4124 assert(false &&
4125 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004126 RewriteImplementationDecl(CIMP);
4127 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004128}
4129
4130void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4131 const std::string &Name,
4132 ValueDecl *VD, bool def) {
4133 assert(BlockByRefDeclNo.count(VD) &&
4134 "RewriteByRefString: ByRef decl missing");
4135 if (def)
4136 ResultStr += "struct ";
4137 ResultStr += "__Block_byref_" + Name +
4138 "_" + utostr(BlockByRefDeclNo[VD]) ;
4139}
4140
4141static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4142 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4143 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4144 return false;
4145}
4146
4147std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4148 StringRef funcName,
4149 std::string Tag) {
4150 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004151 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004152 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004153 SourceLocation BlockLoc = CE->getExprLoc();
4154 std::string S;
4155 ConvertSourceLocationToLineDirective(BlockLoc, S);
4156
4157 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4158 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159
4160 BlockDecl *BD = CE->getBlockDecl();
4161
4162 if (isa<FunctionNoProtoType>(AFT)) {
4163 // No user-supplied arguments. Still need to pass in a pointer to the
4164 // block (to reference imported block decl refs).
4165 S += "(" + StructRef + " *__cself)";
4166 } else if (BD->param_empty()) {
4167 S += "(" + StructRef + " *__cself)";
4168 } else {
4169 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4170 assert(FT && "SynthesizeBlockFunc: No function proto");
4171 S += '(';
4172 // first add the implicit argument.
4173 S += StructRef + " *__cself, ";
4174 std::string ParamStr;
4175 for (BlockDecl::param_iterator AI = BD->param_begin(),
4176 E = BD->param_end(); AI != E; ++AI) {
4177 if (AI != BD->param_begin()) S += ", ";
4178 ParamStr = (*AI)->getNameAsString();
4179 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004180 (void)convertBlockPointerToFunctionPointer(QT);
4181 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004182 S += ParamStr;
4183 }
4184 if (FT->isVariadic()) {
4185 if (!BD->param_empty()) S += ", ";
4186 S += "...";
4187 }
4188 S += ')';
4189 }
4190 S += " {\n";
4191
4192 // Create local declarations to avoid rewriting all closure decl ref exprs.
4193 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004194 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004195 E = BlockByRefDecls.end(); I != E; ++I) {
4196 S += " ";
4197 std::string Name = (*I)->getNameAsString();
4198 std::string TypeString;
4199 RewriteByRefString(TypeString, Name, (*I));
4200 TypeString += " *";
4201 Name = TypeString + Name;
4202 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4203 }
4204 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004205 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004206 E = BlockByCopyDecls.end(); I != E; ++I) {
4207 S += " ";
4208 // Handle nested closure invocation. For example:
4209 //
4210 // void (^myImportedClosure)(void);
4211 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4212 //
4213 // void (^anotherClosure)(void);
4214 // anotherClosure = ^(void) {
4215 // myImportedClosure(); // import and invoke the closure
4216 // };
4217 //
4218 if (isTopLevelBlockPointerType((*I)->getType())) {
4219 RewriteBlockPointerTypeVariable(S, (*I));
4220 S += " = (";
4221 RewriteBlockPointerType(S, (*I)->getType());
4222 S += ")";
4223 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4224 }
4225 else {
4226 std::string Name = (*I)->getNameAsString();
4227 QualType QT = (*I)->getType();
4228 if (HasLocalVariableExternalStorage(*I))
4229 QT = Context->getPointerType(QT);
4230 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4231 S += Name + " = __cself->" +
4232 (*I)->getNameAsString() + "; // bound by copy\n";
4233 }
4234 }
4235 std::string RewrittenStr = RewrittenBlockExprs[CE];
4236 const char *cstr = RewrittenStr.c_str();
4237 while (*cstr++ != '{') ;
4238 S += cstr;
4239 S += "\n";
4240 return S;
4241}
4242
4243std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4244 StringRef funcName,
4245 std::string Tag) {
4246 std::string StructRef = "struct " + Tag;
4247 std::string S = "static void __";
4248
4249 S += funcName;
4250 S += "_block_copy_" + utostr(i);
4251 S += "(" + StructRef;
4252 S += "*dst, " + StructRef;
4253 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004254 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004255 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004256 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004257 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004258 S += VD->getNameAsString();
4259 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004260 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4261 else if (VD->getType()->isBlockPointerType())
4262 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4263 else
4264 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4265 }
4266 S += "}\n";
4267
4268 S += "\nstatic void __";
4269 S += funcName;
4270 S += "_block_dispose_" + utostr(i);
4271 S += "(" + StructRef;
4272 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004273 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004274 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004275 S += VD->getNameAsString();
4276 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004277 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4278 else if (VD->getType()->isBlockPointerType())
4279 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4280 else
4281 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4282 }
4283 S += "}\n";
4284 return S;
4285}
4286
4287std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4288 std::string Desc) {
4289 std::string S = "\nstruct " + Tag;
4290 std::string Constructor = " " + Tag;
4291
4292 S += " {\n struct __block_impl impl;\n";
4293 S += " struct " + Desc;
4294 S += "* Desc;\n";
4295
4296 Constructor += "(void *fp, "; // Invoke function pointer.
4297 Constructor += "struct " + Desc; // Descriptor pointer.
4298 Constructor += " *desc";
4299
4300 if (BlockDeclRefs.size()) {
4301 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004302 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004303 E = BlockByCopyDecls.end(); I != E; ++I) {
4304 S += " ";
4305 std::string FieldName = (*I)->getNameAsString();
4306 std::string ArgName = "_" + FieldName;
4307 // Handle nested closure invocation. For example:
4308 //
4309 // void (^myImportedBlock)(void);
4310 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4311 //
4312 // void (^anotherBlock)(void);
4313 // anotherBlock = ^(void) {
4314 // myImportedBlock(); // import and invoke the closure
4315 // };
4316 //
4317 if (isTopLevelBlockPointerType((*I)->getType())) {
4318 S += "struct __block_impl *";
4319 Constructor += ", void *" + ArgName;
4320 } else {
4321 QualType QT = (*I)->getType();
4322 if (HasLocalVariableExternalStorage(*I))
4323 QT = Context->getPointerType(QT);
4324 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4325 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4326 Constructor += ", " + ArgName;
4327 }
4328 S += FieldName + ";\n";
4329 }
4330 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004331 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004332 E = BlockByRefDecls.end(); I != E; ++I) {
4333 S += " ";
4334 std::string FieldName = (*I)->getNameAsString();
4335 std::string ArgName = "_" + FieldName;
4336 {
4337 std::string TypeString;
4338 RewriteByRefString(TypeString, FieldName, (*I));
4339 TypeString += " *";
4340 FieldName = TypeString + FieldName;
4341 ArgName = TypeString + ArgName;
4342 Constructor += ", " + ArgName;
4343 }
4344 S += FieldName + "; // by ref\n";
4345 }
4346 // Finish writing the constructor.
4347 Constructor += ", int flags=0)";
4348 // Initialize all "by copy" arguments.
4349 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004350 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004351 E = BlockByCopyDecls.end(); I != E; ++I) {
4352 std::string Name = (*I)->getNameAsString();
4353 if (firsTime) {
4354 Constructor += " : ";
4355 firsTime = false;
4356 }
4357 else
4358 Constructor += ", ";
4359 if (isTopLevelBlockPointerType((*I)->getType()))
4360 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4361 else
4362 Constructor += Name + "(_" + Name + ")";
4363 }
4364 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004365 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004366 E = BlockByRefDecls.end(); I != E; ++I) {
4367 std::string Name = (*I)->getNameAsString();
4368 if (firsTime) {
4369 Constructor += " : ";
4370 firsTime = false;
4371 }
4372 else
4373 Constructor += ", ";
4374 Constructor += Name + "(_" + Name + "->__forwarding)";
4375 }
4376
4377 Constructor += " {\n";
4378 if (GlobalVarDecl)
4379 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4380 else
4381 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4382 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4383
4384 Constructor += " Desc = desc;\n";
4385 } else {
4386 // Finish writing the constructor.
4387 Constructor += ", int flags=0) {\n";
4388 if (GlobalVarDecl)
4389 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4390 else
4391 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4392 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4393 Constructor += " Desc = desc;\n";
4394 }
4395 Constructor += " ";
4396 Constructor += "}\n";
4397 S += Constructor;
4398 S += "};\n";
4399 return S;
4400}
4401
4402std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4403 std::string ImplTag, int i,
4404 StringRef FunName,
4405 unsigned hasCopy) {
4406 std::string S = "\nstatic struct " + DescTag;
4407
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004408 S += " {\n size_t reserved;\n";
4409 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004410 if (hasCopy) {
4411 S += " void (*copy)(struct ";
4412 S += ImplTag; S += "*, struct ";
4413 S += ImplTag; S += "*);\n";
4414
4415 S += " void (*dispose)(struct ";
4416 S += ImplTag; S += "*);\n";
4417 }
4418 S += "} ";
4419
4420 S += DescTag + "_DATA = { 0, sizeof(struct ";
4421 S += ImplTag + ")";
4422 if (hasCopy) {
4423 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4424 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4425 }
4426 S += "};\n";
4427 return S;
4428}
4429
4430void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4431 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004432 bool RewriteSC = (GlobalVarDecl &&
4433 !Blocks.empty() &&
4434 GlobalVarDecl->getStorageClass() == SC_Static &&
4435 GlobalVarDecl->getType().getCVRQualifiers());
4436 if (RewriteSC) {
4437 std::string SC(" void __");
4438 SC += GlobalVarDecl->getNameAsString();
4439 SC += "() {}";
4440 InsertText(FunLocStart, SC);
4441 }
4442
4443 // Insert closures that were part of the function.
4444 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4445 CollectBlockDeclRefInfo(Blocks[i]);
4446 // Need to copy-in the inner copied-in variables not actually used in this
4447 // block.
4448 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004449 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004450 ValueDecl *VD = Exp->getDecl();
4451 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004452 if (!VD->hasAttr<BlocksAttr>()) {
4453 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4454 BlockByCopyDeclsPtrSet.insert(VD);
4455 BlockByCopyDecls.push_back(VD);
4456 }
4457 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004458 }
John McCall113bee02012-03-10 09:33:50 +00004459
4460 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004461 BlockByRefDeclsPtrSet.insert(VD);
4462 BlockByRefDecls.push_back(VD);
4463 }
John McCall113bee02012-03-10 09:33:50 +00004464
Fariborz Jahanian11671902012-02-07 17:11:38 +00004465 // imported objects in the inner blocks not used in the outer
4466 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004467 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004468 VD->getType()->isBlockPointerType())
4469 ImportedBlockDecls.insert(VD);
4470 }
4471
4472 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4473 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4474
4475 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4476
4477 InsertText(FunLocStart, CI);
4478
4479 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4480
4481 InsertText(FunLocStart, CF);
4482
4483 if (ImportedBlockDecls.size()) {
4484 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4485 InsertText(FunLocStart, HF);
4486 }
4487 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4488 ImportedBlockDecls.size() > 0);
4489 InsertText(FunLocStart, BD);
4490
4491 BlockDeclRefs.clear();
4492 BlockByRefDecls.clear();
4493 BlockByRefDeclsPtrSet.clear();
4494 BlockByCopyDecls.clear();
4495 BlockByCopyDeclsPtrSet.clear();
4496 ImportedBlockDecls.clear();
4497 }
4498 if (RewriteSC) {
4499 // Must insert any 'const/volatile/static here. Since it has been
4500 // removed as result of rewriting of block literals.
4501 std::string SC;
4502 if (GlobalVarDecl->getStorageClass() == SC_Static)
4503 SC = "static ";
4504 if (GlobalVarDecl->getType().isConstQualified())
4505 SC += "const ";
4506 if (GlobalVarDecl->getType().isVolatileQualified())
4507 SC += "volatile ";
4508 if (GlobalVarDecl->getType().isRestrictQualified())
4509 SC += "restrict ";
4510 InsertText(FunLocStart, SC);
4511 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004512 if (GlobalConstructionExp) {
4513 // extra fancy dance for global literal expression.
4514
4515 // Always the latest block expression on the block stack.
4516 std::string Tag = "__";
4517 Tag += FunName;
4518 Tag += "_block_impl_";
4519 Tag += utostr(Blocks.size()-1);
4520 std::string globalBuf = "static ";
4521 globalBuf += Tag; globalBuf += " ";
4522 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004523
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004524 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004525 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4526 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004527 globalBuf += constructorExprBuf.str();
4528 globalBuf += ";\n";
4529 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004530 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004531 }
4532
Fariborz Jahanian11671902012-02-07 17:11:38 +00004533 Blocks.clear();
4534 InnerDeclRefsCount.clear();
4535 InnerDeclRefs.clear();
4536 RewrittenBlockExprs.clear();
4537}
4538
4539void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004540 SourceLocation FunLocStart =
4541 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4542 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004543 StringRef FuncName = FD->getName();
4544
4545 SynthesizeBlockLiterals(FunLocStart, FuncName);
4546}
4547
4548static void BuildUniqueMethodName(std::string &Name,
4549 ObjCMethodDecl *MD) {
4550 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4551 Name = IFace->getName();
4552 Name += "__" + MD->getSelector().getAsString();
4553 // Convert colons to underscores.
4554 std::string::size_type loc = 0;
4555 while ((loc = Name.find(":", loc)) != std::string::npos)
4556 Name.replace(loc, 1, "_");
4557}
4558
4559void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4560 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4561 //SourceLocation FunLocStart = MD->getLocStart();
4562 SourceLocation FunLocStart = MD->getLocStart();
4563 std::string FuncName;
4564 BuildUniqueMethodName(FuncName, MD);
4565 SynthesizeBlockLiterals(FunLocStart, FuncName);
4566}
4567
4568void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4569 for (Stmt::child_range CI = S->children(); CI; ++CI)
4570 if (*CI) {
4571 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4572 GetBlockDeclRefExprs(CBE->getBody());
4573 else
4574 GetBlockDeclRefExprs(*CI);
4575 }
4576 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004577 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4578 if (DRE->refersToEnclosingLocal()) {
4579 // FIXME: Handle enums.
4580 if (!isa<FunctionDecl>(DRE->getDecl()))
4581 BlockDeclRefs.push_back(DRE);
4582 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4583 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004584 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004585 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004586
4587 return;
4588}
4589
Craig Topper5603df42013-07-05 19:34:19 +00004590void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4591 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004592 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004593 for (Stmt::child_range CI = S->children(); CI; ++CI)
4594 if (*CI) {
4595 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4596 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4597 GetInnerBlockDeclRefExprs(CBE->getBody(),
4598 InnerBlockDeclRefs,
4599 InnerContexts);
4600 }
4601 else
4602 GetInnerBlockDeclRefExprs(*CI,
4603 InnerBlockDeclRefs,
4604 InnerContexts);
4605
4606 }
4607 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004608 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4609 if (DRE->refersToEnclosingLocal()) {
4610 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4611 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4612 InnerBlockDeclRefs.push_back(DRE);
4613 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4614 if (Var->isFunctionOrMethodVarDecl())
4615 ImportedLocalExternalDecls.insert(Var);
4616 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004617 }
4618
4619 return;
4620}
4621
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004622/// convertObjCTypeToCStyleType - This routine converts such objc types
4623/// as qualified objects, and blocks to their closest c/c++ types that
4624/// it can. It returns true if input type was modified.
4625bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4626 QualType oldT = T;
4627 convertBlockPointerToFunctionPointer(T);
4628 if (T->isFunctionPointerType()) {
4629 QualType PointeeTy;
4630 if (const PointerType* PT = T->getAs<PointerType>()) {
4631 PointeeTy = PT->getPointeeType();
4632 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4633 T = convertFunctionTypeOfBlocks(FT);
4634 T = Context->getPointerType(T);
4635 }
4636 }
4637 }
4638
4639 convertToUnqualifiedObjCType(T);
4640 return T != oldT;
4641}
4642
Fariborz Jahanian11671902012-02-07 17:11:38 +00004643/// convertFunctionTypeOfBlocks - This routine converts a function type
4644/// whose result type may be a block pointer or whose argument type(s)
4645/// might be block pointers to an equivalent function type replacing
4646/// all block pointers to function pointers.
4647QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4648 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4649 // FTP will be null for closures that don't take arguments.
4650 // Generate a funky cast.
4651 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004652 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004653 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004654
4655 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004656 for (auto &I : FTP->param_types()) {
4657 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004658 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004659 if (convertObjCTypeToCStyleType(t))
4660 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004661 ArgTypes.push_back(t);
4662 }
4663 }
4664 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004665 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004666 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004667 else FuncType = QualType(FT, 0);
4668 return FuncType;
4669}
4670
4671Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4672 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004673 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674
4675 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4676 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004677 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4678 CPT = MExpr->getType()->getAs<BlockPointerType>();
4679 }
4680 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4681 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4682 }
4683 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4684 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4685 else if (const ConditionalOperator *CEXPR =
4686 dyn_cast<ConditionalOperator>(BlockExp)) {
4687 Expr *LHSExp = CEXPR->getLHS();
4688 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4689 Expr *RHSExp = CEXPR->getRHS();
4690 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4691 Expr *CONDExp = CEXPR->getCond();
4692 ConditionalOperator *CondExpr =
4693 new (Context) ConditionalOperator(CONDExp,
4694 SourceLocation(), cast<Expr>(LHSStmt),
4695 SourceLocation(), cast<Expr>(RHSStmt),
4696 Exp->getType(), VK_RValue, OK_Ordinary);
4697 return CondExpr;
4698 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4699 CPT = IRE->getType()->getAs<BlockPointerType>();
4700 } else if (const PseudoObjectExpr *POE
4701 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4702 CPT = POE->getType()->castAs<BlockPointerType>();
4703 } else {
4704 assert(1 && "RewriteBlockClass: Bad type");
4705 }
4706 assert(CPT && "RewriteBlockClass: Bad type");
4707 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4708 assert(FT && "RewriteBlockClass: Bad type");
4709 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4710 // FTP will be null for closures that don't take arguments.
4711
4712 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4713 SourceLocation(), SourceLocation(),
4714 &Context->Idents.get("__block_impl"));
4715 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4716
4717 // Generate a funky cast.
4718 SmallVector<QualType, 8> ArgTypes;
4719
4720 // Push the block argument type.
4721 ArgTypes.push_back(PtrBlock);
4722 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004723 for (auto &I : FTP->param_types()) {
4724 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004725 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4726 if (!convertBlockPointerToFunctionPointer(t))
4727 convertToUnqualifiedObjCType(t);
4728 ArgTypes.push_back(t);
4729 }
4730 }
4731 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004732 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004733
4734 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4735
4736 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4737 CK_BitCast,
4738 const_cast<Expr*>(BlockExp));
4739 // Don't forget the parens to enforce the proper binding.
4740 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4741 BlkCast);
4742 //PE->dump();
4743
Craig Topper8ae12032014-05-07 06:21:57 +00004744 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004745 SourceLocation(),
4746 &Context->Idents.get("FuncPtr"),
Craig Topper8ae12032014-05-07 06:21:57 +00004747 Context->VoidPtrTy, nullptr,
4748 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004749 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004750 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4751 FD->getType(), VK_LValue,
4752 OK_Ordinary);
4753
4754
4755 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4756 CK_BitCast, ME);
4757 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4758
4759 SmallVector<Expr*, 8> BlkExprs;
4760 // Add the implicit argument.
4761 BlkExprs.push_back(BlkCast);
4762 // Add the user arguments.
4763 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4764 E = Exp->arg_end(); I != E; ++I) {
4765 BlkExprs.push_back(*I);
4766 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004767 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004768 Exp->getType(), VK_RValue,
4769 SourceLocation());
4770 return CE;
4771}
4772
4773// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004774// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004775// For example:
4776//
4777// int main() {
4778// __block Foo *f;
4779// __block int i;
4780//
4781// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004782// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004783// i = 77;
4784// };
4785//}
John McCall113bee02012-03-10 09:33:50 +00004786Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004787 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4788 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004789 ValueDecl *VD = DeclRefExp->getDecl();
4790 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Craig Topper8ae12032014-05-07 06:21:57 +00004791
4792 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004793 SourceLocation(),
4794 &Context->Idents.get("__forwarding"),
Craig Topper8ae12032014-05-07 06:21:57 +00004795 Context->VoidPtrTy, nullptr,
4796 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004797 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004798 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4799 FD, SourceLocation(),
4800 FD->getType(), VK_LValue,
4801 OK_Ordinary);
4802
4803 StringRef Name = VD->getName();
Craig Topper8ae12032014-05-07 06:21:57 +00004804 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004805 &Context->Idents.get(Name),
Craig Topper8ae12032014-05-07 06:21:57 +00004806 Context->VoidPtrTy, nullptr,
4807 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004808 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004809 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4810 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4811
4812
4813
4814 // Need parens to enforce precedence.
4815 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4816 DeclRefExp->getExprLoc(),
4817 ME);
4818 ReplaceStmt(DeclRefExp, PE);
4819 return PE;
4820}
4821
4822// Rewrites the imported local variable V with external storage
4823// (static, extern, etc.) as *V
4824//
4825Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4826 ValueDecl *VD = DRE->getDecl();
4827 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4828 if (!ImportedLocalExternalDecls.count(Var))
4829 return DRE;
4830 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4831 VK_LValue, OK_Ordinary,
4832 DRE->getLocation());
4833 // Need parens to enforce precedence.
4834 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4835 Exp);
4836 ReplaceStmt(DRE, PE);
4837 return PE;
4838}
4839
4840void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4841 SourceLocation LocStart = CE->getLParenLoc();
4842 SourceLocation LocEnd = CE->getRParenLoc();
4843
4844 // Need to avoid trying to rewrite synthesized casts.
4845 if (LocStart.isInvalid())
4846 return;
4847 // Need to avoid trying to rewrite casts contained in macros.
4848 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4849 return;
4850
4851 const char *startBuf = SM->getCharacterData(LocStart);
4852 const char *endBuf = SM->getCharacterData(LocEnd);
4853 QualType QT = CE->getType();
4854 const Type* TypePtr = QT->getAs<Type>();
4855 if (isa<TypeOfExprType>(TypePtr)) {
4856 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4857 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4858 std::string TypeAsString = "(";
4859 RewriteBlockPointerType(TypeAsString, QT);
4860 TypeAsString += ")";
4861 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4862 return;
4863 }
4864 // advance the location to startArgList.
4865 const char *argPtr = startBuf;
4866
4867 while (*argPtr++ && (argPtr < endBuf)) {
4868 switch (*argPtr) {
4869 case '^':
4870 // Replace the '^' with '*'.
4871 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4872 ReplaceText(LocStart, 1, "*");
4873 break;
4874 }
4875 }
4876 return;
4877}
4878
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004879void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4880 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004881 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4882 CastKind != CK_AnyPointerToBlockPointerCast)
4883 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004884
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004885 QualType QT = IC->getType();
4886 (void)convertBlockPointerToFunctionPointer(QT);
4887 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4888 std::string Str = "(";
4889 Str += TypeString;
4890 Str += ")";
4891 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4892
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004893 return;
4894}
4895
Fariborz Jahanian11671902012-02-07 17:11:38 +00004896void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4897 SourceLocation DeclLoc = FD->getLocation();
4898 unsigned parenCount = 0;
4899
4900 // We have 1 or more arguments that have closure pointers.
4901 const char *startBuf = SM->getCharacterData(DeclLoc);
4902 const char *startArgList = strchr(startBuf, '(');
4903
4904 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4905
4906 parenCount++;
4907 // advance the location to startArgList.
4908 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4909 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4910
4911 const char *argPtr = startArgList;
4912
4913 while (*argPtr++ && parenCount) {
4914 switch (*argPtr) {
4915 case '^':
4916 // Replace the '^' with '*'.
4917 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4918 ReplaceText(DeclLoc, 1, "*");
4919 break;
4920 case '(':
4921 parenCount++;
4922 break;
4923 case ')':
4924 parenCount--;
4925 break;
4926 }
4927 }
4928 return;
4929}
4930
4931bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4932 const FunctionProtoType *FTP;
4933 const PointerType *PT = QT->getAs<PointerType>();
4934 if (PT) {
4935 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4936 } else {
4937 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4938 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4939 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4940 }
4941 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004942 for (const auto &I : FTP->param_types())
4943 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004944 return true;
4945 }
4946 return false;
4947}
4948
4949bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4950 const FunctionProtoType *FTP;
4951 const PointerType *PT = QT->getAs<PointerType>();
4952 if (PT) {
4953 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4954 } else {
4955 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4956 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4957 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4958 }
4959 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004960 for (const auto &I : FTP->param_types()) {
4961 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004962 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004963 if (I->isObjCObjectPointerType() &&
4964 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004965 return true;
4966 }
4967
4968 }
4969 return false;
4970}
4971
4972void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4973 const char *&RParen) {
4974 const char *argPtr = strchr(Name, '(');
4975 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4976
4977 LParen = argPtr; // output the start.
4978 argPtr++; // skip past the left paren.
4979 unsigned parenCount = 1;
4980
4981 while (*argPtr && parenCount) {
4982 switch (*argPtr) {
4983 case '(': parenCount++; break;
4984 case ')': parenCount--; break;
4985 default: break;
4986 }
4987 if (parenCount) argPtr++;
4988 }
4989 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4990 RParen = argPtr; // output the end
4991}
4992
4993void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4995 RewriteBlockPointerFunctionArgs(FD);
4996 return;
4997 }
4998 // Handle Variables and Typedefs.
4999 SourceLocation DeclLoc = ND->getLocation();
5000 QualType DeclT;
5001 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5002 DeclT = VD->getType();
5003 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5004 DeclT = TDD->getUnderlyingType();
5005 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5006 DeclT = FD->getType();
5007 else
5008 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5009
5010 const char *startBuf = SM->getCharacterData(DeclLoc);
5011 const char *endBuf = startBuf;
5012 // scan backward (from the decl location) for the end of the previous decl.
5013 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5014 startBuf--;
5015 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5016 std::string buf;
5017 unsigned OrigLength=0;
5018 // *startBuf != '^' if we are dealing with a pointer to function that
5019 // may take block argument types (which will be handled below).
5020 if (*startBuf == '^') {
5021 // Replace the '^' with '*', computing a negative offset.
5022 buf = '*';
5023 startBuf++;
5024 OrigLength++;
5025 }
5026 while (*startBuf != ')') {
5027 buf += *startBuf;
5028 startBuf++;
5029 OrigLength++;
5030 }
5031 buf += ')';
5032 OrigLength++;
5033
5034 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5035 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5036 // Replace the '^' with '*' for arguments.
5037 // Replace id<P> with id/*<>*/
5038 DeclLoc = ND->getLocation();
5039 startBuf = SM->getCharacterData(DeclLoc);
5040 const char *argListBegin, *argListEnd;
5041 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5042 while (argListBegin < argListEnd) {
5043 if (*argListBegin == '^')
5044 buf += '*';
5045 else if (*argListBegin == '<') {
5046 buf += "/*";
5047 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005048 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005049 while (*argListBegin != '>') {
5050 buf += *argListBegin++;
5051 OrigLength++;
5052 }
5053 buf += *argListBegin;
5054 buf += "*/";
5055 }
5056 else
5057 buf += *argListBegin;
5058 argListBegin++;
5059 OrigLength++;
5060 }
5061 buf += ')';
5062 OrigLength++;
5063 }
5064 ReplaceText(Start, OrigLength, buf);
5065
5066 return;
5067}
5068
5069
5070/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5071/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5072/// struct Block_byref_id_object *src) {
5073/// _Block_object_assign (&_dest->object, _src->object,
5074/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5075/// [|BLOCK_FIELD_IS_WEAK]) // object
5076/// _Block_object_assign(&_dest->object, _src->object,
5077/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5078/// [|BLOCK_FIELD_IS_WEAK]) // block
5079/// }
5080/// And:
5081/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5082/// _Block_object_dispose(_src->object,
5083/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5084/// [|BLOCK_FIELD_IS_WEAK]) // object
5085/// _Block_object_dispose(_src->object,
5086/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5087/// [|BLOCK_FIELD_IS_WEAK]) // block
5088/// }
5089
5090std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5091 int flag) {
5092 std::string S;
5093 if (CopyDestroyCache.count(flag))
5094 return S;
5095 CopyDestroyCache.insert(flag);
5096 S = "static void __Block_byref_id_object_copy_";
5097 S += utostr(flag);
5098 S += "(void *dst, void *src) {\n";
5099
5100 // offset into the object pointer is computed as:
5101 // void * + void* + int + int + void* + void *
5102 unsigned IntSize =
5103 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5104 unsigned VoidPtrSize =
5105 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5106
5107 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5108 S += " _Block_object_assign((char*)dst + ";
5109 S += utostr(offset);
5110 S += ", *(void * *) ((char*)src + ";
5111 S += utostr(offset);
5112 S += "), ";
5113 S += utostr(flag);
5114 S += ");\n}\n";
5115
5116 S += "static void __Block_byref_id_object_dispose_";
5117 S += utostr(flag);
5118 S += "(void *src) {\n";
5119 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5120 S += utostr(offset);
5121 S += "), ";
5122 S += utostr(flag);
5123 S += ");\n}\n";
5124 return S;
5125}
5126
5127/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5128/// the declaration into:
5129/// struct __Block_byref_ND {
5130/// void *__isa; // NULL for everything except __weak pointers
5131/// struct __Block_byref_ND *__forwarding;
5132/// int32_t __flags;
5133/// int32_t __size;
5134/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5135/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5136/// typex ND;
5137/// };
5138///
5139/// It then replaces declaration of ND variable with:
5140/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5141/// __size=sizeof(struct __Block_byref_ND),
5142/// ND=initializer-if-any};
5143///
5144///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005145void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5146 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005147 int flag = 0;
5148 int isa = 0;
5149 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5150 if (DeclLoc.isInvalid())
5151 // If type location is missing, it is because of missing type (a warning).
5152 // Use variable's location which is good for this case.
5153 DeclLoc = ND->getLocation();
5154 const char *startBuf = SM->getCharacterData(DeclLoc);
5155 SourceLocation X = ND->getLocEnd();
5156 X = SM->getExpansionLoc(X);
5157 const char *endBuf = SM->getCharacterData(X);
5158 std::string Name(ND->getNameAsString());
5159 std::string ByrefType;
5160 RewriteByRefString(ByrefType, Name, ND, true);
5161 ByrefType += " {\n";
5162 ByrefType += " void *__isa;\n";
5163 RewriteByRefString(ByrefType, Name, ND);
5164 ByrefType += " *__forwarding;\n";
5165 ByrefType += " int __flags;\n";
5166 ByrefType += " int __size;\n";
5167 // Add void *__Block_byref_id_object_copy;
5168 // void *__Block_byref_id_object_dispose; if needed.
5169 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005170 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005171 if (HasCopyAndDispose) {
5172 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5173 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5174 }
5175
5176 QualType T = Ty;
5177 (void)convertBlockPointerToFunctionPointer(T);
5178 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5179
5180 ByrefType += " " + Name + ";\n";
5181 ByrefType += "};\n";
5182 // Insert this type in global scope. It is needed by helper function.
5183 SourceLocation FunLocStart;
5184 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005185 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005186 else {
5187 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5188 FunLocStart = CurMethodDef->getLocStart();
5189 }
5190 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005191
Fariborz Jahanian11671902012-02-07 17:11:38 +00005192 if (Ty.isObjCGCWeak()) {
5193 flag |= BLOCK_FIELD_IS_WEAK;
5194 isa = 1;
5195 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005196 if (HasCopyAndDispose) {
5197 flag = BLOCK_BYREF_CALLER;
5198 QualType Ty = ND->getType();
5199 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5200 if (Ty->isBlockPointerType())
5201 flag |= BLOCK_FIELD_IS_BLOCK;
5202 else
5203 flag |= BLOCK_FIELD_IS_OBJECT;
5204 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5205 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005206 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005207 }
5208
5209 // struct __Block_byref_ND ND =
5210 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5211 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005212 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005213 // FIXME. rewriter does not support __block c++ objects which
5214 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005215 if (hasInit)
5216 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5217 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5218 if (CXXDecl && CXXDecl->isDefaultConstructor())
5219 hasInit = false;
5220 }
5221
Fariborz Jahanian11671902012-02-07 17:11:38 +00005222 unsigned flags = 0;
5223 if (HasCopyAndDispose)
5224 flags |= BLOCK_HAS_COPY_DISPOSE;
5225 Name = ND->getNameAsString();
5226 ByrefType.clear();
5227 RewriteByRefString(ByrefType, Name, ND);
5228 std::string ForwardingCastType("(");
5229 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005230 ByrefType += " " + Name + " = {(void*)";
5231 ByrefType += utostr(isa);
5232 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5233 ByrefType += utostr(flags);
5234 ByrefType += ", ";
5235 ByrefType += "sizeof(";
5236 RewriteByRefString(ByrefType, Name, ND);
5237 ByrefType += ")";
5238 if (HasCopyAndDispose) {
5239 ByrefType += ", __Block_byref_id_object_copy_";
5240 ByrefType += utostr(flag);
5241 ByrefType += ", __Block_byref_id_object_dispose_";
5242 ByrefType += utostr(flag);
5243 }
5244
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005245 if (!firstDecl) {
5246 // In multiple __block declarations, and for all but 1st declaration,
5247 // find location of the separating comma. This would be start location
5248 // where new text is to be inserted.
5249 DeclLoc = ND->getLocation();
5250 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5251 const char *commaBuf = startDeclBuf;
5252 while (*commaBuf != ',')
5253 commaBuf--;
5254 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5255 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5256 startBuf = commaBuf;
5257 }
5258
Fariborz Jahanian11671902012-02-07 17:11:38 +00005259 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005260 ByrefType += "};\n";
5261 unsigned nameSize = Name.size();
5262 // for block or function pointer declaration. Name is aleady
5263 // part of the declaration.
5264 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5265 nameSize = 1;
5266 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5267 }
5268 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005269 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005270 SourceLocation startLoc;
5271 Expr *E = ND->getInit();
5272 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5273 startLoc = ECE->getLParenLoc();
5274 else
5275 startLoc = E->getLocStart();
5276 startLoc = SM->getExpansionLoc(startLoc);
5277 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005278 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005279
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005280 const char separator = lastDecl ? ';' : ',';
5281 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5282 const char *separatorBuf = strchr(startInitializerBuf, separator);
5283 assert((*separatorBuf == separator) &&
5284 "RewriteByRefVar: can't find ';' or ','");
5285 SourceLocation separatorLoc =
5286 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5287
5288 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005289 }
5290 return;
5291}
5292
5293void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5294 // Add initializers for any closure decl refs.
5295 GetBlockDeclRefExprs(Exp->getBody());
5296 if (BlockDeclRefs.size()) {
5297 // Unique all "by copy" declarations.
5298 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005299 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005300 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5301 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5302 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5303 }
5304 }
5305 // Unique all "by ref" declarations.
5306 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005307 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005308 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5309 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5310 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5311 }
5312 }
5313 // Find any imported blocks...they will need special attention.
5314 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005315 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005316 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5317 BlockDeclRefs[i]->getType()->isBlockPointerType())
5318 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5319 }
5320}
5321
5322FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5323 IdentifierInfo *ID = &Context->Idents.get(name);
5324 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5325 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005326 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005327 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005328}
5329
5330Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005331 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005332
Fariborz Jahanian11671902012-02-07 17:11:38 +00005333 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005334
Fariborz Jahanian11671902012-02-07 17:11:38 +00005335 Blocks.push_back(Exp);
5336
5337 CollectBlockDeclRefInfo(Exp);
5338
5339 // Add inner imported variables now used in current block.
5340 int countOfInnerDecls = 0;
5341 if (!InnerBlockDeclRefs.empty()) {
5342 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005343 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005344 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005345 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005346 // We need to save the copied-in variables in nested
5347 // blocks because it is needed at the end for some of the API generations.
5348 // See SynthesizeBlockLiterals routine.
5349 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5350 BlockDeclRefs.push_back(Exp);
5351 BlockByCopyDeclsPtrSet.insert(VD);
5352 BlockByCopyDecls.push_back(VD);
5353 }
John McCall113bee02012-03-10 09:33:50 +00005354 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005355 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5356 BlockDeclRefs.push_back(Exp);
5357 BlockByRefDeclsPtrSet.insert(VD);
5358 BlockByRefDecls.push_back(VD);
5359 }
5360 }
5361 // Find any imported blocks...they will need special attention.
5362 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005363 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005364 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5365 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5366 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5367 }
5368 InnerDeclRefsCount.push_back(countOfInnerDecls);
5369
5370 std::string FuncName;
5371
5372 if (CurFunctionDef)
5373 FuncName = CurFunctionDef->getNameAsString();
5374 else if (CurMethodDef)
5375 BuildUniqueMethodName(FuncName, CurMethodDef);
5376 else if (GlobalVarDecl)
5377 FuncName = std::string(GlobalVarDecl->getNameAsString());
5378
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005379 bool GlobalBlockExpr =
5380 block->getDeclContext()->getRedeclContext()->isFileContext();
5381
5382 if (GlobalBlockExpr && !GlobalVarDecl) {
5383 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5384 GlobalBlockExpr = false;
5385 }
5386
Fariborz Jahanian11671902012-02-07 17:11:38 +00005387 std::string BlockNumber = utostr(Blocks.size()-1);
5388
Fariborz Jahanian11671902012-02-07 17:11:38 +00005389 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5390
5391 // Get a pointer to the function type so we can cast appropriately.
5392 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5393 QualType FType = Context->getPointerType(BFT);
5394
5395 FunctionDecl *FD;
5396 Expr *NewRep;
5397
Benjamin Kramer60509af2013-09-09 14:48:42 +00005398 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005399 std::string Tag;
5400
5401 if (GlobalBlockExpr)
5402 Tag = "__global_";
5403 else
5404 Tag = "__";
5405 Tag += FuncName + "_block_impl_" + BlockNumber;
5406
Fariborz Jahanian11671902012-02-07 17:11:38 +00005407 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005408 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005409 SourceLocation());
5410
5411 SmallVector<Expr*, 4> InitExprs;
5412
5413 // Initialize the block function.
5414 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005415 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5416 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005417 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5418 CK_BitCast, Arg);
5419 InitExprs.push_back(castExpr);
5420
5421 // Initialize the block descriptor.
5422 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5423
5424 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5425 SourceLocation(), SourceLocation(),
5426 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005427 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005428 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005429 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005430 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005431 Context->VoidPtrTy,
5432 VK_LValue,
5433 SourceLocation()),
5434 UO_AddrOf,
5435 Context->getPointerType(Context->VoidPtrTy),
5436 VK_RValue, OK_Ordinary,
5437 SourceLocation());
5438 InitExprs.push_back(DescRefExpr);
5439
5440 // Add initializers for any closure decl refs.
5441 if (BlockDeclRefs.size()) {
5442 Expr *Exp;
5443 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005444 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005445 E = BlockByCopyDecls.end(); I != E; ++I) {
5446 if (isObjCType((*I)->getType())) {
5447 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5448 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005449 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5450 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005451 if (HasLocalVariableExternalStorage(*I)) {
5452 QualType QT = (*I)->getType();
5453 QT = Context->getPointerType(QT);
5454 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5455 OK_Ordinary, SourceLocation());
5456 }
5457 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5458 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005459 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5460 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005461 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5462 CK_BitCast, Arg);
5463 } else {
5464 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005465 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5466 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005467 if (HasLocalVariableExternalStorage(*I)) {
5468 QualType QT = (*I)->getType();
5469 QT = Context->getPointerType(QT);
5470 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5471 OK_Ordinary, SourceLocation());
5472 }
5473
5474 }
5475 InitExprs.push_back(Exp);
5476 }
5477 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005478 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005479 E = BlockByRefDecls.end(); I != E; ++I) {
5480 ValueDecl *ND = (*I);
5481 std::string Name(ND->getNameAsString());
5482 std::string RecName;
5483 RewriteByRefString(RecName, Name, ND, true);
5484 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5485 + sizeof("struct"));
5486 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5487 SourceLocation(), SourceLocation(),
5488 II);
5489 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5490 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5491
5492 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005493 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005494 SourceLocation());
5495 bool isNestedCapturedVar = false;
5496 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005497 for (const auto &CI : block->captures()) {
5498 const VarDecl *variable = CI.getVariable();
5499 if (variable == ND && CI.isNested()) {
5500 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005501 "SynthBlockInitExpr - captured block variable is not byref");
5502 isNestedCapturedVar = true;
5503 break;
5504 }
5505 }
5506 // captured nested byref variable has its address passed. Do not take
5507 // its address again.
5508 if (!isNestedCapturedVar)
5509 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5510 Context->getPointerType(Exp->getType()),
5511 VK_RValue, OK_Ordinary, SourceLocation());
5512 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5513 InitExprs.push_back(Exp);
5514 }
5515 }
5516 if (ImportedBlockDecls.size()) {
5517 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5518 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5519 unsigned IntSize =
5520 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5521 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5522 Context->IntTy, SourceLocation());
5523 InitExprs.push_back(FlagExp);
5524 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005525 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005526 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005527
5528 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005529 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005530 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5531 GlobalConstructionExp = NewRep;
5532 NewRep = DRE;
5533 }
5534
Fariborz Jahanian11671902012-02-07 17:11:38 +00005535 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5536 Context->getPointerType(NewRep->getType()),
5537 VK_RValue, OK_Ordinary, SourceLocation());
5538 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5539 NewRep);
5540 BlockDeclRefs.clear();
5541 BlockByRefDecls.clear();
5542 BlockByRefDeclsPtrSet.clear();
5543 BlockByCopyDecls.clear();
5544 BlockByCopyDeclsPtrSet.clear();
5545 ImportedBlockDecls.clear();
5546 return NewRep;
5547}
5548
5549bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5550 if (const ObjCForCollectionStmt * CS =
5551 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5552 return CS->getElement() == DS;
5553 return false;
5554}
5555
5556//===----------------------------------------------------------------------===//
5557// Function Body / Expression rewriting
5558//===----------------------------------------------------------------------===//
5559
5560Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5561 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5562 isa<DoStmt>(S) || isa<ForStmt>(S))
5563 Stmts.push_back(S);
5564 else if (isa<ObjCForCollectionStmt>(S)) {
5565 Stmts.push_back(S);
5566 ObjCBcLabelNo.push_back(++BcLabelCount);
5567 }
5568
5569 // Pseudo-object operations and ivar references need special
5570 // treatment because we're going to recursively rewrite them.
5571 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5572 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5573 return RewritePropertyOrImplicitSetter(PseudoOp);
5574 } else {
5575 return RewritePropertyOrImplicitGetter(PseudoOp);
5576 }
5577 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5578 return RewriteObjCIvarRefExpr(IvarRefExpr);
5579 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005580 else if (isa<OpaqueValueExpr>(S))
5581 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005582
5583 SourceRange OrigStmtRange = S->getSourceRange();
5584
5585 // Perform a bottom up rewrite of all children.
5586 for (Stmt::child_range CI = S->children(); CI; ++CI)
5587 if (*CI) {
5588 Stmt *childStmt = (*CI);
5589 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5590 if (newStmt) {
5591 *CI = newStmt;
5592 }
5593 }
5594
5595 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005596 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005597 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5598 InnerContexts.insert(BE->getBlockDecl());
5599 ImportedLocalExternalDecls.clear();
5600 GetInnerBlockDeclRefExprs(BE->getBody(),
5601 InnerBlockDeclRefs, InnerContexts);
5602 // Rewrite the block body in place.
5603 Stmt *SaveCurrentBody = CurrentBody;
5604 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005605 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005606 // block literal on rhs of a property-dot-sytax assignment
5607 // must be replaced by its synthesize ast so getRewrittenText
5608 // works as expected. In this case, what actually ends up on RHS
5609 // is the blockTranscribed which is the helper function for the
5610 // block literal; as in: self.c = ^() {[ace ARR];};
5611 bool saveDisableReplaceStmt = DisableReplaceStmt;
5612 DisableReplaceStmt = false;
5613 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5614 DisableReplaceStmt = saveDisableReplaceStmt;
5615 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005616 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005617 ImportedLocalExternalDecls.clear();
5618 // Now we snarf the rewritten text and stash it away for later use.
5619 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5620 RewrittenBlockExprs[BE] = Str;
5621
5622 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5623
5624 //blockTranscribed->dump();
5625 ReplaceStmt(S, blockTranscribed);
5626 return blockTranscribed;
5627 }
5628 // Handle specific things.
5629 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5630 return RewriteAtEncode(AtEncode);
5631
5632 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5633 return RewriteAtSelector(AtSelector);
5634
5635 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5636 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005637
5638 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5639 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005640
Patrick Beard0caa3942012-04-19 00:25:12 +00005641 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5642 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005643
5644 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5645 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005646
5647 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5648 dyn_cast<ObjCDictionaryLiteral>(S))
5649 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005650
5651 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5652#if 0
5653 // Before we rewrite it, put the original message expression in a comment.
5654 SourceLocation startLoc = MessExpr->getLocStart();
5655 SourceLocation endLoc = MessExpr->getLocEnd();
5656
5657 const char *startBuf = SM->getCharacterData(startLoc);
5658 const char *endBuf = SM->getCharacterData(endLoc);
5659
5660 std::string messString;
5661 messString += "// ";
5662 messString.append(startBuf, endBuf-startBuf+1);
5663 messString += "\n";
5664
5665 // FIXME: Missing definition of
5666 // InsertText(clang::SourceLocation, char const*, unsigned int).
5667 // InsertText(startLoc, messString.c_str(), messString.size());
5668 // Tried this, but it didn't work either...
5669 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5670#endif
5671 return RewriteMessageExpr(MessExpr);
5672 }
5673
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005674 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5675 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5676 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5677 }
5678
Fariborz Jahanian11671902012-02-07 17:11:38 +00005679 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5680 return RewriteObjCTryStmt(StmtTry);
5681
5682 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5683 return RewriteObjCSynchronizedStmt(StmtTry);
5684
5685 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5686 return RewriteObjCThrowStmt(StmtThrow);
5687
5688 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5689 return RewriteObjCProtocolExpr(ProtocolExp);
5690
5691 if (ObjCForCollectionStmt *StmtForCollection =
5692 dyn_cast<ObjCForCollectionStmt>(S))
5693 return RewriteObjCForCollectionStmt(StmtForCollection,
5694 OrigStmtRange.getEnd());
5695 if (BreakStmt *StmtBreakStmt =
5696 dyn_cast<BreakStmt>(S))
5697 return RewriteBreakStmt(StmtBreakStmt);
5698 if (ContinueStmt *StmtContinueStmt =
5699 dyn_cast<ContinueStmt>(S))
5700 return RewriteContinueStmt(StmtContinueStmt);
5701
5702 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5703 // and cast exprs.
5704 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5705 // FIXME: What we're doing here is modifying the type-specifier that
5706 // precedes the first Decl. In the future the DeclGroup should have
5707 // a separate type-specifier that we can rewrite.
5708 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5709 // the context of an ObjCForCollectionStmt. For example:
5710 // NSArray *someArray;
5711 // for (id <FooProtocol> index in someArray) ;
5712 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5713 // and it depends on the original text locations/positions.
5714 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5715 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5716
5717 // Blocks rewrite rules.
5718 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5719 DI != DE; ++DI) {
5720 Decl *SD = *DI;
5721 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5722 if (isTopLevelBlockPointerType(ND->getType()))
5723 RewriteBlockPointerDecl(ND);
5724 else if (ND->getType()->isFunctionPointerType())
5725 CheckFunctionPointerDecl(ND->getType(), ND);
5726 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5727 if (VD->hasAttr<BlocksAttr>()) {
5728 static unsigned uniqueByrefDeclCount = 0;
5729 assert(!BlockByRefDeclNo.count(ND) &&
5730 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5731 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005732 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005733 }
5734 else
5735 RewriteTypeOfDecl(VD);
5736 }
5737 }
5738 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5739 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5740 RewriteBlockPointerDecl(TD);
5741 else if (TD->getUnderlyingType()->isFunctionPointerType())
5742 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5743 }
5744 }
5745 }
5746
5747 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5748 RewriteObjCQualifiedInterfaceTypes(CE);
5749
5750 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5751 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5752 assert(!Stmts.empty() && "Statement stack is empty");
5753 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5754 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5755 && "Statement stack mismatch");
5756 Stmts.pop_back();
5757 }
5758 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005759 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5760 ValueDecl *VD = DRE->getDecl();
5761 if (VD->hasAttr<BlocksAttr>())
5762 return RewriteBlockDeclRefExpr(DRE);
5763 if (HasLocalVariableExternalStorage(VD))
5764 return RewriteLocalVariableExternalStorage(DRE);
5765 }
5766
5767 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5768 if (CE->getCallee()->getType()->isBlockPointerType()) {
5769 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5770 ReplaceStmt(S, BlockCall);
5771 return BlockCall;
5772 }
5773 }
5774 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5775 RewriteCastExpr(CE);
5776 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005777 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5778 RewriteImplicitCastObjCExpr(ICE);
5779 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005780#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005781
Fariborz Jahanian11671902012-02-07 17:11:38 +00005782 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5783 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5784 ICE->getSubExpr(),
5785 SourceLocation());
5786 // Get the new text.
5787 std::string SStr;
5788 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005789 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005790 const std::string &Str = Buf.str();
5791
5792 printf("CAST = %s\n", &Str[0]);
5793 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5794 delete S;
5795 return Replacement;
5796 }
5797#endif
5798 // Return this stmt unmodified.
5799 return S;
5800}
5801
5802void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005803 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005804 if (isTopLevelBlockPointerType(FD->getType()))
5805 RewriteBlockPointerDecl(FD);
5806 if (FD->getType()->isObjCQualifiedIdType() ||
5807 FD->getType()->isObjCQualifiedInterfaceType())
5808 RewriteObjCQualifiedInterfaceTypes(FD);
5809 }
5810}
5811
5812/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5813/// main file of the input.
5814void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5815 switch (D->getKind()) {
5816 case Decl::Function: {
5817 FunctionDecl *FD = cast<FunctionDecl>(D);
5818 if (FD->isOverloadedOperator())
5819 return;
5820
5821 // Since function prototypes don't have ParmDecl's, we check the function
5822 // prototype. This enables us to rewrite function declarations and
5823 // definitions using the same code.
5824 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5825
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005826 if (!FD->isThisDeclarationADefinition())
5827 break;
5828
Fariborz Jahanian11671902012-02-07 17:11:38 +00005829 // FIXME: If this should support Obj-C++, support CXXTryStmt
5830 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5831 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005832 CurrentBody = Body;
5833 Body =
5834 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5835 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005836 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005837 if (PropParentMap) {
5838 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005839 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005840 }
5841 // This synthesizes and inserts the block "impl" struct, invoke function,
5842 // and any copy/dispose helper functions.
5843 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005844 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005845 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005846 }
5847 break;
5848 }
5849 case Decl::ObjCMethod: {
5850 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5851 if (CompoundStmt *Body = MD->getCompoundBody()) {
5852 CurMethodDef = MD;
5853 CurrentBody = Body;
5854 Body =
5855 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5856 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005857 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005858 if (PropParentMap) {
5859 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005860 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005861 }
5862 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005863 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005864 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005865 }
5866 break;
5867 }
5868 case Decl::ObjCImplementation: {
5869 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5870 ClassImplementation.push_back(CI);
5871 break;
5872 }
5873 case Decl::ObjCCategoryImpl: {
5874 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5875 CategoryImplementation.push_back(CI);
5876 break;
5877 }
5878 case Decl::Var: {
5879 VarDecl *VD = cast<VarDecl>(D);
5880 RewriteObjCQualifiedInterfaceTypes(VD);
5881 if (isTopLevelBlockPointerType(VD->getType()))
5882 RewriteBlockPointerDecl(VD);
5883 else if (VD->getType()->isFunctionPointerType()) {
5884 CheckFunctionPointerDecl(VD->getType(), VD);
5885 if (VD->getInit()) {
5886 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5887 RewriteCastExpr(CE);
5888 }
5889 }
5890 } else if (VD->getType()->isRecordType()) {
5891 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5892 if (RD->isCompleteDefinition())
5893 RewriteRecordBody(RD);
5894 }
5895 if (VD->getInit()) {
5896 GlobalVarDecl = VD;
5897 CurrentBody = VD->getInit();
5898 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005899 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005900 if (PropParentMap) {
5901 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005902 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005903 }
5904 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005905 GlobalVarDecl = nullptr;
5906
Fariborz Jahanian11671902012-02-07 17:11:38 +00005907 // This is needed for blocks.
5908 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5909 RewriteCastExpr(CE);
5910 }
5911 }
5912 break;
5913 }
5914 case Decl::TypeAlias:
5915 case Decl::Typedef: {
5916 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5917 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5918 RewriteBlockPointerDecl(TD);
5919 else if (TD->getUnderlyingType()->isFunctionPointerType())
5920 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005921 else
5922 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005923 }
5924 break;
5925 }
5926 case Decl::CXXRecord:
5927 case Decl::Record: {
5928 RecordDecl *RD = cast<RecordDecl>(D);
5929 if (RD->isCompleteDefinition())
5930 RewriteRecordBody(RD);
5931 break;
5932 }
5933 default:
5934 break;
5935 }
5936 // Nothing yet.
5937}
5938
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005939/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5940/// protocol reference symbols in the for of:
5941/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5942static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5943 ObjCProtocolDecl *PDecl,
5944 std::string &Result) {
5945 // Also output .objc_protorefs$B section and its meta-data.
5946 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005947 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005948 Result += "struct _protocol_t *";
5949 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5950 Result += PDecl->getNameAsString();
5951 Result += " = &";
5952 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5953 Result += ";\n";
5954}
5955
Fariborz Jahanian11671902012-02-07 17:11:38 +00005956void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5957 if (Diags.hasErrorOccurred())
5958 return;
5959
5960 RewriteInclude();
5961
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005962 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005963 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005964 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005965 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005966 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5967 HandleTopLevelSingleDecl(FDecl);
5968 }
5969
Fariborz Jahanian11671902012-02-07 17:11:38 +00005970 // Here's a great place to add any extra declarations that may be needed.
5971 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005972 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5973 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5974 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005975 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005976
5977 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005978
5979 if (ClassImplementation.size() || CategoryImplementation.size())
5980 RewriteImplementations();
5981
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005982 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5983 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5984 // Write struct declaration for the class matching its ivar declarations.
5985 // Note that for modern abi, this is postponed until the end of TU
5986 // because class extensions and the implementation might declare their own
5987 // private ivars.
5988 RewriteInterfaceDecl(CDecl);
5989 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005990
Fariborz Jahanian11671902012-02-07 17:11:38 +00005991 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5992 // we are done.
5993 if (const RewriteBuffer *RewriteBuf =
5994 Rewrite.getRewriteBufferFor(MainFileID)) {
5995 //printf("Changed:\n");
5996 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5997 } else {
5998 llvm::errs() << "No changes\n";
5999 }
6000
6001 if (ClassImplementation.size() || CategoryImplementation.size() ||
6002 ProtocolExprDecls.size()) {
6003 // Rewrite Objective-c meta data*
6004 std::string ResultStr;
6005 RewriteMetaDataIntoBuffer(ResultStr);
6006 // Emit metadata.
6007 *OutFile << ResultStr;
6008 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006009 // Emit ImageInfo;
6010 {
6011 std::string ResultStr;
6012 WriteImageInfo(ResultStr);
6013 *OutFile << ResultStr;
6014 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006015 OutFile->flush();
6016}
6017
6018void RewriteModernObjC::Initialize(ASTContext &context) {
6019 InitializeCommon(context);
6020
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006021 Preamble += "#ifndef __OBJC2__\n";
6022 Preamble += "#define __OBJC2__\n";
6023 Preamble += "#endif\n";
6024
Fariborz Jahanian11671902012-02-07 17:11:38 +00006025 // declaring objc_selector outside the parameter list removes a silly
6026 // scope related warning...
6027 if (IsHeader)
6028 Preamble = "#pragma once\n";
6029 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006030 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6031 Preamble += "\n\tstruct objc_object *superClass; ";
6032 // Add a constructor for creating temporary objects.
6033 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6034 Preamble += ": object(o), superClass(s) {} ";
6035 Preamble += "\n};\n";
6036
Fariborz Jahanian11671902012-02-07 17:11:38 +00006037 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006038 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006039 // These are currently generated.
6040 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006041 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006042 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006043 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6044 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006045 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006046 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006047 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6048 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006049 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006050
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006051 // These need be generated for performance. Currently they are not,
6052 // using API calls instead.
6053 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6054 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6055 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6056
Fariborz Jahanian11671902012-02-07 17:11:38 +00006057 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006058 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6059 Preamble += "typedef struct objc_object Protocol;\n";
6060 Preamble += "#define _REWRITER_typedef_Protocol\n";
6061 Preamble += "#endif\n";
6062 if (LangOpts.MicrosoftExt) {
6063 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6064 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006065 }
6066 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006067 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006068
6069 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6070 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6071 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6072 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6073 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6074
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006075 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006076 Preamble += "(const char *);\n";
6077 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6078 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006079 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006080 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006081 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006083 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6084 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006085 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006086 Preamble += "#ifdef _WIN64\n";
6087 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6088 Preamble += "#else\n";
6089 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6090 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006091 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6092 Preamble += "struct __objcFastEnumerationState {\n\t";
6093 Preamble += "unsigned long state;\n\t";
6094 Preamble += "void **itemsPtr;\n\t";
6095 Preamble += "unsigned long *mutationsPtr;\n\t";
6096 Preamble += "unsigned long extra[5];\n};\n";
6097 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6098 Preamble += "#define __FASTENUMERATIONSTATE\n";
6099 Preamble += "#endif\n";
6100 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6101 Preamble += "struct __NSConstantStringImpl {\n";
6102 Preamble += " int *isa;\n";
6103 Preamble += " int flags;\n";
6104 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00006105 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006106 Preamble += " long long length;\n";
6107 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006108 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006109 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006110 Preamble += "};\n";
6111 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6112 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6113 Preamble += "#else\n";
6114 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6115 Preamble += "#endif\n";
6116 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6117 Preamble += "#endif\n";
6118 // Blocks preamble.
6119 Preamble += "#ifndef BLOCK_IMPL\n";
6120 Preamble += "#define BLOCK_IMPL\n";
6121 Preamble += "struct __block_impl {\n";
6122 Preamble += " void *isa;\n";
6123 Preamble += " int Flags;\n";
6124 Preamble += " int Reserved;\n";
6125 Preamble += " void *FuncPtr;\n";
6126 Preamble += "};\n";
6127 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6128 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6129 Preamble += "extern \"C\" __declspec(dllexport) "
6130 "void _Block_object_assign(void *, const void *, const int);\n";
6131 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6132 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6133 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6134 Preamble += "#else\n";
6135 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6136 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6137 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6138 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6139 Preamble += "#endif\n";
6140 Preamble += "#endif\n";
6141 if (LangOpts.MicrosoftExt) {
6142 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6143 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6144 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6145 Preamble += "#define __attribute__(X)\n";
6146 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006147 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006148 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006149 Preamble += "#endif\n";
6150 Preamble += "#ifndef __block\n";
6151 Preamble += "#define __block\n";
6152 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006153 }
6154 else {
6155 Preamble += "#define __block\n";
6156 Preamble += "#define __weak\n";
6157 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006158
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006159 // Declarations required for modern objective-c array and dictionary literals.
6160 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006161 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006162 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006163 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006164 Preamble += "\tva_list marker;\n";
6165 Preamble += "\tva_start(marker, count);\n";
6166 Preamble += "\tarr = new void *[count];\n";
6167 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6168 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6169 Preamble += "\tva_end( marker );\n";
6170 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006171 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006172 Preamble += "\tdelete[] arr;\n";
6173 Preamble += " }\n";
6174 Preamble += "};\n";
6175
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006176 // Declaration required for implementation of @autoreleasepool statement.
6177 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6178 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6179 Preamble += "struct __AtAutoreleasePool {\n";
6180 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6181 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6182 Preamble += " void * atautoreleasepoolobj;\n";
6183 Preamble += "};\n";
6184
Fariborz Jahanian11671902012-02-07 17:11:38 +00006185 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6186 // as this avoids warning in any 64bit/32bit compilation model.
6187 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6188}
6189
6190/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6191/// ivar offset.
6192void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6193 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006194 Result += "__OFFSETOFIVAR__(struct ";
6195 Result += ivar->getContainingInterface()->getNameAsString();
6196 if (LangOpts.MicrosoftExt)
6197 Result += "_IMPL";
6198 Result += ", ";
6199 if (ivar->isBitField())
6200 ObjCIvarBitfieldGroupDecl(ivar, Result);
6201 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006203 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006204}
6205
6206/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6207/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006208/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006209/// char *attributes;
6210/// }
6211
6212/// struct _prop_list_t {
6213/// uint32_t entsize; // sizeof(struct _prop_t)
6214/// uint32_t count_of_properties;
6215/// struct _prop_t prop_list[count_of_properties];
6216/// }
6217
6218/// struct _protocol_t;
6219
6220/// struct _protocol_list_t {
6221/// long protocol_count; // Note, this is 32/64 bit
6222/// struct _protocol_t * protocol_list[protocol_count];
6223/// }
6224
6225/// struct _objc_method {
6226/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006227/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006228/// char *_imp;
6229/// }
6230
6231/// struct _method_list_t {
6232/// uint32_t entsize; // sizeof(struct _objc_method)
6233/// uint32_t method_count;
6234/// struct _objc_method method_list[method_count];
6235/// }
6236
6237/// struct _protocol_t {
6238/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006239/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006240/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006241/// const struct method_list_t *instance_methods;
6242/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006243/// const struct method_list_t *optionalInstanceMethods;
6244/// const struct method_list_t *optionalClassMethods;
6245/// const struct _prop_list_t * properties;
6246/// const uint32_t size; // sizeof(struct _protocol_t)
6247/// const uint32_t flags; // = 0
6248/// const char ** extendedMethodTypes;
6249/// }
6250
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006251/// struct _ivar_t {
6252/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006253/// const char *name;
6254/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006255/// uint32_t alignment;
6256/// uint32_t size;
6257/// }
6258
6259/// struct _ivar_list_t {
6260/// uint32 entsize; // sizeof(struct _ivar_t)
6261/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006262/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006263/// }
6264
6265/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006266/// uint32_t flags;
6267/// uint32_t instanceStart;
6268/// uint32_t instanceSize;
6269/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006270/// const uint8_t *ivarLayout;
6271/// const char *name;
6272/// const struct _method_list_t *baseMethods;
6273/// const struct _protocol_list_t *baseProtocols;
6274/// const struct _ivar_list_t *ivars;
6275/// const uint8_t *weakIvarLayout;
6276/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006277/// }
6278
6279/// struct _class_t {
6280/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006281/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006282/// void *cache;
6283/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006284/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006285/// }
6286
6287/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006288/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006289/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006290/// const struct _method_list_t *instance_methods;
6291/// const struct _method_list_t *class_methods;
6292/// const struct _protocol_list_t *protocols;
6293/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006294/// }
6295
6296/// MessageRefTy - LLVM for:
6297/// struct _message_ref_t {
6298/// IMP messenger;
6299/// SEL name;
6300/// };
6301
6302/// SuperMessageRefTy - LLVM for:
6303/// struct _super_message_ref_t {
6304/// SUPER_IMP messenger;
6305/// SEL name;
6306/// };
6307
Fariborz Jahanian45489622012-03-14 18:09:23 +00006308static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006309 static bool meta_data_declared = false;
6310 if (meta_data_declared)
6311 return;
6312
6313 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006314 Result += "\tconst char *name;\n";
6315 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006316 Result += "};\n";
6317
6318 Result += "\nstruct _protocol_t;\n";
6319
Fariborz Jahanian11671902012-02-07 17:11:38 +00006320 Result += "\nstruct _objc_method {\n";
6321 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006322 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006323 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006324 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006325
6326 Result += "\nstruct _protocol_t {\n";
6327 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006328 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006329 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006330 Result += "\tconst struct method_list_t *instance_methods;\n";
6331 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006332 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6333 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6334 Result += "\tconst struct _prop_list_t * properties;\n";
6335 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6336 Result += "\tconst unsigned int flags; // = 0\n";
6337 Result += "\tconst char ** extendedMethodTypes;\n";
6338 Result += "};\n";
6339
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006340 Result += "\nstruct _ivar_t {\n";
6341 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006342 Result += "\tconst char *name;\n";
6343 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006344 Result += "\tunsigned int alignment;\n";
6345 Result += "\tunsigned int size;\n";
6346 Result += "};\n";
6347
6348 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006349 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006350 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006351 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006352 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6353 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006354 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006355 Result += "\tconst unsigned char *ivarLayout;\n";
6356 Result += "\tconst char *name;\n";
6357 Result += "\tconst struct _method_list_t *baseMethods;\n";
6358 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6359 Result += "\tconst struct _ivar_list_t *ivars;\n";
6360 Result += "\tconst unsigned char *weakIvarLayout;\n";
6361 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006362 Result += "};\n";
6363
6364 Result += "\nstruct _class_t {\n";
6365 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006366 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006367 Result += "\tvoid *cache;\n";
6368 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006369 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006370 Result += "};\n";
6371
6372 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006373 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006374 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006375 Result += "\tconst struct _method_list_t *instance_methods;\n";
6376 Result += "\tconst struct _method_list_t *class_methods;\n";
6377 Result += "\tconst struct _protocol_list_t *protocols;\n";
6378 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006379 Result += "};\n";
6380
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006381 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006382 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006383 meta_data_declared = true;
6384}
6385
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006386static void Write_protocol_list_t_TypeDecl(std::string &Result,
6387 long super_protocol_count) {
6388 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6389 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6390 Result += "\tstruct _protocol_t *super_protocols[";
6391 Result += utostr(super_protocol_count); Result += "];\n";
6392 Result += "}";
6393}
6394
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006395static void Write_method_list_t_TypeDecl(std::string &Result,
6396 unsigned int method_count) {
6397 Result += "struct /*_method_list_t*/"; Result += " {\n";
6398 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6399 Result += "\tunsigned int method_count;\n";
6400 Result += "\tstruct _objc_method method_list[";
6401 Result += utostr(method_count); Result += "];\n";
6402 Result += "}";
6403}
6404
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006405static void Write__prop_list_t_TypeDecl(std::string &Result,
6406 unsigned int property_count) {
6407 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6408 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6409 Result += "\tunsigned int count_of_properties;\n";
6410 Result += "\tstruct _prop_t prop_list[";
6411 Result += utostr(property_count); Result += "];\n";
6412 Result += "}";
6413}
6414
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006415static void Write__ivar_list_t_TypeDecl(std::string &Result,
6416 unsigned int ivar_count) {
6417 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6418 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6419 Result += "\tunsigned int count;\n";
6420 Result += "\tstruct _ivar_t ivar_list[";
6421 Result += utostr(ivar_count); Result += "];\n";
6422 Result += "}";
6423}
6424
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006425static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6426 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6427 StringRef VarName,
6428 StringRef ProtocolName) {
6429 if (SuperProtocols.size() > 0) {
6430 Result += "\nstatic ";
6431 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6432 Result += " "; Result += VarName;
6433 Result += ProtocolName;
6434 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6435 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6436 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6437 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6438 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6439 Result += SuperPD->getNameAsString();
6440 if (i == e-1)
6441 Result += "\n};\n";
6442 else
6443 Result += ",\n";
6444 }
6445 }
6446}
6447
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006448static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6449 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006450 ArrayRef<ObjCMethodDecl *> Methods,
6451 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006452 StringRef TopLevelDeclName,
6453 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006454 if (Methods.size() > 0) {
6455 Result += "\nstatic ";
6456 Write_method_list_t_TypeDecl(Result, Methods.size());
6457 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006458 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006459 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6460 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6461 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6462 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6463 ObjCMethodDecl *MD = Methods[i];
6464 if (i == 0)
6465 Result += "\t{{(struct objc_selector *)\"";
6466 else
6467 Result += "\t{(struct objc_selector *)\"";
6468 Result += (MD)->getSelector().getAsString(); Result += "\"";
6469 Result += ", ";
6470 std::string MethodTypeString;
6471 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6472 Result += "\""; Result += MethodTypeString; Result += "\"";
6473 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006474 if (!MethodImpl)
6475 Result += "0";
6476 else {
6477 Result += "(void *)";
6478 Result += RewriteObj.MethodInternalNames[MD];
6479 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006480 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006481 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006482 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006483 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006484 }
6485 Result += "};\n";
6486 }
6487}
6488
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006489static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006490 ASTContext *Context, std::string &Result,
6491 ArrayRef<ObjCPropertyDecl *> Properties,
6492 const Decl *Container,
6493 StringRef VarName,
6494 StringRef ProtocolName) {
6495 if (Properties.size() > 0) {
6496 Result += "\nstatic ";
6497 Write__prop_list_t_TypeDecl(Result, Properties.size());
6498 Result += " "; Result += VarName;
6499 Result += ProtocolName;
6500 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6501 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6502 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6503 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6504 ObjCPropertyDecl *PropDecl = Properties[i];
6505 if (i == 0)
6506 Result += "\t{{\"";
6507 else
6508 Result += "\t{\"";
6509 Result += PropDecl->getName(); Result += "\",";
6510 std::string PropertyTypeString, QuotePropertyTypeString;
6511 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6512 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6513 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6514 if (i == e-1)
6515 Result += "}}\n";
6516 else
6517 Result += "},\n";
6518 }
6519 Result += "};\n";
6520 }
6521}
6522
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006523// Metadata flags
6524enum MetaDataDlags {
6525 CLS = 0x0,
6526 CLS_META = 0x1,
6527 CLS_ROOT = 0x2,
6528 OBJC2_CLS_HIDDEN = 0x10,
6529 CLS_EXCEPTION = 0x20,
6530
6531 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6532 CLS_HAS_IVAR_RELEASER = 0x40,
6533 /// class was compiled with -fobjc-arr
6534 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6535};
6536
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006537static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6538 unsigned int flags,
6539 const std::string &InstanceStart,
6540 const std::string &InstanceSize,
6541 ArrayRef<ObjCMethodDecl *>baseMethods,
6542 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6543 ArrayRef<ObjCIvarDecl *>ivars,
6544 ArrayRef<ObjCPropertyDecl *>Properties,
6545 StringRef VarName,
6546 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006547 Result += "\nstatic struct _class_ro_t ";
6548 Result += VarName; Result += ClassName;
6549 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6550 Result += "\t";
6551 Result += llvm::utostr(flags); Result += ", ";
6552 Result += InstanceStart; Result += ", ";
6553 Result += InstanceSize; Result += ", \n";
6554 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006555 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6556 if (Triple.getArch() == llvm::Triple::x86_64)
6557 // uint32_t const reserved; // only when building for 64bit targets
6558 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006559 // const uint8_t * const ivarLayout;
6560 Result += "0, \n\t";
6561 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006562 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006563 if (baseMethods.size() > 0) {
6564 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006565 if (metaclass)
6566 Result += "_OBJC_$_CLASS_METHODS_";
6567 else
6568 Result += "_OBJC_$_INSTANCE_METHODS_";
6569 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006570 Result += ",\n\t";
6571 }
6572 else
6573 Result += "0, \n\t";
6574
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006575 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006576 Result += "(const struct _objc_protocol_list *)&";
6577 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6578 Result += ",\n\t";
6579 }
6580 else
6581 Result += "0, \n\t";
6582
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006583 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006584 Result += "(const struct _ivar_list_t *)&";
6585 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6586 Result += ",\n\t";
6587 }
6588 else
6589 Result += "0, \n\t";
6590
6591 // weakIvarLayout
6592 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006593 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006594 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006595 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006596 Result += ",\n";
6597 }
6598 else
6599 Result += "0, \n";
6600
6601 Result += "};\n";
6602}
6603
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006604static void Write_class_t(ASTContext *Context, std::string &Result,
6605 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006606 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6607 bool rootClass = (!CDecl->getSuperClass());
6608 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006609
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006610 if (!rootClass) {
6611 // Find the Root class
6612 RootClass = CDecl->getSuperClass();
6613 while (RootClass->getSuperClass()) {
6614 RootClass = RootClass->getSuperClass();
6615 }
6616 }
6617
6618 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006619 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006620 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006621 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006622 if (CDecl->getImplementation())
6623 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006624 else
6625 Result += "__declspec(dllimport) ";
6626
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006627 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006628 Result += CDecl->getNameAsString();
6629 Result += ";\n";
6630 }
6631 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006632 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006633 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006634 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006635 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006636 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006637 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006638 else
6639 Result += "__declspec(dllimport) ";
6640
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006641 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006642 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006643 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006644 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006645
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006646 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006647 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006648 if (RootClass->getImplementation())
6649 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006650 else
6651 Result += "__declspec(dllimport) ";
6652
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006653 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006654 Result += VarName;
6655 Result += RootClass->getNameAsString();
6656 Result += ";\n";
6657 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006658 }
6659
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006660 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6661 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006662 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6663 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006664 if (metaclass) {
6665 if (!rootClass) {
6666 Result += "0, // &"; Result += VarName;
6667 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006668 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006669 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006670 Result += CDecl->getSuperClass()->getNameAsString();
6671 Result += ",\n\t";
6672 }
6673 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006674 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006675 Result += CDecl->getNameAsString();
6676 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006677 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006678 Result += ",\n\t";
6679 }
6680 }
6681 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006682 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006683 Result += CDecl->getNameAsString();
6684 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006685 if (!rootClass) {
6686 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006687 Result += CDecl->getSuperClass()->getNameAsString();
6688 Result += ",\n\t";
6689 }
6690 else
6691 Result += "0,\n\t";
6692 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006693 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6694 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6695 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006696 Result += "&_OBJC_METACLASS_RO_$_";
6697 else
6698 Result += "&_OBJC_CLASS_RO_$_";
6699 Result += CDecl->getNameAsString();
6700 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006701
6702 // Add static function to initialize some of the meta-data fields.
6703 // avoid doing it twice.
6704 if (metaclass)
6705 return;
6706
6707 const ObjCInterfaceDecl *SuperClass =
6708 rootClass ? CDecl : CDecl->getSuperClass();
6709
6710 Result += "static void OBJC_CLASS_SETUP_$_";
6711 Result += CDecl->getNameAsString();
6712 Result += "(void ) {\n";
6713 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6714 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006715 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006716
6717 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006718 Result += ".superclass = ";
6719 if (rootClass)
6720 Result += "&OBJC_CLASS_$_";
6721 else
6722 Result += "&OBJC_METACLASS_$_";
6723
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006724 Result += SuperClass->getNameAsString(); Result += ";\n";
6725
6726 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6727 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6728
6729 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6730 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6731 Result += CDecl->getNameAsString(); Result += ";\n";
6732
6733 if (!rootClass) {
6734 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6735 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6736 Result += SuperClass->getNameAsString(); Result += ";\n";
6737 }
6738
6739 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6740 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6741 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006742}
6743
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006744static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6745 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006746 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006747 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006748 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6749 ArrayRef<ObjCMethodDecl *> ClassMethods,
6750 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6751 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006752 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006753 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006754 // must declare an extern class object in case this class is not implemented
6755 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006756 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006757 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006758 if (ClassDecl->getImplementation())
6759 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006760 else
6761 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006762
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006763 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006764 Result += "OBJC_CLASS_$_"; Result += ClassName;
6765 Result += ";\n";
6766
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006767 Result += "\nstatic struct _category_t ";
6768 Result += "_OBJC_$_CATEGORY_";
6769 Result += ClassName; Result += "_$_"; Result += CatName;
6770 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6771 Result += "{\n";
6772 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006773 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006774 Result += ",\n";
6775 if (InstanceMethods.size() > 0) {
6776 Result += "\t(const struct _method_list_t *)&";
6777 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6778 Result += ClassName; Result += "_$_"; Result += CatName;
6779 Result += ",\n";
6780 }
6781 else
6782 Result += "\t0,\n";
6783
6784 if (ClassMethods.size() > 0) {
6785 Result += "\t(const struct _method_list_t *)&";
6786 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6787 Result += ClassName; Result += "_$_"; Result += CatName;
6788 Result += ",\n";
6789 }
6790 else
6791 Result += "\t0,\n";
6792
6793 if (RefedProtocols.size() > 0) {
6794 Result += "\t(const struct _protocol_list_t *)&";
6795 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6796 Result += ClassName; Result += "_$_"; Result += CatName;
6797 Result += ",\n";
6798 }
6799 else
6800 Result += "\t0,\n";
6801
6802 if (ClassProperties.size() > 0) {
6803 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6804 Result += ClassName; Result += "_$_"; Result += CatName;
6805 Result += ",\n";
6806 }
6807 else
6808 Result += "\t0,\n";
6809
6810 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006811
6812 // Add static function to initialize the class pointer in the category structure.
6813 Result += "static void OBJC_CATEGORY_SETUP_$_";
6814 Result += ClassDecl->getNameAsString();
6815 Result += "_$_";
6816 Result += CatName;
6817 Result += "(void ) {\n";
6818 Result += "\t_OBJC_$_CATEGORY_";
6819 Result += ClassDecl->getNameAsString();
6820 Result += "_$_";
6821 Result += CatName;
6822 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6823 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006824}
6825
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006826static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6827 ASTContext *Context, std::string &Result,
6828 ArrayRef<ObjCMethodDecl *> Methods,
6829 StringRef VarName,
6830 StringRef ProtocolName) {
6831 if (Methods.size() == 0)
6832 return;
6833
6834 Result += "\nstatic const char *";
6835 Result += VarName; Result += ProtocolName;
6836 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6837 Result += "{\n";
6838 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6839 ObjCMethodDecl *MD = Methods[i];
6840 std::string MethodTypeString, QuoteMethodTypeString;
6841 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6842 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6843 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6844 if (i == e-1)
6845 Result += "\n};\n";
6846 else {
6847 Result += ",\n";
6848 }
6849 }
6850}
6851
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006852static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6853 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006854 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006855 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006856 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006857 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6858 // this is what happens:
6859 /**
6860 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6861 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6862 Class->getVisibility() == HiddenVisibility)
6863 Visibility shoud be: HiddenVisibility;
6864 else
6865 Visibility shoud be: DefaultVisibility;
6866 */
6867
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006868 Result += "\n";
6869 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6870 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006871 if (Context->getLangOpts().MicrosoftExt)
6872 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6873
6874 if (!Context->getLangOpts().MicrosoftExt ||
6875 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006876 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006877 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006878 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006879 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006880 if (Ivars[i]->isBitField())
6881 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6882 else
6883 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006884 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6885 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006886 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6887 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006888 if (Ivars[i]->isBitField()) {
6889 // skip over rest of the ivar bitfields.
6890 SKIP_BITFIELDS(i , e, Ivars);
6891 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006892 }
6893}
6894
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006895static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6896 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006897 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006898 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006899 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006900 if (OriginalIvars.size() > 0) {
6901 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6902 SmallVector<ObjCIvarDecl *, 8> Ivars;
6903 // strip off all but the first ivar bitfield from each group of ivars.
6904 // Such ivars in the ivar list table will be replaced by their grouping struct
6905 // 'ivar'.
6906 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6907 if (OriginalIvars[i]->isBitField()) {
6908 Ivars.push_back(OriginalIvars[i]);
6909 // skip over rest of the ivar bitfields.
6910 SKIP_BITFIELDS(i , e, OriginalIvars);
6911 }
6912 else
6913 Ivars.push_back(OriginalIvars[i]);
6914 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006915
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006916 Result += "\nstatic ";
6917 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6918 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006919 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006920 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6921 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6922 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6923 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6924 ObjCIvarDecl *IvarDecl = Ivars[i];
6925 if (i == 0)
6926 Result += "\t{{";
6927 else
6928 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006929 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006930 if (Ivars[i]->isBitField())
6931 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6932 else
6933 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006934 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006935
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006936 Result += "\"";
6937 if (Ivars[i]->isBitField())
6938 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6939 else
6940 Result += IvarDecl->getName();
6941 Result += "\", ";
6942
6943 QualType IVQT = IvarDecl->getType();
6944 if (IvarDecl->isBitField())
6945 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6946
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006947 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006948 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006949 IvarDecl);
6950 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6951 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6952
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006953 // FIXME. this alignment represents the host alignment and need be changed to
6954 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006955 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006956 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006957 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006958 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006959 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006960 if (i == e-1)
6961 Result += "}}\n";
6962 else
6963 Result += "},\n";
6964 }
6965 Result += "};\n";
6966 }
6967}
6968
Fariborz Jahanian11671902012-02-07 17:11:38 +00006969/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006970void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6971 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006972
Fariborz Jahanian11671902012-02-07 17:11:38 +00006973 // Do not synthesize the protocol more than once.
6974 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6975 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006976 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006977
6978 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6979 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006980 // Must write out all protocol definitions in current qualifier list,
6981 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006982 for (auto *I : PDecl->protocols())
6983 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006984
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006985 // Construct method lists.
6986 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6987 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006988 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006989 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6990 OptInstanceMethods.push_back(MD);
6991 } else {
6992 InstanceMethods.push_back(MD);
6993 }
6994 }
6995
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006996 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006997 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6998 OptClassMethods.push_back(MD);
6999 } else {
7000 ClassMethods.push_back(MD);
7001 }
7002 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007003 std::vector<ObjCMethodDecl *> AllMethods;
7004 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7005 AllMethods.push_back(InstanceMethods[i]);
7006 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7007 AllMethods.push_back(ClassMethods[i]);
7008 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7009 AllMethods.push_back(OptInstanceMethods[i]);
7010 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7011 AllMethods.push_back(OptClassMethods[i]);
7012
7013 Write__extendedMethodTypes_initializer(*this, Context, Result,
7014 AllMethods,
7015 "_OBJC_PROTOCOL_METHOD_TYPES_",
7016 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007017 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007018 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007019 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7020 "_OBJC_PROTOCOL_REFS_",
7021 PDecl->getNameAsString());
7022
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007023 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007024 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007025 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007026
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007027 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007028 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007029 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007030
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007031 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007032 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007033 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007034
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007035 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007036 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007037 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007038
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007039 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007040 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007041 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00007042 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007043 "_OBJC_PROTOCOL_PROPERTIES_",
7044 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00007045
Fariborz Jahanian48985802012-02-08 00:50:52 +00007046 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007047 Result += "\n";
7048 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007049 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007050 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007051 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007052 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7053 Result += "\t0,\n"; // id is; is null
7054 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007055 if (SuperProtocols.size() > 0) {
7056 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7057 Result += PDecl->getNameAsString(); Result += ",\n";
7058 }
7059 else
7060 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007061 if (InstanceMethods.size() > 0) {
7062 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7063 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007064 }
7065 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007066 Result += "\t0,\n";
7067
7068 if (ClassMethods.size() > 0) {
7069 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_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";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007074
Fariborz Jahanian48985802012-02-08 00:50:52 +00007075 if (OptInstanceMethods.size() > 0) {
7076 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7077 Result += PDecl->getNameAsString(); Result += ",\n";
7078 }
7079 else
7080 Result += "\t0,\n";
7081
7082 if (OptClassMethods.size() > 0) {
7083 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7084 Result += PDecl->getNameAsString(); Result += ",\n";
7085 }
7086 else
7087 Result += "\t0,\n";
7088
7089 if (ProtocolProperties.size() > 0) {
7090 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7091 Result += PDecl->getNameAsString(); Result += ",\n";
7092 }
7093 else
7094 Result += "\t0,\n";
7095
7096 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7097 Result += "\t0,\n";
7098
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007099 if (AllMethods.size() > 0) {
7100 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7101 Result += PDecl->getNameAsString();
7102 Result += "\n};\n";
7103 }
7104 else
7105 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007106
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007107 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007108 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007109 Result += "struct _protocol_t *";
7110 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7111 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7112 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007113
Fariborz Jahanian11671902012-02-07 17:11:38 +00007114 // Mark this protocol as having been generated.
7115 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7116 llvm_unreachable("protocol already synthesized");
7117
7118}
7119
7120void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7121 const ObjCList<ObjCProtocolDecl> &Protocols,
7122 StringRef prefix, StringRef ClassName,
7123 std::string &Result) {
7124 if (Protocols.empty()) return;
7125
7126 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007127 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007128
7129 // Output the top lovel protocol meta-data for the class.
7130 /* struct _objc_protocol_list {
7131 struct _objc_protocol_list *next;
7132 int protocol_count;
7133 struct _objc_protocol *class_protocols[];
7134 }
7135 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007136 Result += "\n";
7137 if (LangOpts.MicrosoftExt)
7138 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7139 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007140 Result += "\tstruct _objc_protocol_list *next;\n";
7141 Result += "\tint protocol_count;\n";
7142 Result += "\tstruct _objc_protocol *class_protocols[";
7143 Result += utostr(Protocols.size());
7144 Result += "];\n} _OBJC_";
7145 Result += prefix;
7146 Result += "_PROTOCOLS_";
7147 Result += ClassName;
7148 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7149 "{\n\t0, ";
7150 Result += utostr(Protocols.size());
7151 Result += "\n";
7152
7153 Result += "\t,{&_OBJC_PROTOCOL_";
7154 Result += Protocols[0]->getNameAsString();
7155 Result += " \n";
7156
7157 for (unsigned i = 1; i != Protocols.size(); i++) {
7158 Result += "\t ,&_OBJC_PROTOCOL_";
7159 Result += Protocols[i]->getNameAsString();
7160 Result += "\n";
7161 }
7162 Result += "\t }\n};\n";
7163}
7164
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007165/// hasObjCExceptionAttribute - Return true if this class or any super
7166/// class has the __objc_exception__ attribute.
7167/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7168static bool hasObjCExceptionAttribute(ASTContext &Context,
7169 const ObjCInterfaceDecl *OID) {
7170 if (OID->hasAttr<ObjCExceptionAttr>())
7171 return true;
7172 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7173 return hasObjCExceptionAttribute(Context, Super);
7174 return false;
7175}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007176
Fariborz Jahanian11671902012-02-07 17:11:38 +00007177void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7178 std::string &Result) {
7179 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7180
7181 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007182 if (CDecl->isImplicitInterfaceDecl())
7183 assert(false &&
7184 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007185
Fariborz Jahanian45489622012-03-14 18:09:23 +00007186 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007187 SmallVector<ObjCIvarDecl *, 8> IVars;
7188
7189 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7190 IVD; IVD = IVD->getNextIvar()) {
7191 // Ignore unnamed bit-fields.
7192 if (!IVD->getDeclName())
7193 continue;
7194 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007195 }
7196
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007197 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007198 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007199 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007200
7201 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007202 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007203
7204 // If any of our property implementations have associated getters or
7205 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007206 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007207 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007208 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007209 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007210 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007211 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007212 if (!PD)
7213 continue;
7214 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007215 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007216 InstanceMethods.push_back(Getter);
7217 if (PD->isReadOnly())
7218 continue;
7219 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007220 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007221 InstanceMethods.push_back(Setter);
7222 }
7223
7224 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7225 "_OBJC_$_INSTANCE_METHODS_",
7226 IDecl->getNameAsString(), true);
7227
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007228 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007229
7230 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7231 "_OBJC_$_CLASS_METHODS_",
7232 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007233
7234 // Protocols referenced in class declaration?
7235 // Protocol's super protocol list
7236 std::vector<ObjCProtocolDecl *> RefedProtocols;
7237 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7238 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7239 E = Protocols.end();
7240 I != E; ++I) {
7241 RefedProtocols.push_back(*I);
7242 // Must write out all protocol definitions in current qualifier list,
7243 // and in their nested qualifiers before writing out current definition.
7244 RewriteObjCProtocolMetaData(*I, Result);
7245 }
7246
7247 Write_protocol_list_initializer(Context, Result,
7248 RefedProtocols,
7249 "_OBJC_CLASS_PROTOCOLS_$_",
7250 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007251
7252 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007253 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007254 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007255 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007256 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007257 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007258
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007259
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007260 // Data for initializing _class_ro_t metaclass meta-data
7261 uint32_t flags = CLS_META;
7262 std::string InstanceSize;
7263 std::string InstanceStart;
7264
7265
7266 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7267 if (classIsHidden)
7268 flags |= OBJC2_CLS_HIDDEN;
7269
7270 if (!CDecl->getSuperClass())
7271 // class is root
7272 flags |= CLS_ROOT;
7273 InstanceSize = "sizeof(struct _class_t)";
7274 InstanceStart = InstanceSize;
7275 Write__class_ro_t_initializer(Context, Result, flags,
7276 InstanceStart, InstanceSize,
7277 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007278 nullptr,
7279 nullptr,
7280 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007281 "_OBJC_METACLASS_RO_$_",
7282 CDecl->getNameAsString());
7283
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007284 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007285 flags = CLS;
7286 if (classIsHidden)
7287 flags |= OBJC2_CLS_HIDDEN;
7288
7289 if (hasObjCExceptionAttribute(*Context, CDecl))
7290 flags |= CLS_EXCEPTION;
7291
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007292 if (!CDecl->getSuperClass())
7293 // class is root
7294 flags |= CLS_ROOT;
7295
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007296 InstanceSize.clear();
7297 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007298 if (!ObjCSynthesizedStructs.count(CDecl)) {
7299 InstanceSize = "0";
7300 InstanceStart = "0";
7301 }
7302 else {
7303 InstanceSize = "sizeof(struct ";
7304 InstanceSize += CDecl->getNameAsString();
7305 InstanceSize += "_IMPL)";
7306
7307 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7308 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007309 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007310 }
7311 else
7312 InstanceStart = InstanceSize;
7313 }
7314 Write__class_ro_t_initializer(Context, Result, flags,
7315 InstanceStart, InstanceSize,
7316 InstanceMethods,
7317 RefedProtocols,
7318 IVars,
7319 ClassProperties,
7320 "_OBJC_CLASS_RO_$_",
7321 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007322
7323 Write_class_t(Context, Result,
7324 "OBJC_METACLASS_$_",
7325 CDecl, /*metaclass*/true);
7326
7327 Write_class_t(Context, Result,
7328 "OBJC_CLASS_$_",
7329 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007330
7331 if (ImplementationIsNonLazy(IDecl))
7332 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007333
Fariborz Jahanian11671902012-02-07 17:11:38 +00007334}
7335
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007336void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7337 int ClsDefCount = ClassImplementation.size();
7338 if (!ClsDefCount)
7339 return;
7340 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7341 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7342 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7343 for (int i = 0; i < ClsDefCount; i++) {
7344 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7345 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7346 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7347 Result += CDecl->getName(); Result += ",\n";
7348 }
7349 Result += "};\n";
7350}
7351
Fariborz Jahanian11671902012-02-07 17:11:38 +00007352void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7353 int ClsDefCount = ClassImplementation.size();
7354 int CatDefCount = CategoryImplementation.size();
7355
7356 // For each implemented class, write out all its meta data.
7357 for (int i = 0; i < ClsDefCount; i++)
7358 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7359
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007360 RewriteClassSetupInitHook(Result);
7361
Fariborz Jahanian11671902012-02-07 17:11:38 +00007362 // For each implemented category, write out all its meta data.
7363 for (int i = 0; i < CatDefCount; i++)
7364 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7365
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007366 RewriteCategorySetupInitHook(Result);
7367
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007368 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007369 if (LangOpts.MicrosoftExt)
7370 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007371 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7372 Result += llvm::utostr(ClsDefCount); Result += "]";
7373 Result +=
7374 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7375 "regular,no_dead_strip\")))= {\n";
7376 for (int i = 0; i < ClsDefCount; i++) {
7377 Result += "\t&OBJC_CLASS_$_";
7378 Result += ClassImplementation[i]->getNameAsString();
7379 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007380 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007381 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007382
7383 if (!DefinedNonLazyClasses.empty()) {
7384 if (LangOpts.MicrosoftExt)
7385 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7386 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7387 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7388 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7389 Result += ",\n";
7390 }
7391 Result += "};\n";
7392 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007393 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007394
7395 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007396 if (LangOpts.MicrosoftExt)
7397 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007398 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7399 Result += llvm::utostr(CatDefCount); Result += "]";
7400 Result +=
7401 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7402 "regular,no_dead_strip\")))= {\n";
7403 for (int i = 0; i < CatDefCount; i++) {
7404 Result += "\t&_OBJC_$_CATEGORY_";
7405 Result +=
7406 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7407 Result += "_$_";
7408 Result += CategoryImplementation[i]->getNameAsString();
7409 Result += ",\n";
7410 }
7411 Result += "};\n";
7412 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007413
7414 if (!DefinedNonLazyCategories.empty()) {
7415 if (LangOpts.MicrosoftExt)
7416 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7417 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7418 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7419 Result += "\t&_OBJC_$_CATEGORY_";
7420 Result +=
7421 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7422 Result += "_$_";
7423 Result += DefinedNonLazyCategories[i]->getNameAsString();
7424 Result += ",\n";
7425 }
7426 Result += "};\n";
7427 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007428}
7429
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007430void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7431 if (LangOpts.MicrosoftExt)
7432 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7433
7434 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7435 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007436 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007437}
7438
Fariborz Jahanian11671902012-02-07 17:11:38 +00007439/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7440/// implementation.
7441void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7442 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007443 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007444 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7445 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007446 ObjCCategoryDecl *CDecl
7447 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007448
7449 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007450 FullCategoryName += "_$_";
7451 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007452
7453 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007454 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007455
7456 // If any of our property implementations have associated getters or
7457 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007458 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007459 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007460 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007461 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007462 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007463 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464 if (!PD)
7465 continue;
7466 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7467 InstanceMethods.push_back(Getter);
7468 if (PD->isReadOnly())
7469 continue;
7470 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7471 InstanceMethods.push_back(Setter);
7472 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007473
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007474 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7475 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7476 FullCategoryName, true);
7477
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007478 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007479
7480 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7481 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7482 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007483
7484 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007485 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007486 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7487 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007488 // Must write out all protocol definitions in current qualifier list,
7489 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007490 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007491
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007492 Write_protocol_list_initializer(Context, Result,
7493 RefedProtocols,
7494 "_OBJC_CATEGORY_PROTOCOLS_$_",
7495 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007496
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007497 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007498 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007499 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007500 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007501 "_OBJC_$_PROP_LIST_",
7502 FullCategoryName);
7503
7504 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007505 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007506 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007507 InstanceMethods,
7508 ClassMethods,
7509 RefedProtocols,
7510 ClassProperties);
7511
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007512 // Determine if this category is also "non-lazy".
7513 if (ImplementationIsNonLazy(IDecl))
7514 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007515
7516}
7517
7518void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7519 int CatDefCount = CategoryImplementation.size();
7520 if (!CatDefCount)
7521 return;
7522 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7523 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7524 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7525 for (int i = 0; i < CatDefCount; i++) {
7526 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7527 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7528 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7529 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7530 Result += ClassDecl->getName();
7531 Result += "_$_";
7532 Result += CatDecl->getName();
7533 Result += ",\n";
7534 }
7535 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007536}
7537
7538// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7539/// class methods.
7540template<typename MethodIterator>
7541void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7542 MethodIterator MethodEnd,
7543 bool IsInstanceMethod,
7544 StringRef prefix,
7545 StringRef ClassName,
7546 std::string &Result) {
7547 if (MethodBegin == MethodEnd) return;
7548
7549 if (!objc_impl_method) {
7550 /* struct _objc_method {
7551 SEL _cmd;
7552 char *method_types;
7553 void *_imp;
7554 }
7555 */
7556 Result += "\nstruct _objc_method {\n";
7557 Result += "\tSEL _cmd;\n";
7558 Result += "\tchar *method_types;\n";
7559 Result += "\tvoid *_imp;\n";
7560 Result += "};\n";
7561
7562 objc_impl_method = true;
7563 }
7564
7565 // Build _objc_method_list for class's methods if needed
7566
7567 /* struct {
7568 struct _objc_method_list *next_method;
7569 int method_count;
7570 struct _objc_method method_list[];
7571 }
7572 */
7573 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007574 Result += "\n";
7575 if (LangOpts.MicrosoftExt) {
7576 if (IsInstanceMethod)
7577 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7578 else
7579 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7580 }
7581 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007582 Result += "\tstruct _objc_method_list *next_method;\n";
7583 Result += "\tint method_count;\n";
7584 Result += "\tstruct _objc_method method_list[";
7585 Result += utostr(NumMethods);
7586 Result += "];\n} _OBJC_";
7587 Result += prefix;
7588 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7589 Result += "_METHODS_";
7590 Result += ClassName;
7591 Result += " __attribute__ ((used, section (\"__OBJC, __";
7592 Result += IsInstanceMethod ? "inst" : "cls";
7593 Result += "_meth\")))= ";
7594 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7595
7596 Result += "\t,{{(SEL)\"";
7597 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7598 std::string MethodTypeString;
7599 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7600 Result += "\", \"";
7601 Result += MethodTypeString;
7602 Result += "\", (void *)";
7603 Result += MethodInternalNames[*MethodBegin];
7604 Result += "}\n";
7605 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7606 Result += "\t ,{(SEL)\"";
7607 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7608 std::string MethodTypeString;
7609 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7610 Result += "\", \"";
7611 Result += MethodTypeString;
7612 Result += "\", (void *)";
7613 Result += MethodInternalNames[*MethodBegin];
7614 Result += "}\n";
7615 }
7616 Result += "\t }\n};\n";
7617}
7618
7619Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7620 SourceRange OldRange = IV->getSourceRange();
7621 Expr *BaseExpr = IV->getBase();
7622
7623 // Rewrite the base, but without actually doing replaces.
7624 {
7625 DisableReplaceStmtScope S(*this);
7626 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7627 IV->setBase(BaseExpr);
7628 }
7629
7630 ObjCIvarDecl *D = IV->getDecl();
7631
7632 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007633
Fariborz Jahanian11671902012-02-07 17:11:38 +00007634 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7635 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007636 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007637 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7638 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007639 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007640 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7641 clsDeclared);
7642 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7643
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007644 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007645 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007646 if (D->isBitField())
7647 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7648 else
7649 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007650
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007651 ReferencedIvars[clsDeclared].insert(D);
7652
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007653 // cast offset to "char *".
7654 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7655 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007656 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007657 BaseExpr);
7658 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7659 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007660 Context->UnsignedLongTy, nullptr,
7661 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007662 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7663 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007664 SourceLocation());
7665 BinaryOperator *addExpr =
7666 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7667 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007668 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007669 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007670 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7671 SourceLocation(),
7672 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007673 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007674 if (D->isBitField())
7675 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007676
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007677 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007678 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007679 RD = RD->getDefinition();
7680 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007681 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007682 ObjCContainerDecl *CDecl =
7683 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7684 // ivar in class extensions requires special treatment.
7685 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7686 CDecl = CatDecl->getClassInterface();
7687 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007688 RecName += "_IMPL";
7689 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7690 SourceLocation(), SourceLocation(),
7691 &Context->Idents.get(RecName.c_str()));
7692 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7693 unsigned UnsignedIntSize =
7694 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7695 Expr *Zero = IntegerLiteral::Create(*Context,
7696 llvm::APInt(UnsignedIntSize, 0),
7697 Context->UnsignedIntTy, SourceLocation());
7698 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7699 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7700 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007701 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007702 SourceLocation(),
7703 &Context->Idents.get(D->getNameAsString()),
Craig Topper8ae12032014-05-07 06:21:57 +00007704 IvarT, nullptr,
7705 /*BitWidth=*/nullptr,
7706 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007707 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7708 FD->getType(), VK_LValue,
7709 OK_Ordinary);
7710 IvarT = Context->getDecltypeType(ME, ME->getType());
7711 }
7712 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007713 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007714 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007715
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007716 castExpr = NoTypeInfoCStyleCastExpr(Context,
7717 castT,
7718 CK_BitCast,
7719 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007720
7721
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007722 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007723 VK_LValue, OK_Ordinary,
7724 SourceLocation());
7725 PE = new (Context) ParenExpr(OldRange.getBegin(),
7726 OldRange.getEnd(),
7727 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007728
7729 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007730 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007731 SourceLocation(),
7732 &Context->Idents.get(D->getNameAsString()),
Craig Topper8ae12032014-05-07 06:21:57 +00007733 D->getType(), nullptr,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007734 /*BitWidth=*/D->getBitWidth(),
Craig Topper8ae12032014-05-07 06:21:57 +00007735 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007736 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7737 FD->getType(), VK_LValue,
7738 OK_Ordinary);
7739 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007740
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007741 }
7742 else
7743 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007744 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007745
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007746 ReplaceStmtWithRange(IV, Replacement, OldRange);
7747 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007748}
Alp Toker0621cb22014-07-16 16:48:33 +00007749
7750#endif