blob: be68d42affa15e971be1ea6d6fcbe49f7444bd2a [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);
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000247 ~RewriteModernObjC() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000248
249 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000250
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000252 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000253 }
254
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000257
258 Stmt *ReplacingStmt = ReplacedNodes[Old];
259 if (ReplacingStmt)
260 return; // We can't rewrite the same node twice.
261
Fariborz Jahanian11671902012-02-07 17:11:38 +0000262 if (DisableReplaceStmt)
263 return;
264
265 // Measure the old text.
266 int Size = Rewrite.getRangeSize(SrcRange);
267 if (Size == -1) {
268 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
269 << Old->getSourceRange();
270 return;
271 }
272 // Get the new text.
273 std::string SStr;
274 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000276 const std::string &Str = S.str();
277
278 // If replacement succeeded or warning disabled return with no warning.
279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280 ReplacedNodes[Old] = New;
281 return;
282 }
283 if (SilenceRewriteMacroWarning)
284 return;
285 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
286 << Old->getSourceRange();
287 }
288
289 void InsertText(SourceLocation Loc, StringRef Str,
290 bool InsertAfter = true) {
291 // If insertion succeeded or warning disabled return with no warning.
292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293 SilenceRewriteMacroWarning)
294 return;
295
296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297 }
298
299 void ReplaceText(SourceLocation Start, unsigned OrigLength,
300 StringRef Str) {
301 // If removal succeeded or warning disabled return with no warning.
302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303 SilenceRewriteMacroWarning)
304 return;
305
306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307 }
308
309 // Syntactic Rewriting.
310 void RewriteRecordBody(RecordDecl *RD);
311 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000312 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000313 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000315 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318 const std::string &typedefString);
319 void RewriteImplementations();
320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321 ObjCImplementationDecl *IMD,
322 ObjCCategoryImplDecl *CID);
323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324 void RewriteImplementationDecl(Decl *Dcl);
325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326 ObjCMethodDecl *MDecl, std::string &ResultStr);
327 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328 const FunctionType *&FPRetType);
329 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330 ValueDecl *VD, bool def=false);
331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000335 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336 void RewriteProperty(ObjCPropertyDecl *prop);
337 void RewriteFunctionDecl(FunctionDecl *FD);
338 void RewriteBlockPointerType(std::string& Str, QualType Type);
339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342 void RewriteTypeOfDecl(VarDecl *VD);
343 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000344
345 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346
347 // Expression Rewriting.
348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365 SourceLocation OrigEnd);
366 Stmt *RewriteBreakStmt(BreakStmt *S);
367 Stmt *RewriteContinueStmt(ContinueStmt *S);
368 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000369 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000370 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000371
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000372 // Computes ivar bitfield group no.
373 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
374 // Names field decl. for ivar bitfield group.
375 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
376 // Names struct type for ivar bitfield group.
377 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
378 // Names symbol for ivar bitfield group field offset.
379 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
380 // Given an ivar bitfield, it builds (or finds) its group record type.
381 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
382 QualType SynthesizeBitfieldGroupStructType(
383 ObjCIvarDecl *IV,
384 SmallVectorImpl<ObjCIvarDecl *> &IVars);
385
Fariborz Jahanian11671902012-02-07 17:11:38 +0000386 // Block rewriting.
387 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
388
389 // Block specific rewrite rules.
390 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000391 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000392 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000393 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
394 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
395
396 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
397 std::string &Result);
398
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000399 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000400 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000401 bool &IsNamedDefinition);
402 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
403 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000404
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000405 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
406
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000407 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
408 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000409
410 void Initialize(ASTContext &context) override;
411
Benjamin Kramer474261a2012-06-02 10:20:41 +0000412 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000413 // rewriting routines on the new ASTs.
414 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000415 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000416 SourceLocation StartLoc=SourceLocation(),
417 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000418
419 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000420 QualType returnType,
421 SmallVectorImpl<QualType> &ArgTypes,
422 SmallVectorImpl<Expr*> &MsgExprs,
423 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000424
425 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
426 SourceLocation StartLoc=SourceLocation(),
427 SourceLocation EndLoc=SourceLocation());
428
429 void SynthCountByEnumWithState(std::string &buf);
430 void SynthMsgSendFunctionDecl();
431 void SynthMsgSendSuperFunctionDecl();
432 void SynthMsgSendStretFunctionDecl();
433 void SynthMsgSendFpretFunctionDecl();
434 void SynthMsgSendSuperStretFunctionDecl();
435 void SynthGetClassFunctionDecl();
436 void SynthGetMetaClassFunctionDecl();
437 void SynthGetSuperClassFunctionDecl();
438 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000439 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000440
441 // Rewriting metadata
442 template<typename MethodIterator>
443 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
444 MethodIterator MethodEnd,
445 bool IsInstanceMethod,
446 StringRef prefix,
447 StringRef ClassName,
448 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000449 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
450 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000451 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000452 const ObjCList<ObjCProtocolDecl> &Prots,
453 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000454 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000455 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000456 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000457
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000458 void RewriteMetaDataIntoBuffer(std::string &Result);
459 void WriteImageInfo(std::string &Result);
460 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463
464 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000465 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000466 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000467 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000468
469
470 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
471 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
472 StringRef funcName, std::string Tag);
473 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
474 StringRef funcName, std::string Tag);
475 std::string SynthesizeBlockImpl(BlockExpr *CE,
476 std::string Tag, std::string Desc);
477 std::string SynthesizeBlockDescriptor(std::string DescTag,
478 std::string ImplTag,
479 int i, StringRef funcName,
480 unsigned hasCopy);
481 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
482 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
483 StringRef FunName);
484 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
485 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000486 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000487
488 // Misc. helper routines.
489 QualType getProtocolType();
490 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000491 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
492 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
493 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
494
495 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
496 void CollectBlockDeclRefInfo(BlockExpr *Exp);
497 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000498 void GetInnerBlockDeclRefExprs(Stmt *S,
499 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000500 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000501
502 // We avoid calling Type::isBlockPointerType(), since it operates on the
503 // canonical type. We only care if the top-level type is a closure pointer.
504 bool isTopLevelBlockPointerType(QualType T) {
505 return isa<BlockPointerType>(T);
506 }
507
508 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
509 /// to a function pointer type and upon success, returns true; false
510 /// otherwise.
511 bool convertBlockPointerToFunctionPointer(QualType &T) {
512 if (isTopLevelBlockPointerType(T)) {
513 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
514 T = Context->getPointerType(BPT->getPointeeType());
515 return true;
516 }
517 return false;
518 }
519
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000520 bool convertObjCTypeToCStyleType(QualType &T);
521
Fariborz Jahanian11671902012-02-07 17:11:38 +0000522 bool needToScanForQualifiers(QualType T);
523 QualType getSuperStructType();
524 QualType getConstantStringStructType();
525 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
526 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
527
528 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000529 if (T->isObjCQualifiedIdType()) {
530 bool isConst = T.isConstQualified();
531 T = isConst ? Context->getObjCIdType().withConst()
532 : Context->getObjCIdType();
533 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000534 else if (T->isObjCQualifiedClassType())
535 T = Context->getObjCClassType();
536 else if (T->isObjCObjectPointerType() &&
537 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
538 if (const ObjCObjectPointerType * OBJPT =
539 T->getAsObjCInterfacePointerType()) {
540 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
541 T = QualType(IFaceT, 0);
542 T = Context->getPointerType(T);
543 }
544 }
545 }
546
547 // FIXME: This predicate seems like it would be useful to add to ASTContext.
548 bool isObjCType(QualType T) {
549 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
550 return false;
551
552 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
553
554 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
555 OCT == Context->getCanonicalType(Context->getObjCClassType()))
556 return true;
557
558 if (const PointerType *PT = OCT->getAs<PointerType>()) {
559 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
560 PT->getPointeeType()->isObjCQualifiedIdType())
561 return true;
562 }
563 return false;
564 }
565 bool PointerTypeTakesAnyBlockArguments(QualType QT);
566 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
567 void GetExtentOfArgList(const char *Name, const char *&LParen,
568 const char *&RParen);
569
570 void QuoteDoublequotes(std::string &From, std::string &To) {
571 for (unsigned i = 0; i < From.length(); i++) {
572 if (From[i] == '"')
573 To += "\\\"";
574 else
575 To += From[i];
576 }
577 }
578
579 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000580 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000581 bool variadic = false) {
582 if (result == Context->getObjCInstanceType())
583 result = Context->getObjCIdType();
584 FunctionProtoType::ExtProtoInfo fpi;
585 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000586 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000587 }
588
589 // Helper function: create a CStyleCastExpr with trivial type source info.
590 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
591 CastKind Kind, Expr *E) {
592 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000593 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
594 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596
597 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
598 IdentifierInfo* II = &Context->Idents.get("load");
599 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000600 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000601 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000602
603 StringLiteral *getStringLiteral(StringRef Str) {
604 QualType StrType = Context->getConstantArrayType(
605 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
606 0);
607 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
608 /*Pascal=*/false, StrType, SourceLocation());
609 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
611
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000612}
Fariborz Jahanian11671902012-02-07 17:11:38 +0000613
614void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615 NamedDecl *D) {
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000618 for (const auto &I : fproto->param_types())
619 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000620 // All the args are checked/rewritten. Don't call twice!
621 RewriteBlockPointerDecl(D);
622 break;
623 }
624 }
625}
626
627void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
628 const PointerType *PT = funcType->getAs<PointerType>();
629 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
630 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
631}
632
633static bool IsHeaderFile(const std::string &Filename) {
634 std::string::size_type DotPos = Filename.rfind('.');
635
636 if (DotPos == std::string::npos) {
637 // no file extension
638 return false;
639 }
640
641 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
642 // C header: .h
643 // C++ header: .hh or .H;
644 return Ext == "h" || Ext == "hh" || Ext == "H";
645}
646
647RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
648 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000649 bool silenceMacroWarn,
650 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000651 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000652 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000653 IsHeader = IsHeaderFile(inFile);
654 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000656 // FIXME. This should be an error. But if block is not called, it is OK. And it
657 // may break including some headers.
658 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
659 "rewriting block literal declared in global scope is not implemented");
660
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
662 DiagnosticsEngine::Warning,
663 "rewriter doesn't support user-specified control flow semantics "
664 "for @try/@finally (code may not execute properly)");
665}
666
David Blaikie6beb6aa2014-08-10 19:56:51 +0000667std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
668 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
669 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
670 return llvm::make_unique<RewriteModernObjC>(
671 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000672}
673
674void RewriteModernObjC::InitializeCommon(ASTContext &context) {
675 Context = &context;
676 SM = &Context->getSourceManager();
677 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000678 MsgSendFunctionDecl = nullptr;
679 MsgSendSuperFunctionDecl = nullptr;
680 MsgSendStretFunctionDecl = nullptr;
681 MsgSendSuperStretFunctionDecl = nullptr;
682 MsgSendFpretFunctionDecl = nullptr;
683 GetClassFunctionDecl = nullptr;
684 GetMetaClassFunctionDecl = nullptr;
685 GetSuperClassFunctionDecl = nullptr;
686 SelGetUidFunctionDecl = nullptr;
687 CFStringFunctionDecl = nullptr;
688 ConstantStringClassReference = nullptr;
689 NSStringRecord = nullptr;
690 CurMethodDef = nullptr;
691 CurFunctionDef = nullptr;
692 GlobalVarDecl = nullptr;
693 GlobalConstructionExp = nullptr;
694 SuperStructDecl = nullptr;
695 ProtocolTypeDecl = nullptr;
696 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000697 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000698 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000700 PropParentMap = nullptr;
701 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000702 DisableReplaceStmt = false;
703 objc_impl_method = false;
704
705 // Get the ID and start/end of the main file.
706 MainFileID = SM->getMainFileID();
707 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
708 MainFileStart = MainBuf->getBufferStart();
709 MainFileEnd = MainBuf->getBufferEnd();
710
David Blaikiebbafb8a2012-03-11 07:00:24 +0000711 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712}
713
714//===----------------------------------------------------------------------===//
715// Top Level Driver Code
716//===----------------------------------------------------------------------===//
717
718void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
719 if (Diags.hasErrorOccurred())
720 return;
721
722 // Two cases: either the decl could be in the main file, or it could be in a
723 // #included file. If the former, rewrite it now. If the later, check to see
724 // if we rewrote the #include/#import.
725 SourceLocation Loc = D->getLocation();
726 Loc = SM->getExpansionLoc(Loc);
727
728 // If this is for a builtin, ignore it.
729 if (Loc.isInvalid()) return;
730
731 // Look for built-in declarations that we need to refer during the rewrite.
732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
733 RewriteFunctionDecl(FD);
734 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
735 // declared in <Foundation/NSString.h>
736 if (FVD->getName() == "_NSConstantStringClassReference") {
737 ConstantStringClassReference = FVD;
738 return;
739 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000740 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
741 RewriteCategoryDecl(CD);
742 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
743 if (PD->isThisDeclarationADefinition())
744 RewriteProtocolDecl(PD);
745 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000746 // FIXME. This will not work in all situations and leaving it out
747 // is harmless.
748 // RewriteLinkageSpec(LSD);
749
Fariborz Jahanian11671902012-02-07 17:11:38 +0000750 // Recurse into linkage specifications
751 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
752 DIEnd = LSD->decls_end();
753 DI != DIEnd; ) {
754 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
755 if (!IFace->isThisDeclarationADefinition()) {
756 SmallVector<Decl *, 8> DG;
757 SourceLocation StartLoc = IFace->getLocStart();
758 do {
759 if (isa<ObjCInterfaceDecl>(*DI) &&
760 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
761 StartLoc == (*DI)->getLocStart())
762 DG.push_back(*DI);
763 else
764 break;
765
766 ++DI;
767 } while (DI != DIEnd);
768 RewriteForwardClassDecl(DG);
769 continue;
770 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000771 else {
772 // Keep track of all interface declarations seen.
773 ObjCInterfacesSeen.push_back(IFace);
774 ++DI;
775 continue;
776 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000777 }
778
779 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
780 if (!Proto->isThisDeclarationADefinition()) {
781 SmallVector<Decl *, 8> DG;
782 SourceLocation StartLoc = Proto->getLocStart();
783 do {
784 if (isa<ObjCProtocolDecl>(*DI) &&
785 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
786 StartLoc == (*DI)->getLocStart())
787 DG.push_back(*DI);
788 else
789 break;
790
791 ++DI;
792 } while (DI != DIEnd);
793 RewriteForwardProtocolDecl(DG);
794 continue;
795 }
796 }
797
798 HandleTopLevelSingleDecl(*DI);
799 ++DI;
800 }
801 }
802 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000803 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000804 return HandleDeclInMainFile(D);
805}
806
807//===----------------------------------------------------------------------===//
808// Syntactic (non-AST) Rewriting Code
809//===----------------------------------------------------------------------===//
810
811void RewriteModernObjC::RewriteInclude() {
812 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
813 StringRef MainBuf = SM->getBufferData(MainFileID);
814 const char *MainBufStart = MainBuf.begin();
815 const char *MainBufEnd = MainBuf.end();
816 size_t ImportLen = strlen("import");
817
818 // Loop over the whole file, looking for includes.
819 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
820 if (*BufPtr == '#') {
821 if (++BufPtr == MainBufEnd)
822 return;
823 while (*BufPtr == ' ' || *BufPtr == '\t')
824 if (++BufPtr == MainBufEnd)
825 return;
826 if (!strncmp(BufPtr, "import", ImportLen)) {
827 // replace import with include
828 SourceLocation ImportLoc =
829 LocStart.getLocWithOffset(BufPtr-MainBufStart);
830 ReplaceText(ImportLoc, ImportLen, "include");
831 BufPtr += ImportLen;
832 }
833 }
834 }
835}
836
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000837static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
838 ObjCIvarDecl *IvarDecl, std::string &Result) {
839 Result += "OBJC_IVAR_$_";
840 Result += IDecl->getName();
841 Result += "$";
842 Result += IvarDecl->getName();
843}
844
845std::string
846RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
847 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
848
849 // Build name of symbol holding ivar offset.
850 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000851 if (D->isBitField())
852 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
853 else
854 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000855
856
857 std::string S = "(*(";
858 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000859 if (D->isBitField())
860 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000861
862 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
863 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
864 RD = RD->getDefinition();
865 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
866 // decltype(((Foo_IMPL*)0)->bar) *
867 ObjCContainerDecl *CDecl =
868 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
869 // ivar in class extensions requires special treatment.
870 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
871 CDecl = CatDecl->getClassInterface();
872 std::string RecName = CDecl->getName();
873 RecName += "_IMPL";
874 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
875 SourceLocation(), SourceLocation(),
876 &Context->Idents.get(RecName.c_str()));
877 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
878 unsigned UnsignedIntSize =
879 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
880 Expr *Zero = IntegerLiteral::Create(*Context,
881 llvm::APInt(UnsignedIntSize, 0),
882 Context->UnsignedIntTy, SourceLocation());
883 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
885 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000886 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000887 SourceLocation(),
888 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000889 IvarT, nullptr,
890 /*BitWidth=*/nullptr, /*Mutable=*/true,
891 ICIS_NoInit);
892 MemberExpr *ME = new (Context)
893 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
894 FD->getType(), VK_LValue, OK_Ordinary);
895 IvarT = Context->getDecltypeType(ME, ME->getType());
896 }
897 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000898 convertObjCTypeToCStyleType(IvarT);
899 QualType castT = Context->getPointerType(IvarT);
900 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
901 S += TypeString;
902 S += ")";
903
904 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
905 S += "((char *)self + ";
906 S += IvarOffsetName;
907 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000908 if (D->isBitField()) {
909 S += ".";
910 S += D->getNameAsString();
911 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000912 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000913 return S;
914}
915
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000916/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
917/// been found in the class implementation. In this case, it must be synthesized.
918static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
919 ObjCPropertyDecl *PD,
920 bool getter) {
921 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
922 : !IMP->getInstanceMethod(PD->getSetterName());
923
924}
925
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
927 ObjCImplementationDecl *IMD,
928 ObjCCategoryImplDecl *CID) {
929 static bool objcGetPropertyDefined = false;
930 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000931 SourceLocation startGetterSetterLoc;
932
933 if (PID->getLocStart().isValid()) {
934 SourceLocation startLoc = PID->getLocStart();
935 InsertText(startLoc, "// ");
936 const char *startBuf = SM->getCharacterData(startLoc);
937 assert((*startBuf == '@') && "bogus @synthesize location");
938 const char *semiBuf = strchr(startBuf, ';');
939 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
940 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
941 }
942 else
943 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000944
945 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
946 return; // FIXME: is this correct?
947
948 // Generate the 'getter' function.
949 ObjCPropertyDecl *PD = PID->getPropertyDecl();
950 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000951 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000952
Bill Wendling44426052012-12-20 19:22:21 +0000953 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000954 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000955 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
956 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957 ObjCPropertyDecl::OBJC_PR_copy));
958 std::string Getr;
959 if (GenGetProperty && !objcGetPropertyDefined) {
960 objcGetPropertyDefined = true;
961 // FIXME. Is this attribute correct in all cases?
962 Getr = "\nextern \"C\" __declspec(dllimport) "
963 "id objc_getProperty(id, SEL, long, bool);\n";
964 }
965 RewriteObjCMethodDecl(OID->getContainingInterface(),
966 PD->getGetterMethodDecl(), Getr);
967 Getr += "{ ";
968 // Synthesize an explicit cast to gain access to the ivar.
969 // See objc-act.c:objc_synthesize_new_getter() for details.
970 if (GenGetProperty) {
971 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
972 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000973 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000974 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000975 FPRetType);
976 Getr += " _TYPE";
977 if (FPRetType) {
978 Getr += ")"; // close the precedence "scope" for "*".
979
980 // Now, emit the argument types (if any).
981 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
982 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000983 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000984 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000985 std::string ParamStr =
986 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000987 Getr += ParamStr;
988 }
989 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000990 if (FT->getNumParams())
991 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000992 Getr += "...";
993 }
994 Getr += ")";
995 } else
996 Getr += "()";
997 }
998 Getr += ";\n";
999 Getr += "return (_TYPE)";
1000 Getr += "objc_getProperty(self, _cmd, ";
1001 RewriteIvarOffsetComputation(OID, Getr);
1002 Getr += ", 1)";
1003 }
1004 else
1005 Getr += "return " + getIvarAccessString(OID);
1006 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001007 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001008 }
1009
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001010 if (PD->isReadOnly() ||
1011 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001012 return;
1013
1014 // Generate the 'setter' function.
1015 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001016 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 ObjCPropertyDecl::OBJC_PR_copy);
1018 if (GenSetProperty && !objcSetPropertyDefined) {
1019 objcSetPropertyDefined = true;
1020 // FIXME. Is this attribute correct in all cases?
1021 Setr = "\nextern \"C\" __declspec(dllimport) "
1022 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1023 }
1024
1025 RewriteObjCMethodDecl(OID->getContainingInterface(),
1026 PD->getSetterMethodDecl(), Setr);
1027 Setr += "{ ";
1028 // Synthesize an explicit cast to initialize the ivar.
1029 // See objc-act.c:objc_synthesize_new_setter() for details.
1030 if (GenSetProperty) {
1031 Setr += "objc_setProperty (self, _cmd, ";
1032 RewriteIvarOffsetComputation(OID, Setr);
1033 Setr += ", (id)";
1034 Setr += PD->getName();
1035 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001036 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001037 Setr += "0, ";
1038 else
1039 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001040 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001041 Setr += "1)";
1042 else
1043 Setr += "0)";
1044 }
1045 else {
1046 Setr += getIvarAccessString(OID) + " = ";
1047 Setr += PD->getName();
1048 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001049 Setr += "; }\n";
1050 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001051}
1052
1053static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1054 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001055 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001056 typedefString += ForwardDecl->getNameAsString();
1057 typedefString += "\n";
1058 typedefString += "#define _REWRITER_typedef_";
1059 typedefString += ForwardDecl->getNameAsString();
1060 typedefString += "\n";
1061 typedefString += "typedef struct objc_object ";
1062 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001063 // typedef struct { } _objc_exc_Classname;
1064 typedefString += ";\ntypedef struct {} _objc_exc_";
1065 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001066 typedefString += ";\n#endif\n";
1067}
1068
1069void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1070 const std::string &typedefString) {
1071 SourceLocation startLoc = ClassDecl->getLocStart();
1072 const char *startBuf = SM->getCharacterData(startLoc);
1073 const char *semiPtr = strchr(startBuf, ';');
1074 // Replace the @class with typedefs corresponding to the classes.
1075 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1076}
1077
1078void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1079 std::string typedefString;
1080 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001081 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1082 if (I == D.begin()) {
1083 // Translate to typedef's that forward reference structs with the same name
1084 // as the class. As a convenience, we include the original declaration
1085 // as a comment.
1086 typedefString += "// @class ";
1087 typedefString += ForwardDecl->getNameAsString();
1088 typedefString += ";";
1089 }
1090 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001091 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001092 else
1093 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001094 }
1095 DeclGroupRef::iterator I = D.begin();
1096 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1097}
1098
1099void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001100 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001101 std::string typedefString;
1102 for (unsigned i = 0; i < D.size(); i++) {
1103 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1104 if (i == 0) {
1105 typedefString += "// @class ";
1106 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001107 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001108 }
1109 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1110 }
1111 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1112}
1113
1114void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1115 // When method is a synthesized one, such as a getter/setter there is
1116 // nothing to rewrite.
1117 if (Method->isImplicit())
1118 return;
1119 SourceLocation LocStart = Method->getLocStart();
1120 SourceLocation LocEnd = Method->getLocEnd();
1121
1122 if (SM->getExpansionLineNumber(LocEnd) >
1123 SM->getExpansionLineNumber(LocStart)) {
1124 InsertText(LocStart, "#if 0\n");
1125 ReplaceText(LocEnd, 1, ";\n#endif\n");
1126 } else {
1127 InsertText(LocStart, "// ");
1128 }
1129}
1130
1131void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1132 SourceLocation Loc = prop->getAtLoc();
1133
1134 ReplaceText(Loc, 0, "// ");
1135 // FIXME: handle properties that are declared across multiple lines.
1136}
1137
1138void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1139 SourceLocation LocStart = CatDecl->getLocStart();
1140
1141 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001142 if (CatDecl->getIvarRBraceLoc().isValid()) {
1143 ReplaceText(LocStart, 1, "/** ");
1144 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1145 }
1146 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001147 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001148 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001149
Aaron Ballmand174edf2014-03-13 19:11:50 +00001150 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001151 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001152
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001153 for (auto *I : CatDecl->instance_methods())
1154 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001155 for (auto *I : CatDecl->class_methods())
1156 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001157
1158 // Lastly, comment out the @end.
1159 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001160 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001161}
1162
1163void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1164 SourceLocation LocStart = PDecl->getLocStart();
1165 assert(PDecl->isThisDeclarationADefinition());
1166
1167 // FIXME: handle protocol headers that are declared across multiple lines.
1168 ReplaceText(LocStart, 0, "// ");
1169
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001170 for (auto *I : PDecl->instance_methods())
1171 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001172 for (auto *I : PDecl->class_methods())
1173 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001174 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001175 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001176
1177 // Lastly, comment out the @end.
1178 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001179 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001180
1181 // Must comment out @optional/@required
1182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
1184 for (const char *p = startBuf; p < endBuf; p++) {
1185 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1188
1189 }
1190 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1191 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1192 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1193
1194 }
1195 }
1196}
1197
1198void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1199 SourceLocation LocStart = (*D.begin())->getLocStart();
1200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid SourceLocation");
1202 // FIXME: handle forward protocol that are declared across multiple lines.
1203 ReplaceText(LocStart, 0, "// ");
1204}
1205
1206void
Craig Topper5603df42013-07-05 19:34:19 +00001207RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001208 SourceLocation LocStart = DG[0]->getLocStart();
1209 if (LocStart.isInvalid())
1210 llvm_unreachable("Invalid SourceLocation");
1211 // FIXME: handle forward protocol that are declared across multiple lines.
1212 ReplaceText(LocStart, 0, "// ");
1213}
1214
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001215void
1216RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1217 SourceLocation LocStart = LSD->getExternLoc();
1218 if (LocStart.isInvalid())
1219 llvm_unreachable("Invalid extern SourceLocation");
1220
1221 ReplaceText(LocStart, 0, "// ");
1222 if (!LSD->hasBraces())
1223 return;
1224 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1225 SourceLocation LocRBrace = LSD->getRBraceLoc();
1226 if (LocRBrace.isInvalid())
1227 llvm_unreachable("Invalid rbrace SourceLocation");
1228 ReplaceText(LocRBrace, 0, "// ");
1229}
1230
Fariborz Jahanian11671902012-02-07 17:11:38 +00001231void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1232 const FunctionType *&FPRetType) {
1233 if (T->isObjCQualifiedIdType())
1234 ResultStr += "id";
1235 else if (T->isFunctionPointerType() ||
1236 T->isBlockPointerType()) {
1237 // needs special handling, since pointer-to-functions have special
1238 // syntax (where a decaration models use).
1239 QualType retType = T;
1240 QualType PointeeTy;
1241 if (const PointerType* PT = retType->getAs<PointerType>())
1242 PointeeTy = PT->getPointeeType();
1243 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1244 PointeeTy = BPT->getPointeeType();
1245 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001246 ResultStr +=
1247 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001248 ResultStr += "(*";
1249 }
1250 } else
1251 ResultStr += T.getAsString(Context->getPrintingPolicy());
1252}
1253
1254void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1255 ObjCMethodDecl *OMD,
1256 std::string &ResultStr) {
1257 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001258 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001259 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001260 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001261 ResultStr += " ";
1262
1263 // Unique method name
1264 std::string NameStr;
1265
1266 if (OMD->isInstanceMethod())
1267 NameStr += "_I_";
1268 else
1269 NameStr += "_C_";
1270
1271 NameStr += IDecl->getNameAsString();
1272 NameStr += "_";
1273
1274 if (ObjCCategoryImplDecl *CID =
1275 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1276 NameStr += CID->getNameAsString();
1277 NameStr += "_";
1278 }
1279 // Append selector names, replacing ':' with '_'
1280 {
1281 std::string selString = OMD->getSelector().getAsString();
1282 int len = selString.size();
1283 for (int i = 0; i < len; i++)
1284 if (selString[i] == ':')
1285 selString[i] = '_';
1286 NameStr += selString;
1287 }
1288 // Remember this name for metadata emission
1289 MethodInternalNames[OMD] = NameStr;
1290 ResultStr += NameStr;
1291
1292 // Rewrite arguments
1293 ResultStr += "(";
1294
1295 // invisible arguments
1296 if (OMD->isInstanceMethod()) {
1297 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1298 selfTy = Context->getPointerType(selfTy);
1299 if (!LangOpts.MicrosoftExt) {
1300 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1301 ResultStr += "struct ";
1302 }
1303 // When rewriting for Microsoft, explicitly omit the structure name.
1304 ResultStr += IDecl->getNameAsString();
1305 ResultStr += " *";
1306 }
1307 else
1308 ResultStr += Context->getObjCClassType().getAsString(
1309 Context->getPrintingPolicy());
1310
1311 ResultStr += " self, ";
1312 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1313 ResultStr += " _cmd";
1314
1315 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001316 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001317 ResultStr += ", ";
1318 if (PDecl->getType()->isObjCQualifiedIdType()) {
1319 ResultStr += "id ";
1320 ResultStr += PDecl->getNameAsString();
1321 } else {
1322 std::string Name = PDecl->getNameAsString();
1323 QualType QT = PDecl->getType();
1324 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001325 (void)convertBlockPointerToFunctionPointer(QT);
1326 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001327 ResultStr += Name;
1328 }
1329 }
1330 if (OMD->isVariadic())
1331 ResultStr += ", ...";
1332 ResultStr += ") ";
1333
1334 if (FPRetType) {
1335 ResultStr += ")"; // close the precedence "scope" for "*".
1336
1337 // Now, emit the argument types (if any).
1338 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1339 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001340 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001341 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001342 std::string ParamStr =
1343 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001344 ResultStr += ParamStr;
1345 }
1346 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001347 if (FT->getNumParams())
1348 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001349 ResultStr += "...";
1350 }
1351 ResultStr += ")";
1352 } else {
1353 ResultStr += "()";
1354 }
1355 }
1356}
1357void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1360
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001361 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001362 if (IMD->getIvarRBraceLoc().isValid()) {
1363 ReplaceText(IMD->getLocStart(), 1, "/** ");
1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001365 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001366 else {
1367 InsertText(IMD->getLocStart(), "// ");
1368 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001369 }
1370 else
1371 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001372
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001373 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001374 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001375 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1376 SourceLocation LocStart = OMD->getLocStart();
1377 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1378
1379 const char *startBuf = SM->getCharacterData(LocStart);
1380 const char *endBuf = SM->getCharacterData(LocEnd);
1381 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1382 }
1383
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001384 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_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 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001394 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1395 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001396
1397 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1398}
1399
1400void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001401 // Do not synthesize more than once.
1402 if (ObjCSynthesizedStructs.count(ClassDecl))
1403 return;
1404 // Make sure super class's are written before current class is written.
1405 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1406 while (SuperClass) {
1407 RewriteInterfaceDecl(SuperClass);
1408 SuperClass = SuperClass->getSuperClass();
1409 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001410 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001411 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001412 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001413 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001414 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1415
Fariborz Jahanianff513382012-02-15 22:01:47 +00001416 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001417 // Mark this typedef as having been written into its c++ equivalent.
1418 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001419
Aaron Ballmand174edf2014-03-13 19:11:50 +00001420 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001421 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001422 for (auto *I : ClassDecl->instance_methods())
1423 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001424 for (auto *I : ClassDecl->class_methods())
1425 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001426
Fariborz Jahanianff513382012-02-15 22:01:47 +00001427 // Lastly, comment out the @end.
1428 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001429 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001430 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001431}
1432
1433Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1434 SourceRange OldRange = PseudoOp->getSourceRange();
1435
1436 // We just magically know some things about the structure of this
1437 // expression.
1438 ObjCMessageExpr *OldMsg =
1439 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1440 PseudoOp->getNumSemanticExprs() - 1));
1441
1442 // Because the rewriter doesn't allow us to rewrite rewritten code,
1443 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001444 Expr *Base;
1445 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 {
1447 DisableReplaceStmtScope S(*this);
1448
1449 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001450 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1452 Base = OldMsg->getInstanceReceiver();
1453 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1454 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1455 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001456
1457 unsigned numArgs = OldMsg->getNumArgs();
1458 for (unsigned i = 0; i < numArgs; i++) {
1459 Expr *Arg = OldMsg->getArg(i);
1460 if (isa<OpaqueValueExpr>(Arg))
1461 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1462 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1463 Args.push_back(Arg);
1464 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001465 }
1466
1467 // TODO: avoid this copy.
1468 SmallVector<SourceLocation, 1> SelLocs;
1469 OldMsg->getSelectorLocs(SelLocs);
1470
Craig Topper8ae12032014-05-07 06:21:57 +00001471 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001472 switch (OldMsg->getReceiverKind()) {
1473 case ObjCMessageExpr::Class:
1474 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1475 OldMsg->getValueKind(),
1476 OldMsg->getLeftLoc(),
1477 OldMsg->getClassReceiverTypeInfo(),
1478 OldMsg->getSelector(),
1479 SelLocs,
1480 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001481 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001482 OldMsg->getRightLoc(),
1483 OldMsg->isImplicit());
1484 break;
1485
1486 case ObjCMessageExpr::Instance:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1490 Base,
1491 OldMsg->getSelector(),
1492 SelLocs,
1493 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001494 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001495 OldMsg->getRightLoc(),
1496 OldMsg->isImplicit());
1497 break;
1498
1499 case ObjCMessageExpr::SuperClass:
1500 case ObjCMessageExpr::SuperInstance:
1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502 OldMsg->getValueKind(),
1503 OldMsg->getLeftLoc(),
1504 OldMsg->getSuperLoc(),
1505 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1506 OldMsg->getSuperType(),
1507 OldMsg->getSelector(),
1508 SelLocs,
1509 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001510 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001511 OldMsg->getRightLoc(),
1512 OldMsg->isImplicit());
1513 break;
1514 }
1515
1516 Stmt *Replacement = SynthMessageExpr(NewMsg);
1517 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1518 return Replacement;
1519}
1520
1521Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1522 SourceRange OldRange = PseudoOp->getSourceRange();
1523
1524 // We just magically know some things about the structure of this
1525 // expression.
1526 ObjCMessageExpr *OldMsg =
1527 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1528
1529 // Because the rewriter doesn't allow us to rewrite rewritten code,
1530 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001531 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001532 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001533 {
1534 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001535 // Rebuild the base expression if we have one.
1536 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1537 Base = OldMsg->getInstanceReceiver();
1538 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1539 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1540 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001541 unsigned numArgs = OldMsg->getNumArgs();
1542 for (unsigned i = 0; i < numArgs; i++) {
1543 Expr *Arg = OldMsg->getArg(i);
1544 if (isa<OpaqueValueExpr>(Arg))
1545 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1546 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1547 Args.push_back(Arg);
1548 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001549 }
1550
1551 // Intentionally empty.
1552 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001553
Craig Topper8ae12032014-05-07 06:21:57 +00001554 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001555 switch (OldMsg->getReceiverKind()) {
1556 case ObjCMessageExpr::Class:
1557 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1558 OldMsg->getValueKind(),
1559 OldMsg->getLeftLoc(),
1560 OldMsg->getClassReceiverTypeInfo(),
1561 OldMsg->getSelector(),
1562 SelLocs,
1563 OldMsg->getMethodDecl(),
1564 Args,
1565 OldMsg->getRightLoc(),
1566 OldMsg->isImplicit());
1567 break;
1568
1569 case ObjCMessageExpr::Instance:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1573 Base,
1574 OldMsg->getSelector(),
1575 SelLocs,
1576 OldMsg->getMethodDecl(),
1577 Args,
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1580 break;
1581
1582 case ObjCMessageExpr::SuperClass:
1583 case ObjCMessageExpr::SuperInstance:
1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585 OldMsg->getValueKind(),
1586 OldMsg->getLeftLoc(),
1587 OldMsg->getSuperLoc(),
1588 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1589 OldMsg->getSuperType(),
1590 OldMsg->getSelector(),
1591 SelLocs,
1592 OldMsg->getMethodDecl(),
1593 Args,
1594 OldMsg->getRightLoc(),
1595 OldMsg->isImplicit());
1596 break;
1597 }
1598
1599 Stmt *Replacement = SynthMessageExpr(NewMsg);
1600 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1601 return Replacement;
1602}
1603
1604/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001605/// ((NSUInteger (*)
1606/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001607/// (void *)objc_msgSend)((id)l_collection,
1608/// sel_registerName(
1609/// "countByEnumeratingWithState:objects:count:"),
1610/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001611/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001612///
1613void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001614 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1615 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001616 buf += "\n\t\t";
1617 buf += "((id)l_collection,\n\t\t";
1618 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1619 buf += "\n\t\t";
1620 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001621 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001622}
1623
1624/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1625/// statement to exit to its outer synthesized loop.
1626///
1627Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1628 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1629 return S;
1630 // replace break with goto __break_label
1631 std::string buf;
1632
1633 SourceLocation startLoc = S->getLocStart();
1634 buf = "goto __break_label_";
1635 buf += utostr(ObjCBcLabelNo.back());
1636 ReplaceText(startLoc, strlen("break"), buf);
1637
Craig Topper8ae12032014-05-07 06:21:57 +00001638 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001639}
1640
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001641void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1642 SourceLocation Loc,
1643 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001644 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001645 LineString += "\n#line ";
1646 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1647 LineString += utostr(PLoc.getLine());
1648 LineString += " \"";
1649 LineString += Lexer::Stringify(PLoc.getFilename());
1650 LineString += "\"\n";
1651 }
1652}
1653
Fariborz Jahanian11671902012-02-07 17:11:38 +00001654/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1655/// statement to continue with its inner synthesized loop.
1656///
1657Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1658 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1659 return S;
1660 // replace continue with goto __continue_label
1661 std::string buf;
1662
1663 SourceLocation startLoc = S->getLocStart();
1664 buf = "goto __continue_label_";
1665 buf += utostr(ObjCBcLabelNo.back());
1666 ReplaceText(startLoc, strlen("continue"), buf);
1667
Craig Topper8ae12032014-05-07 06:21:57 +00001668 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001669}
1670
1671/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1672/// It rewrites:
1673/// for ( type elem in collection) { stmts; }
1674
1675/// Into:
1676/// {
1677/// type elem;
1678/// struct __objcFastEnumerationState enumState = { 0 };
1679/// id __rw_items[16];
1680/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001681/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001682/// objects:__rw_items count:16];
1683/// if (limit) {
1684/// unsigned long startMutations = *enumState.mutationsPtr;
1685/// do {
1686/// unsigned long counter = 0;
1687/// do {
1688/// if (startMutations != *enumState.mutationsPtr)
1689/// objc_enumerationMutation(l_collection);
1690/// elem = (type)enumState.itemsPtr[counter++];
1691/// stmts;
1692/// __continue_label: ;
1693/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001694/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1695/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001696/// elem = nil;
1697/// __break_label: ;
1698/// }
1699/// else
1700/// elem = nil;
1701/// }
1702///
1703Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1704 SourceLocation OrigEnd) {
1705 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1706 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1707 "ObjCForCollectionStmt Statement stack mismatch");
1708 assert(!ObjCBcLabelNo.empty() &&
1709 "ObjCForCollectionStmt - Label No stack empty");
1710
1711 SourceLocation startLoc = S->getLocStart();
1712 const char *startBuf = SM->getCharacterData(startLoc);
1713 StringRef elementName;
1714 std::string elementTypeAsString;
1715 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001716 // line directive first.
1717 SourceLocation ForEachLoc = S->getForLoc();
1718 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1719 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001720 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1721 // type elem;
1722 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1723 QualType ElementType = cast<ValueDecl>(D)->getType();
1724 if (ElementType->isObjCQualifiedIdType() ||
1725 ElementType->isObjCQualifiedInterfaceType())
1726 // Simply use 'id' for all qualified types.
1727 elementTypeAsString = "id";
1728 else
1729 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1730 buf += elementTypeAsString;
1731 buf += " ";
1732 elementName = D->getName();
1733 buf += elementName;
1734 buf += ";\n\t";
1735 }
1736 else {
1737 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1738 elementName = DR->getDecl()->getName();
1739 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1740 if (VD->getType()->isObjCQualifiedIdType() ||
1741 VD->getType()->isObjCQualifiedInterfaceType())
1742 // Simply use 'id' for all qualified types.
1743 elementTypeAsString = "id";
1744 else
1745 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1746 }
1747
1748 // struct __objcFastEnumerationState enumState = { 0 };
1749 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1750 // id __rw_items[16];
1751 buf += "id __rw_items[16];\n\t";
1752 // id l_collection = (id)
1753 buf += "id l_collection = (id)";
1754 // Find start location of 'collection' the hard way!
1755 const char *startCollectionBuf = startBuf;
1756 startCollectionBuf += 3; // skip 'for'
1757 startCollectionBuf = strchr(startCollectionBuf, '(');
1758 startCollectionBuf++; // skip '('
1759 // find 'in' and skip it.
1760 while (*startCollectionBuf != ' ' ||
1761 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1762 (*(startCollectionBuf+3) != ' ' &&
1763 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1764 startCollectionBuf++;
1765 startCollectionBuf += 3;
1766
1767 // Replace: "for (type element in" with string constructed thus far.
1768 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1769 // Replace ')' in for '(' type elem in collection ')' with ';'
1770 SourceLocation rightParenLoc = S->getRParenLoc();
1771 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1772 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1773 buf = ";\n\t";
1774
1775 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1776 // objects:__rw_items count:16];
1777 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001778 // NSUInteger limit =
1779 // ((NSUInteger (*)
1780 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001781 // (void *)objc_msgSend)((id)l_collection,
1782 // sel_registerName(
1783 // "countByEnumeratingWithState:objects:count:"),
1784 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001785 // (id *)__rw_items, (NSUInteger)16);
1786 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001787 SynthCountByEnumWithState(buf);
1788 buf += ";\n\t";
1789 /// if (limit) {
1790 /// unsigned long startMutations = *enumState.mutationsPtr;
1791 /// do {
1792 /// unsigned long counter = 0;
1793 /// do {
1794 /// if (startMutations != *enumState.mutationsPtr)
1795 /// objc_enumerationMutation(l_collection);
1796 /// elem = (type)enumState.itemsPtr[counter++];
1797 buf += "if (limit) {\n\t";
1798 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1799 buf += "do {\n\t\t";
1800 buf += "unsigned long counter = 0;\n\t\t";
1801 buf += "do {\n\t\t\t";
1802 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1803 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1804 buf += elementName;
1805 buf += " = (";
1806 buf += elementTypeAsString;
1807 buf += ")enumState.itemsPtr[counter++];";
1808 // Replace ')' in for '(' type elem in collection ')' with all of these.
1809 ReplaceText(lparenLoc, 1, buf);
1810
1811 /// __continue_label: ;
1812 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001813 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1814 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001815 /// elem = nil;
1816 /// __break_label: ;
1817 /// }
1818 /// else
1819 /// elem = nil;
1820 /// }
1821 ///
1822 buf = ";\n\t";
1823 buf += "__continue_label_";
1824 buf += utostr(ObjCBcLabelNo.back());
1825 buf += ": ;";
1826 buf += "\n\t\t";
1827 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001828 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001829 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001830 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001831 buf += elementName;
1832 buf += " = ((";
1833 buf += elementTypeAsString;
1834 buf += ")0);\n\t";
1835 buf += "__break_label_";
1836 buf += utostr(ObjCBcLabelNo.back());
1837 buf += ": ;\n\t";
1838 buf += "}\n\t";
1839 buf += "else\n\t\t";
1840 buf += elementName;
1841 buf += " = ((";
1842 buf += elementTypeAsString;
1843 buf += ")0);\n\t";
1844 buf += "}\n";
1845
1846 // Insert all these *after* the statement body.
1847 // FIXME: If this should support Obj-C++, support CXXTryStmt
1848 if (isa<CompoundStmt>(S->getBody())) {
1849 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1850 InsertText(endBodyLoc, buf);
1851 } else {
1852 /* Need to treat single statements specially. For example:
1853 *
1854 * for (A *a in b) if (stuff()) break;
1855 * for (A *a in b) xxxyy;
1856 *
1857 * The following code simply scans ahead to the semi to find the actual end.
1858 */
1859 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1860 const char *semiBuf = strchr(stmtBuf, ';');
1861 assert(semiBuf && "Can't find ';'");
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1863 InsertText(endBodyLoc, buf);
1864 }
1865 Stmts.pop_back();
1866 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001867 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001868}
1869
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001870static void Write_RethrowObject(std::string &buf) {
1871 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1872 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1873 buf += "\tid rethrow;\n";
1874 buf += "\t} _fin_force_rethow(_rethrow);";
1875}
1876
Fariborz Jahanian11671902012-02-07 17:11:38 +00001877/// RewriteObjCSynchronizedStmt -
1878/// This routine rewrites @synchronized(expr) stmt;
1879/// into:
1880/// objc_sync_enter(expr);
1881/// @try stmt @finally { objc_sync_exit(expr); }
1882///
1883Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
1887
1888 assert((*startBuf == '@') && "bogus @synchronized location");
1889
1890 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001891 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1892 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001893 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001894
Fariborz Jahanian11671902012-02-07 17:11:38 +00001895 const char *lparenBuf = startBuf;
1896 while (*lparenBuf != '(') lparenBuf++;
1897 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001898
1899 buf = "; objc_sync_enter(_sync_obj);\n";
1900 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1901 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1902 buf += "\n\tid sync_exit;";
1903 buf += "\n\t} _sync_exit(_sync_obj);\n";
1904
1905 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1906 // the sync expression is typically a message expression that's already
1907 // been rewritten! (which implies the SourceLocation's are invalid).
1908 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1909 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1910 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1911 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1912
1913 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1914 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1915 assert (*LBraceLocBuf == '{');
1916 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001917
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001918 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001919 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1920 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001921
1922 buf = "} catch (id e) {_rethrow = e;}\n";
1923 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001924 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001925 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001926
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001927 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001928
Craig Topper8ae12032014-05-07 06:21:57 +00001929 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001930}
1931
1932void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1933{
1934 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001935 for (Stmt *SubStmt : S->children())
1936 if (SubStmt)
1937 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001938
1939 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1940 Diags.Report(Context->getFullLoc(S->getLocStart()),
1941 TryFinallyContainsReturnDiag);
1942 }
1943 return;
1944}
1945
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001946Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1947 SourceLocation startLoc = S->getAtLoc();
1948 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001949 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1950 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001951
1952 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001953}
1954
Fariborz Jahanian11671902012-02-07 17:11:38 +00001955Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001956 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001957 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001958 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001959 SourceLocation TryLocation = S->getAtTryLoc();
1960 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001961
1962 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001963 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001964 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001965 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001966 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001967 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001968 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001969 // Get the start location and compute the semi location.
1970 SourceLocation startLoc = S->getLocStart();
1971 const char *startBuf = SM->getCharacterData(startLoc);
1972
1973 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001974 if (finalStmt)
1975 ReplaceText(startLoc, 1, buf);
1976 else
1977 // @try -> try
1978 ReplaceText(startLoc, 1, "");
1979
Fariborz Jahanian11671902012-02-07 17:11:38 +00001980 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1981 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001982 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001983
Fariborz Jahanian11671902012-02-07 17:11:38 +00001984 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001985 bool AtRemoved = false;
1986 if (catchDecl) {
1987 QualType t = catchDecl->getType();
1988 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991 if (IDecl) {
1992 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001993 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1994
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001995 startBuf = SM->getCharacterData(startLoc);
1996 assert((*startBuf == '@') && "bogus @catch location");
1997 SourceLocation rParenLoc = Catch->getRParenLoc();
1998 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1999
2000 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002001 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002002 Result += " *_"; Result += catchDecl->getNameAsString();
2003 Result += ")";
2004 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2005 // Foo *e = (Foo *)_e;
2006 Result.clear();
2007 Result = "{ ";
2008 Result += IDecl->getNameAsString();
2009 Result += " *"; Result += catchDecl->getNameAsString();
2010 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2011 Result += "_"; Result += catchDecl->getNameAsString();
2012
2013 Result += "; ";
2014 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2015 ReplaceText(lBraceLoc, 1, Result);
2016 AtRemoved = true;
2017 }
2018 }
2019 }
2020 if (!AtRemoved)
2021 // @catch -> catch
2022 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002023
Fariborz Jahanian11671902012-02-07 17:11:38 +00002024 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002025 if (finalStmt) {
2026 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002027 SourceLocation FinallyLoc = finalStmt->getLocStart();
2028
2029 if (noCatch) {
2030 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2031 buf += "catch (id e) {_rethrow = e;}\n";
2032 }
2033 else {
2034 buf += "}\n";
2035 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2036 buf += "catch (id e) {_rethrow = e;}\n";
2037 }
2038
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002039 SourceLocation startFinalLoc = finalStmt->getLocStart();
2040 ReplaceText(startFinalLoc, 8, buf);
2041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startFinalBodyLoc = body->getLocStart();
2043 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002044 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002045 ReplaceText(startFinalBodyLoc, 1, buf);
2046
2047 SourceLocation endFinalBodyLoc = body->getLocEnd();
2048 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002049 // Now check for any return/continue/go statements within the @try.
2050 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002051 }
2052
Craig Topper8ae12032014-05-07 06:21:57 +00002053 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002054}
2055
2056// This can't be done with ReplaceStmt(S, ThrowExpr), since
2057// the throw expression is typically a message expression that's already
2058// been rewritten! (which implies the SourceLocation's are invalid).
2059Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2060 // Get the start location and compute the semi location.
2061 SourceLocation startLoc = S->getLocStart();
2062 const char *startBuf = SM->getCharacterData(startLoc);
2063
2064 assert((*startBuf == '@') && "bogus @throw location");
2065
2066 std::string buf;
2067 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2068 if (S->getThrowExpr())
2069 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002070 else
2071 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002072
2073 // handle "@ throw" correctly.
2074 const char *wBuf = strchr(startBuf, 'w');
2075 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2076 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2077
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002078 SourceLocation endLoc = S->getLocEnd();
2079 const char *endBuf = SM->getCharacterData(endLoc);
2080 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002081 assert((*semiBuf == ';') && "@throw: can't find ';'");
2082 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002083 if (S->getThrowExpr())
2084 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002085 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002086}
2087
2088Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2089 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002090 std::string StrEncoding;
2091 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002092 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002093 ReplaceStmt(Exp, Replacement);
2094
2095 // Replace this subexpr in the parent.
2096 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2097 return Replacement;
2098}
2099
2100Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2101 if (!SelGetUidFunctionDecl)
2102 SynthSelGetUidFunctionDecl();
2103 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2104 // Create a call to sel_registerName("selName").
2105 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002106 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002108 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002109 ReplaceStmt(Exp, SelExp);
2110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2111 return SelExp;
2112}
2113
Craig Toppercf2126e2015-10-22 03:13:07 +00002114CallExpr *
2115RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2116 ArrayRef<Expr *> Args,
2117 SourceLocation StartLoc,
2118 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002119 // Get the type, we will need to reference it in a couple spots.
2120 QualType msgSendType = FD->getType();
2121
2122 // Create a reference to the objc_msgSend() declaration.
2123 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002124 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002125
2126 // Now, we cast the reference to a pointer to the objc_msgSend type.
2127 QualType pToFunc = Context->getPointerType(msgSendType);
2128 ImplicitCastExpr *ICE =
2129 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002130 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002131
2132 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2133
Craig Toppercf2126e2015-10-22 03:13:07 +00002134 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2135 FT->getCallResultType(*Context),
2136 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002137 return Exp;
2138}
2139
2140static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2141 const char *&startRef, const char *&endRef) {
2142 while (startBuf < endBuf) {
2143 if (*startBuf == '<')
2144 startRef = startBuf; // mark the start.
2145 if (*startBuf == '>') {
2146 if (startRef && *startRef == '<') {
2147 endRef = startBuf; // mark the end.
2148 return true;
2149 }
2150 return false;
2151 }
2152 startBuf++;
2153 }
2154 return false;
2155}
2156
2157static void scanToNextArgument(const char *&argRef) {
2158 int angle = 0;
2159 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2160 if (*argRef == '<')
2161 angle++;
2162 else if (*argRef == '>')
2163 angle--;
2164 argRef++;
2165 }
2166 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2167}
2168
2169bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2170 if (T->isObjCQualifiedIdType())
2171 return true;
2172 if (const PointerType *PT = T->getAs<PointerType>()) {
2173 if (PT->getPointeeType()->isObjCQualifiedIdType())
2174 return true;
2175 }
2176 if (T->isObjCObjectPointerType()) {
2177 T = T->getPointeeType();
2178 return T->isObjCQualifiedInterfaceType();
2179 }
2180 if (T->isArrayType()) {
2181 QualType ElemTy = Context->getBaseElementType(T);
2182 return needToScanForQualifiers(ElemTy);
2183 }
2184 return false;
2185}
2186
2187void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2188 QualType Type = E->getType();
2189 if (needToScanForQualifiers(Type)) {
2190 SourceLocation Loc, EndLoc;
2191
2192 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2193 Loc = ECE->getLParenLoc();
2194 EndLoc = ECE->getRParenLoc();
2195 } else {
2196 Loc = E->getLocStart();
2197 EndLoc = E->getLocEnd();
2198 }
2199 // This will defend against trying to rewrite synthesized expressions.
2200 if (Loc.isInvalid() || EndLoc.isInvalid())
2201 return;
2202
2203 const char *startBuf = SM->getCharacterData(Loc);
2204 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002205 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002206 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2207 // Get the locations of the startRef, endRef.
2208 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2209 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2210 // Comment out the protocol references.
2211 InsertText(LessLoc, "/*");
2212 InsertText(GreaterLoc, "*/");
2213 }
2214 }
2215}
2216
2217void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2218 SourceLocation Loc;
2219 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002220 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002221 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2222 Loc = VD->getLocation();
2223 Type = VD->getType();
2224 }
2225 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2226 Loc = FD->getLocation();
2227 // Check for ObjC 'id' and class types that have been adorned with protocol
2228 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2229 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2230 assert(funcType && "missing function type");
2231 proto = dyn_cast<FunctionProtoType>(funcType);
2232 if (!proto)
2233 return;
Alp Toker314cc812014-01-25 16:55:45 +00002234 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002235 }
2236 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2237 Loc = FD->getLocation();
2238 Type = FD->getType();
2239 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002240 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2241 Loc = TD->getLocation();
2242 Type = TD->getUnderlyingType();
2243 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002244 else
2245 return;
2246
2247 if (needToScanForQualifiers(Type)) {
2248 // Since types are unique, we need to scan the buffer.
2249
2250 const char *endBuf = SM->getCharacterData(Loc);
2251 const char *startBuf = endBuf;
2252 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2253 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002254 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
2257 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2258 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2259 // Comment out the protocol references.
2260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
2262 }
2263 }
2264 if (!proto)
2265 return; // most likely, was a variable
2266 // Now check arguments.
2267 const char *startBuf = SM->getCharacterData(Loc);
2268 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002269 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2270 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002271 // Since types are unique, we need to scan the buffer.
2272
2273 const char *endBuf = startBuf;
2274 // scan forward (from the decl location) for argument types.
2275 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002276 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002277 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2278 // Get the locations of the startRef, endRef.
2279 SourceLocation LessLoc =
2280 Loc.getLocWithOffset(startRef-startFuncBuf);
2281 SourceLocation GreaterLoc =
2282 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2283 // Comment out the protocol references.
2284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
2286 }
2287 startBuf = ++endBuf;
2288 }
2289 else {
2290 // If the function name is derived from a macro expansion, then the
2291 // argument buffer will not follow the name. Need to speak with Chris.
2292 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2293 startBuf++; // scan forward (from the decl location) for argument types.
2294 startBuf++;
2295 }
2296 }
2297}
2298
2299void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2300 QualType QT = ND->getType();
2301 const Type* TypePtr = QT->getAs<Type>();
2302 if (!isa<TypeOfExprType>(TypePtr))
2303 return;
2304 while (isa<TypeOfExprType>(TypePtr)) {
2305 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2306 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2307 TypePtr = QT->getAs<Type>();
2308 }
2309 // FIXME. This will not work for multiple declarators; as in:
2310 // __typeof__(a) b,c,d;
2311 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2312 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2313 const char *startBuf = SM->getCharacterData(DeclLoc);
2314 if (ND->getInit()) {
2315 std::string Name(ND->getNameAsString());
2316 TypeAsString += " " + Name + " = ";
2317 Expr *E = ND->getInit();
2318 SourceLocation startLoc;
2319 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2320 startLoc = ECE->getLParenLoc();
2321 else
2322 startLoc = E->getLocStart();
2323 startLoc = SM->getExpansionLoc(startLoc);
2324 const char *endBuf = SM->getCharacterData(startLoc);
2325 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2326 }
2327 else {
2328 SourceLocation X = ND->getLocEnd();
2329 X = SM->getExpansionLoc(X);
2330 const char *endBuf = SM->getCharacterData(X);
2331 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2332 }
2333}
2334
2335// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2336void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2337 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2338 SmallVector<QualType, 16> ArgTys;
2339 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2340 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002341 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002342 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002343 SourceLocation(),
2344 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002345 SelGetUidIdent, getFuncType,
2346 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002347}
2348
2349void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2350 // declared in <objc/objc.h>
2351 if (FD->getIdentifier() &&
2352 FD->getName() == "sel_registerName") {
2353 SelGetUidFunctionDecl = FD;
2354 return;
2355 }
2356 RewriteObjCQualifiedInterfaceTypes(FD);
2357}
2358
2359void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2360 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2361 const char *argPtr = TypeString.c_str();
2362 if (!strchr(argPtr, '^')) {
2363 Str += TypeString;
2364 return;
2365 }
2366 while (*argPtr) {
2367 Str += (*argPtr == '^' ? '*' : *argPtr);
2368 argPtr++;
2369 }
2370}
2371
2372// FIXME. Consolidate this routine with RewriteBlockPointerType.
2373void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2374 ValueDecl *VD) {
2375 QualType Type = VD->getType();
2376 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2377 const char *argPtr = TypeString.c_str();
2378 int paren = 0;
2379 while (*argPtr) {
2380 switch (*argPtr) {
2381 case '(':
2382 Str += *argPtr;
2383 paren++;
2384 break;
2385 case ')':
2386 Str += *argPtr;
2387 paren--;
2388 break;
2389 case '^':
2390 Str += '*';
2391 if (paren == 1)
2392 Str += VD->getNameAsString();
2393 break;
2394 default:
2395 Str += *argPtr;
2396 break;
2397 }
2398 argPtr++;
2399 }
2400}
2401
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002402void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2403 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2404 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2405 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2406 if (!proto)
2407 return;
Alp Toker314cc812014-01-25 16:55:45 +00002408 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002409 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2410 FdStr += " ";
2411 FdStr += FD->getName();
2412 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002413 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002414 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002415 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002416 RewriteBlockPointerType(FdStr, ArgType);
2417 if (i+1 < numArgs)
2418 FdStr += ", ";
2419 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002420 if (FD->isVariadic()) {
2421 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2422 }
2423 else
2424 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002425 InsertText(FunLocStart, FdStr);
2426}
2427
Benjamin Kramer60509af2013-09-09 14:48:42 +00002428// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2429void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2430 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002431 return;
2432 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2433 SmallVector<QualType, 16> ArgTys;
2434 QualType argT = Context->getObjCIdType();
2435 assert(!argT.isNull() && "Can't find 'id' type");
2436 ArgTys.push_back(argT);
2437 ArgTys.push_back(argT);
2438 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002439 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002440 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002441 SourceLocation(),
2442 SourceLocation(),
2443 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002444 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002445}
2446
2447// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2448void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2449 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2450 SmallVector<QualType, 16> ArgTys;
2451 QualType argT = Context->getObjCIdType();
2452 assert(!argT.isNull() && "Can't find 'id' type");
2453 ArgTys.push_back(argT);
2454 argT = Context->getObjCSelType();
2455 assert(!argT.isNull() && "Can't find 'SEL' type");
2456 ArgTys.push_back(argT);
2457 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002458 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002459 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002460 SourceLocation(),
2461 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002462 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002463 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002464}
2465
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002466// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002467void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2468 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002469 SmallVector<QualType, 2> ArgTys;
2470 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002472 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002473 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002474 SourceLocation(),
2475 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002476 msgSendIdent, msgSendType,
2477 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002478}
2479
2480// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2481void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2482 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2483 SmallVector<QualType, 16> ArgTys;
2484 QualType argT = Context->getObjCIdType();
2485 assert(!argT.isNull() && "Can't find 'id' type");
2486 ArgTys.push_back(argT);
2487 argT = Context->getObjCSelType();
2488 assert(!argT.isNull() && "Can't find 'SEL' type");
2489 ArgTys.push_back(argT);
2490 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002491 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002492 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002493 SourceLocation(),
2494 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002495 msgSendIdent, msgSendType,
2496 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002497}
2498
2499// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002500// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002501void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2502 IdentifierInfo *msgSendIdent =
2503 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002504 SmallVector<QualType, 2> ArgTys;
2505 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002506 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002507 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002508 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2509 SourceLocation(),
2510 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002511 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002512 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002513 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002514}
2515
2516// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2517void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2518 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2519 SmallVector<QualType, 16> ArgTys;
2520 QualType argT = Context->getObjCIdType();
2521 assert(!argT.isNull() && "Can't find 'id' type");
2522 ArgTys.push_back(argT);
2523 argT = Context->getObjCSelType();
2524 assert(!argT.isNull() && "Can't find 'SEL' type");
2525 ArgTys.push_back(argT);
2526 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002527 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002528 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002529 SourceLocation(),
2530 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002531 msgSendIdent, msgSendType,
2532 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002533}
2534
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002535// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002536void RewriteModernObjC::SynthGetClassFunctionDecl() {
2537 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2538 SmallVector<QualType, 16> ArgTys;
2539 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002540 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002541 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002542 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002543 SourceLocation(),
2544 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002545 getClassIdent, getClassType,
2546 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002547}
2548
2549// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2550void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2551 IdentifierInfo *getSuperClassIdent =
2552 &Context->Idents.get("class_getSuperclass");
2553 SmallVector<QualType, 16> ArgTys;
2554 ArgTys.push_back(Context->getObjCClassType());
2555 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002556 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002557 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2558 SourceLocation(),
2559 SourceLocation(),
2560 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002561 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002562 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002563}
2564
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002565// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002566void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2567 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2568 SmallVector<QualType, 16> ArgTys;
2569 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002570 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002571 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002572 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002573 SourceLocation(),
2574 SourceLocation(),
2575 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002576 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002577}
2578
2579Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002580 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002581 QualType strType = getConstantStringStructType();
2582
2583 std::string S = "__NSConstantStringImpl_";
2584
2585 std::string tmpName = InFileName;
2586 unsigned i;
2587 for (i=0; i < tmpName.length(); i++) {
2588 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002589 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002590 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002591 tmpName[i] = '_';
2592 }
2593 S += tmpName;
2594 S += "_";
2595 S += utostr(NumObjCStringLiterals++);
2596
2597 Preamble += "static __NSConstantStringImpl " + S;
2598 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2599 Preamble += "0x000007c8,"; // utf8_str
2600 // The pretty printer for StringLiteral handles escape characters properly.
2601 std::string prettyBufS;
2602 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002603 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002604 Preamble += prettyBuf.str();
2605 Preamble += ",";
2606 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2607
2608 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2609 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002610 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002611 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002612 SourceLocation());
2613 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2614 Context->getPointerType(DRE->getType()),
2615 VK_RValue, OK_Ordinary,
2616 SourceLocation());
2617 // cast to NSConstantString *
2618 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2619 CK_CPointerToObjCPointerCast, Unop);
2620 ReplaceStmt(Exp, cast);
2621 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2622 return cast;
2623}
2624
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002625Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2626 unsigned IntSize =
2627 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2628
2629 Expr *FlagExp = IntegerLiteral::Create(*Context,
2630 llvm::APInt(IntSize, Exp->getValue()),
2631 Context->IntTy, Exp->getLocation());
2632 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2633 CK_BitCast, FlagExp);
2634 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2635 cast);
2636 ReplaceStmt(Exp, PE);
2637 return PE;
2638}
2639
Patrick Beard0caa3942012-04-19 00:25:12 +00002640Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002641 // synthesize declaration of helper functions needed in this routine.
2642 if (!SelGetUidFunctionDecl)
2643 SynthSelGetUidFunctionDecl();
2644 // use objc_msgSend() for all.
2645 if (!MsgSendFunctionDecl)
2646 SynthMsgSendFunctionDecl();
2647 if (!GetClassFunctionDecl)
2648 SynthGetClassFunctionDecl();
2649
2650 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2651 SourceLocation StartLoc = Exp->getLocStart();
2652 SourceLocation EndLoc = Exp->getLocEnd();
2653
2654 // Synthesize a call to objc_msgSend().
2655 SmallVector<Expr*, 4> MsgExprs;
2656 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002657
Patrick Beard0caa3942012-04-19 00:25:12 +00002658 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2659 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2660 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002661
Patrick Beard0caa3942012-04-19 00:25:12 +00002662 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002663 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002664 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002665 StartLoc, EndLoc);
2666 MsgExprs.push_back(Cls);
2667
Patrick Beard0caa3942012-04-19 00:25:12 +00002668 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002669 // it will be the 2nd argument.
2670 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002671 SelExprs.push_back(
2672 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002673 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002674 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002675 MsgExprs.push_back(SelExp);
2676
Patrick Beard0caa3942012-04-19 00:25:12 +00002677 // User provided sub-expression is the 3rd, and last, argument.
2678 Expr *subExpr = Exp->getSubExpr();
2679 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002680 QualType type = ICE->getType();
2681 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2682 CastKind CK = CK_BitCast;
2683 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2684 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002685 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002686 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002687 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002688
2689 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002690 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002691 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002692 for (const auto PI : BoxingMethod->parameters())
2693 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002694
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002695 QualType returnType = Exp->getType();
2696 // Get the type, we will need to reference it in a couple spots.
2697 QualType msgSendType = MsgSendFlavor->getType();
2698
2699 // Create a reference to the objc_msgSend() declaration.
2700 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2701 VK_LValue, SourceLocation());
2702
2703 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002704 Context->getPointerType(Context->VoidTy),
2705 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002706
2707 // Now do the "normal" pointer to function cast.
2708 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002709 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002710 castType = Context->getPointerType(castType);
2711 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2712 cast);
2713
2714 // Don't forget the parens to enforce the proper binding.
2715 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2716
2717 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002718 CallExpr *CE = new (Context)
2719 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002720 ReplaceStmt(Exp, CE);
2721 return CE;
2722}
2723
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002724Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2725 // synthesize declaration of helper functions needed in this routine.
2726 if (!SelGetUidFunctionDecl)
2727 SynthSelGetUidFunctionDecl();
2728 // use objc_msgSend() for all.
2729 if (!MsgSendFunctionDecl)
2730 SynthMsgSendFunctionDecl();
2731 if (!GetClassFunctionDecl)
2732 SynthGetClassFunctionDecl();
2733
2734 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2735 SourceLocation StartLoc = Exp->getLocStart();
2736 SourceLocation EndLoc = Exp->getLocEnd();
2737
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002738 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002739 QualType IntQT = Context->IntTy;
2740 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002741 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002742 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002743 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2744 DeclRefExpr *NSArrayDRE =
2745 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2746 SourceLocation());
2747
2748 SmallVector<Expr*, 16> InitExprs;
2749 unsigned NumElements = Exp->getNumElements();
2750 unsigned UnsignedIntSize =
2751 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2752 Expr *count = IntegerLiteral::Create(*Context,
2753 llvm::APInt(UnsignedIntSize, NumElements),
2754 Context->UnsignedIntTy, SourceLocation());
2755 InitExprs.push_back(count);
2756 for (unsigned i = 0; i < NumElements; i++)
2757 InitExprs.push_back(Exp->getElement(i));
2758 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002759 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002760 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002761
2762 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002763 SourceLocation(),
2764 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002765 Context->getPointerType(Context->VoidPtrTy),
2766 nullptr, /*BitWidth=*/nullptr,
2767 /*Mutable=*/true, ICIS_NoInit);
2768 MemberExpr *ArrayLiteralME = new (Context)
2769 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2770 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2771 QualType ConstIdT = Context->getObjCIdType().withConst();
2772 CStyleCastExpr * ArrayLiteralObjects =
2773 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002774 Context->getPointerType(ConstIdT),
2775 CK_BitCast,
2776 ArrayLiteralME);
2777
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002778 // Synthesize a call to objc_msgSend().
2779 SmallVector<Expr*, 32> MsgExprs;
2780 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002781 QualType expType = Exp->getType();
2782
2783 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2784 ObjCInterfaceDecl *Class =
2785 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2786
2787 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002788 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002790 StartLoc, EndLoc);
2791 MsgExprs.push_back(Cls);
2792
2793 // Create a call to sel_registerName("arrayWithObjects:count:").
2794 // it will be the 2nd argument.
2795 SmallVector<Expr*, 4> SelExprs;
2796 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002797 SelExprs.push_back(
2798 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002799 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002800 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002801 MsgExprs.push_back(SelExp);
2802
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002803 // (const id [])objects
2804 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002805
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002806 // (NSUInteger)cnt
2807 Expr *cnt = IntegerLiteral::Create(*Context,
2808 llvm::APInt(UnsignedIntSize, NumElements),
2809 Context->UnsignedIntTy, SourceLocation());
2810 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002811
2812
2813 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002814 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002815 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002816 for (const auto *PI : ArrayMethod->params())
2817 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002818
2819 QualType returnType = Exp->getType();
2820 // Get the type, we will need to reference it in a couple spots.
2821 QualType msgSendType = MsgSendFlavor->getType();
2822
2823 // Create a reference to the objc_msgSend() declaration.
2824 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2825 VK_LValue, SourceLocation());
2826
2827 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2828 Context->getPointerType(Context->VoidTy),
2829 CK_BitCast, DRE);
2830
2831 // Now do the "normal" pointer to function cast.
2832 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002833 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002834 castType = Context->getPointerType(castType);
2835 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2836 cast);
2837
2838 // Don't forget the parens to enforce the proper binding.
2839 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2840
2841 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002842 CallExpr *CE = new (Context)
2843 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002844 ReplaceStmt(Exp, CE);
2845 return CE;
2846}
2847
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002848Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2849 // synthesize declaration of helper functions needed in this routine.
2850 if (!SelGetUidFunctionDecl)
2851 SynthSelGetUidFunctionDecl();
2852 // use objc_msgSend() for all.
2853 if (!MsgSendFunctionDecl)
2854 SynthMsgSendFunctionDecl();
2855 if (!GetClassFunctionDecl)
2856 SynthGetClassFunctionDecl();
2857
2858 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2859 SourceLocation StartLoc = Exp->getLocStart();
2860 SourceLocation EndLoc = Exp->getLocEnd();
2861
2862 // Build the expression: __NSContainer_literal(int, ...).arr
2863 QualType IntQT = Context->IntTy;
2864 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002865 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002866 std::string NSDictFName("__NSContainer_literal");
2867 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2868 DeclRefExpr *NSDictDRE =
2869 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2870 SourceLocation());
2871
2872 SmallVector<Expr*, 16> KeyExprs;
2873 SmallVector<Expr*, 16> ValueExprs;
2874
2875 unsigned NumElements = Exp->getNumElements();
2876 unsigned UnsignedIntSize =
2877 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2878 Expr *count = IntegerLiteral::Create(*Context,
2879 llvm::APInt(UnsignedIntSize, NumElements),
2880 Context->UnsignedIntTy, SourceLocation());
2881 KeyExprs.push_back(count);
2882 ValueExprs.push_back(count);
2883 for (unsigned i = 0; i < NumElements; i++) {
2884 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2885 KeyExprs.push_back(Element.Key);
2886 ValueExprs.push_back(Element.Value);
2887 }
2888
2889 // (const id [])objects
2890 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002891 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002892 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002893
2894 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002895 SourceLocation(),
2896 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002897 Context->getPointerType(Context->VoidPtrTy),
2898 nullptr, /*BitWidth=*/nullptr,
2899 /*Mutable=*/true, ICIS_NoInit);
2900 MemberExpr *DictLiteralValueME = new (Context)
2901 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2902 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2903 QualType ConstIdT = Context->getObjCIdType().withConst();
2904 CStyleCastExpr * DictValueObjects =
2905 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002906 Context->getPointerType(ConstIdT),
2907 CK_BitCast,
2908 DictLiteralValueME);
2909 // (const id <NSCopying> [])keys
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002910 Expr *NSKeyCallExpr =
2911 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2912 NSDictFType, VK_LValue, SourceLocation());
2913
2914 MemberExpr *DictLiteralKeyME = new (Context)
2915 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2916 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2917
2918 CStyleCastExpr * DictKeyObjects =
2919 NoTypeInfoCStyleCastExpr(Context,
2920 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 CK_BitCast,
2922 DictLiteralKeyME);
2923
2924
2925
2926 // Synthesize a call to objc_msgSend().
2927 SmallVector<Expr*, 32> MsgExprs;
2928 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002929 QualType expType = Exp->getType();
2930
2931 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2932 ObjCInterfaceDecl *Class =
2933 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2934
2935 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002936 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002937 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002938 StartLoc, EndLoc);
2939 MsgExprs.push_back(Cls);
2940
2941 // Create a call to sel_registerName("arrayWithObjects:count:").
2942 // it will be the 2nd argument.
2943 SmallVector<Expr*, 4> SelExprs;
2944 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002945 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002946 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002947 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002948 MsgExprs.push_back(SelExp);
2949
2950 // (const id [])objects
2951 MsgExprs.push_back(DictValueObjects);
2952
2953 // (const id <NSCopying> [])keys
2954 MsgExprs.push_back(DictKeyObjects);
2955
2956 // (NSUInteger)cnt
2957 Expr *cnt = IntegerLiteral::Create(*Context,
2958 llvm::APInt(UnsignedIntSize, NumElements),
2959 Context->UnsignedIntTy, SourceLocation());
2960 MsgExprs.push_back(cnt);
2961
2962
2963 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002964 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002965 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002966 for (const auto *PI : DictMethod->params()) {
2967 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002968 if (const PointerType* PT = T->getAs<PointerType>()) {
2969 QualType PointeeTy = PT->getPointeeType();
2970 convertToUnqualifiedObjCType(PointeeTy);
2971 T = Context->getPointerType(PointeeTy);
2972 }
2973 ArgTypes.push_back(T);
2974 }
2975
2976 QualType returnType = Exp->getType();
2977 // Get the type, we will need to reference it in a couple spots.
2978 QualType msgSendType = MsgSendFlavor->getType();
2979
2980 // Create a reference to the objc_msgSend() declaration.
2981 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2982 VK_LValue, SourceLocation());
2983
2984 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2985 Context->getPointerType(Context->VoidTy),
2986 CK_BitCast, DRE);
2987
2988 // Now do the "normal" pointer to function cast.
2989 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002990 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002991 castType = Context->getPointerType(castType);
2992 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2993 cast);
2994
2995 // Don't forget the parens to enforce the proper binding.
2996 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2997
2998 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002999 CallExpr *CE = new (Context)
3000 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003001 ReplaceStmt(Exp, CE);
3002 return CE;
3003}
3004
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003005// struct __rw_objc_super {
3006// struct objc_object *object; struct objc_object *superClass;
3007// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003008QualType RewriteModernObjC::getSuperStructType() {
3009 if (!SuperStructDecl) {
3010 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3011 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003012 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003013 QualType FieldTypes[2];
3014
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003015 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003016 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003017 // struct objc_object *superClass;
3018 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003019
3020 // Create fields
3021 for (unsigned i = 0; i < 2; ++i) {
3022 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3023 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003024 SourceLocation(), nullptr,
3025 FieldTypes[i], nullptr,
3026 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003027 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003028 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003029 }
3030
3031 SuperStructDecl->completeDefinition();
3032 }
3033 return Context->getTagDeclType(SuperStructDecl);
3034}
3035
3036QualType RewriteModernObjC::getConstantStringStructType() {
3037 if (!ConstantStringDecl) {
3038 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3039 SourceLocation(), SourceLocation(),
3040 &Context->Idents.get("__NSConstantStringImpl"));
3041 QualType FieldTypes[4];
3042
3043 // struct objc_object *receiver;
3044 FieldTypes[0] = Context->getObjCIdType();
3045 // int flags;
3046 FieldTypes[1] = Context->IntTy;
3047 // char *str;
3048 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3049 // long length;
3050 FieldTypes[3] = Context->LongTy;
3051
3052 // Create fields
3053 for (unsigned i = 0; i < 4; ++i) {
3054 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3055 ConstantStringDecl,
3056 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003057 SourceLocation(), nullptr,
3058 FieldTypes[i], nullptr,
3059 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003060 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003061 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003062 }
3063
3064 ConstantStringDecl->completeDefinition();
3065 }
3066 return Context->getTagDeclType(ConstantStringDecl);
3067}
3068
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003069/// getFunctionSourceLocation - returns start location of a function
3070/// definition. Complication arises when function has declared as
3071/// extern "C" or extern "C" {...}
3072static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3073 FunctionDecl *FD) {
3074 if (FD->isExternC() && !FD->isMain()) {
3075 const DeclContext *DC = FD->getDeclContext();
3076 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3077 // if it is extern "C" {...}, return function decl's own location.
3078 if (!LSD->getRBraceLoc().isValid())
3079 return LSD->getExternLoc();
3080 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003081 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003082 R.RewriteBlockLiteralFunctionDecl(FD);
3083 return FD->getTypeSpecStartLoc();
3084}
3085
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003086void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3087
3088 SourceLocation Location = D->getLocation();
3089
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003090 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003091 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003092 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3093 LineString += utostr(PLoc.getLine());
3094 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003095 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003096 if (isa<ObjCMethodDecl>(D))
3097 LineString += "\"";
3098 else LineString += "\"\n";
3099
3100 Location = D->getLocStart();
3101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3102 if (FD->isExternC() && !FD->isMain()) {
3103 const DeclContext *DC = FD->getDeclContext();
3104 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3105 // if it is extern "C" {...}, return function decl's own location.
3106 if (!LSD->getRBraceLoc().isValid())
3107 Location = LSD->getExternLoc();
3108 }
3109 }
3110 InsertText(Location, LineString);
3111 }
3112}
3113
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003114/// SynthMsgSendStretCallExpr - This routine translates message expression
3115/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3116/// nil check on receiver must be performed before calling objc_msgSend_stret.
3117/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3118/// msgSendType - function type of objc_msgSend_stret(...)
3119/// returnType - Result type of the method being synthesized.
3120/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3121/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3122/// starting with receiver.
3123/// Method - Method being rewritten.
3124Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003125 QualType returnType,
3126 SmallVectorImpl<QualType> &ArgTypes,
3127 SmallVectorImpl<Expr*> &MsgExprs,
3128 ObjCMethodDecl *Method) {
3129 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003130 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3131 Method ? Method->isVariadic()
3132 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003133 castType = Context->getPointerType(castType);
3134
3135 // build type for containing the objc_msgSend_stret object.
3136 static unsigned stretCount=0;
3137 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003138 std::string str =
3139 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003140 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003141 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003142 str += " {\n\t";
3143 str += name;
3144 str += "(id receiver, SEL sel";
3145 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003146 std::string ArgName = "arg"; ArgName += utostr(i);
3147 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3148 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003149 }
3150 // could be vararg.
3151 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003152 std::string ArgName = "arg"; ArgName += utostr(i);
3153 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3154 Context->getPrintingPolicy());
3155 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003156 }
3157
3158 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003159 str += "\t unsigned size = sizeof(";
3160 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3161
3162 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3163
3164 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3165 str += ")(void *)objc_msgSend)(receiver, sel";
3166 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3167 str += ", arg"; str += utostr(i);
3168 }
3169 // could be vararg.
3170 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3171 str += ", arg"; str += utostr(i);
3172 }
3173 str+= ");\n";
3174
3175 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003176 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3177 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003178
3179
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003180 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3181 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3182 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3183 str += ", arg"; str += utostr(i);
3184 }
3185 // could be vararg.
3186 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3187 str += ", arg"; str += utostr(i);
3188 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003189 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003190
3191
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003192 str += "\t}\n";
3193 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3194 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003195 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003196 SourceLocation FunLocStart;
3197 if (CurFunctionDef)
3198 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3199 else {
3200 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3201 FunLocStart = CurMethodDef->getLocStart();
3202 }
3203
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003204 InsertText(FunLocStart, str);
3205 ++stretCount;
3206
3207 // AST for __Stretn(receiver, args).s;
3208 IdentifierInfo *ID = &Context->Idents.get(name);
3209 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003210 SourceLocation(), ID, castType,
3211 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003212 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3213 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003214 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003215 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003216
3217 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003218 SourceLocation(),
3219 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003220 returnType, nullptr,
3221 /*BitWidth=*/nullptr,
3222 /*Mutable=*/true, ICIS_NoInit);
3223 MemberExpr *ME = new (Context)
3224 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3225 FieldD->getType(), VK_LValue, OK_Ordinary);
3226
3227 return ME;
3228}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003229
Fariborz Jahanian11671902012-02-07 17:11:38 +00003230Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3231 SourceLocation StartLoc,
3232 SourceLocation EndLoc) {
3233 if (!SelGetUidFunctionDecl)
3234 SynthSelGetUidFunctionDecl();
3235 if (!MsgSendFunctionDecl)
3236 SynthMsgSendFunctionDecl();
3237 if (!MsgSendSuperFunctionDecl)
3238 SynthMsgSendSuperFunctionDecl();
3239 if (!MsgSendStretFunctionDecl)
3240 SynthMsgSendStretFunctionDecl();
3241 if (!MsgSendSuperStretFunctionDecl)
3242 SynthMsgSendSuperStretFunctionDecl();
3243 if (!MsgSendFpretFunctionDecl)
3244 SynthMsgSendFpretFunctionDecl();
3245 if (!GetClassFunctionDecl)
3246 SynthGetClassFunctionDecl();
3247 if (!GetSuperClassFunctionDecl)
3248 SynthGetSuperClassFunctionDecl();
3249 if (!GetMetaClassFunctionDecl)
3250 SynthGetMetaClassFunctionDecl();
3251
3252 // default to objc_msgSend().
3253 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3254 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003255 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003256 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003257 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003258 if (resultType->isRecordType())
3259 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3260 else if (resultType->isRealFloatingType())
3261 MsgSendFlavor = MsgSendFpretFunctionDecl;
3262 }
3263
3264 // Synthesize a call to objc_msgSend().
3265 SmallVector<Expr*, 8> MsgExprs;
3266 switch (Exp->getReceiverKind()) {
3267 case ObjCMessageExpr::SuperClass: {
3268 MsgSendFlavor = MsgSendSuperFunctionDecl;
3269 if (MsgSendStretFlavor)
3270 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3271 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3272
3273 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3274
3275 SmallVector<Expr*, 4> InitExprs;
3276
3277 // set the receiver to self, the first argument to all methods.
3278 InitExprs.push_back(
3279 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3280 CK_BitCast,
3281 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003282 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003283 Context->getObjCIdType(),
3284 VK_RValue,
3285 SourceLocation()))
3286 ); // set the 'receiver'.
3287
3288 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3289 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003290 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003291 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003292 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003293 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003294 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003295 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003296 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003297 StartLoc, EndLoc);
3298
3299 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3300 // To turn off a warning, type-cast to 'id'
3301 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3302 NoTypeInfoCStyleCastExpr(Context,
3303 Context->getObjCIdType(),
3304 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003305 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003306 QualType superType = getSuperStructType();
3307 Expr *SuperRep;
3308
3309 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003310 SynthSuperConstructorFunctionDecl();
3311 // Simulate a constructor call...
3312 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003313 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003314 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003315 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003316 superType, VK_LValue,
3317 SourceLocation());
3318 // The code for super is a little tricky to prevent collision with
3319 // the structure definition in the header. The rewriter has it's own
3320 // internal definition (__rw_objc_super) that is uses. This is why
3321 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003322 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003323 //
3324 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3325 Context->getPointerType(SuperRep->getType()),
3326 VK_RValue, OK_Ordinary,
3327 SourceLocation());
3328 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3329 Context->getPointerType(superType),
3330 CK_BitCast, SuperRep);
3331 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003332 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003333 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003334 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003335 SourceLocation());
3336 TypeSourceInfo *superTInfo
3337 = Context->getTrivialTypeSourceInfo(superType);
3338 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3339 superType, VK_LValue,
3340 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003341 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003342 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3343 Context->getPointerType(SuperRep->getType()),
3344 VK_RValue, OK_Ordinary,
3345 SourceLocation());
3346 }
3347 MsgExprs.push_back(SuperRep);
3348 break;
3349 }
3350
3351 case ObjCMessageExpr::Class: {
3352 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 ObjCInterfaceDecl *Class
3354 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3355 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003356 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003357 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003358 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003359 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3360 Context->getObjCIdType(),
3361 CK_BitCast, Cls);
3362 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003363 break;
3364 }
3365
3366 case ObjCMessageExpr::SuperInstance:{
3367 MsgSendFlavor = MsgSendSuperFunctionDecl;
3368 if (MsgSendStretFlavor)
3369 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3370 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3371 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3372 SmallVector<Expr*, 4> InitExprs;
3373
3374 InitExprs.push_back(
3375 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3376 CK_BitCast,
3377 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003378 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003379 Context->getObjCIdType(),
3380 VK_RValue, SourceLocation()))
3381 ); // set the 'receiver'.
3382
3383 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3384 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003385 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003386 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003387 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003388 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003389 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003390 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003391 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003392 StartLoc, EndLoc);
3393
3394 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3395 // To turn off a warning, type-cast to 'id'
3396 InitExprs.push_back(
3397 // set 'super class', using class_getSuperclass().
3398 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3399 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003400 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003401 QualType superType = getSuperStructType();
3402 Expr *SuperRep;
3403
3404 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003405 SynthSuperConstructorFunctionDecl();
3406 // Simulate a constructor call...
3407 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003408 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003409 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003410 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003411 superType, VK_LValue, SourceLocation());
3412 // The code for super is a little tricky to prevent collision with
3413 // the structure definition in the header. The rewriter has it's own
3414 // internal definition (__rw_objc_super) that is uses. This is why
3415 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003416 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003417 //
3418 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3419 Context->getPointerType(SuperRep->getType()),
3420 VK_RValue, OK_Ordinary,
3421 SourceLocation());
3422 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3423 Context->getPointerType(superType),
3424 CK_BitCast, SuperRep);
3425 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003426 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003427 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003428 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003429 SourceLocation());
3430 TypeSourceInfo *superTInfo
3431 = Context->getTrivialTypeSourceInfo(superType);
3432 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3433 superType, VK_RValue, ILE,
3434 false);
3435 }
3436 MsgExprs.push_back(SuperRep);
3437 break;
3438 }
3439
3440 case ObjCMessageExpr::Instance: {
3441 // Remove all type-casts because it may contain objc-style types; e.g.
3442 // Foo<Proto> *.
3443 Expr *recExpr = Exp->getInstanceReceiver();
3444 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3445 recExpr = CE->getSubExpr();
3446 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3447 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3448 ? CK_BlockPointerToObjCPointerCast
3449 : CK_CPointerToObjCPointerCast;
3450
3451 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3452 CK, recExpr);
3453 MsgExprs.push_back(recExpr);
3454 break;
3455 }
3456 }
3457
3458 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3459 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003460 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003461 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003462 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003463 MsgExprs.push_back(SelExp);
3464
3465 // Now push any user supplied arguments.
3466 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3467 Expr *userExpr = Exp->getArg(i);
3468 // Make all implicit casts explicit...ICE comes in handy:-)
3469 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3470 // Reuse the ICE type, it is exactly what the doctor ordered.
3471 QualType type = ICE->getType();
3472 if (needToScanForQualifiers(type))
3473 type = Context->getObjCIdType();
3474 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3475 (void)convertBlockPointerToFunctionPointer(type);
3476 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3477 CastKind CK;
3478 if (SubExpr->getType()->isIntegralType(*Context) &&
3479 type->isBooleanType()) {
3480 CK = CK_IntegralToBoolean;
3481 } else if (type->isObjCObjectPointerType()) {
3482 if (SubExpr->getType()->isBlockPointerType()) {
3483 CK = CK_BlockPointerToObjCPointerCast;
3484 } else if (SubExpr->getType()->isPointerType()) {
3485 CK = CK_CPointerToObjCPointerCast;
3486 } else {
3487 CK = CK_BitCast;
3488 }
3489 } else {
3490 CK = CK_BitCast;
3491 }
3492
3493 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3494 }
3495 // Make id<P...> cast into an 'id' cast.
3496 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3497 if (CE->getType()->isObjCQualifiedIdType()) {
3498 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3499 userExpr = CE->getSubExpr();
3500 CastKind CK;
3501 if (userExpr->getType()->isIntegralType(*Context)) {
3502 CK = CK_IntegralToPointer;
3503 } else if (userExpr->getType()->isBlockPointerType()) {
3504 CK = CK_BlockPointerToObjCPointerCast;
3505 } else if (userExpr->getType()->isPointerType()) {
3506 CK = CK_CPointerToObjCPointerCast;
3507 } else {
3508 CK = CK_BitCast;
3509 }
3510 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3511 CK, userExpr);
3512 }
3513 }
3514 MsgExprs.push_back(userExpr);
3515 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3516 // out the argument in the original expression (since we aren't deleting
3517 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3518 //Exp->setArg(i, 0);
3519 }
3520 // Generate the funky cast.
3521 CastExpr *cast;
3522 SmallVector<QualType, 8> ArgTypes;
3523 QualType returnType;
3524
3525 // Push 'id' and 'SEL', the 2 implicit arguments.
3526 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3527 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3528 else
3529 ArgTypes.push_back(Context->getObjCIdType());
3530 ArgTypes.push_back(Context->getObjCSelType());
3531 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3532 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003533 for (const auto *PI : OMD->params()) {
3534 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003535 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003536 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003537 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3538 (void)convertBlockPointerToFunctionPointer(t);
3539 ArgTypes.push_back(t);
3540 }
3541 returnType = Exp->getType();
3542 convertToUnqualifiedObjCType(returnType);
3543 (void)convertBlockPointerToFunctionPointer(returnType);
3544 } else {
3545 returnType = Context->getObjCIdType();
3546 }
3547 // Get the type, we will need to reference it in a couple spots.
3548 QualType msgSendType = MsgSendFlavor->getType();
3549
3550 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003551 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003552 VK_LValue, SourceLocation());
3553
3554 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3555 // If we don't do this cast, we get the following bizarre warning/note:
3556 // xx.m:13: warning: function called through a non-compatible type
3557 // xx.m:13: note: if this code is reached, the program will abort
3558 cast = NoTypeInfoCStyleCastExpr(Context,
3559 Context->getPointerType(Context->VoidTy),
3560 CK_BitCast, DRE);
3561
3562 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003563 // If we don't have a method decl, force a variadic cast.
3564 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003565 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003566 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003567 castType = Context->getPointerType(castType);
3568 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3569 cast);
3570
3571 // Don't forget the parens to enforce the proper binding.
3572 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3573
3574 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003575 CallExpr *CE = new (Context)
3576 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003577 Stmt *ReplacingStmt = CE;
3578 if (MsgSendStretFlavor) {
3579 // We have the method which returns a struct/union. Must also generate
3580 // call to objc_msgSend_stret and hang both varieties on a conditional
3581 // expression which dictate which one to envoke depending on size of
3582 // method's return type.
3583
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003584 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3585 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003586 ArgTypes, MsgExprs,
3587 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003588 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003589 }
3590 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3591 return ReplacingStmt;
3592}
3593
3594Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3595 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3596 Exp->getLocEnd());
3597
3598 // Now do the actual rewrite.
3599 ReplaceStmt(Exp, ReplacingStmt);
3600
3601 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3602 return ReplacingStmt;
3603}
3604
3605// typedef struct objc_object Protocol;
3606QualType RewriteModernObjC::getProtocolType() {
3607 if (!ProtocolTypeDecl) {
3608 TypeSourceInfo *TInfo
3609 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3610 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3611 SourceLocation(), SourceLocation(),
3612 &Context->Idents.get("Protocol"),
3613 TInfo);
3614 }
3615 return Context->getTypeDeclType(ProtocolTypeDecl);
3616}
3617
3618/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3619/// a synthesized/forward data reference (to the protocol's metadata).
3620/// The forward references (and metadata) are generated in
3621/// RewriteModernObjC::HandleTranslationUnit().
3622Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003623 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3624 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003625 IdentifierInfo *ID = &Context->Idents.get(Name);
3626 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003627 SourceLocation(), ID, getProtocolType(),
3628 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003629 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3630 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003631 CastExpr *castExpr =
3632 NoTypeInfoCStyleCastExpr(
3633 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003634 ReplaceStmt(Exp, castExpr);
3635 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3636 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3637 return castExpr;
3638
3639}
3640
3641bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3642 const char *endBuf) {
3643 while (startBuf < endBuf) {
3644 if (*startBuf == '#') {
3645 // Skip whitespace.
3646 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3647 ;
3648 if (!strncmp(startBuf, "if", strlen("if")) ||
3649 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3650 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3651 !strncmp(startBuf, "define", strlen("define")) ||
3652 !strncmp(startBuf, "undef", strlen("undef")) ||
3653 !strncmp(startBuf, "else", strlen("else")) ||
3654 !strncmp(startBuf, "elif", strlen("elif")) ||
3655 !strncmp(startBuf, "endif", strlen("endif")) ||
3656 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3657 !strncmp(startBuf, "include", strlen("include")) ||
3658 !strncmp(startBuf, "import", strlen("import")) ||
3659 !strncmp(startBuf, "include_next", strlen("include_next")))
3660 return true;
3661 }
3662 startBuf++;
3663 }
3664 return false;
3665}
3666
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003667/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3668/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003669bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003670 TagDecl *Tag,
3671 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003672 if (!IDecl)
3673 return false;
3674 SourceLocation TagLocation;
3675 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3676 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003677 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003678 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003679 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003680 TagLocation = RD->getLocation();
3681 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003682 IDecl->getLocation(), TagLocation);
3683 }
3684 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3685 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3686 return false;
3687 IsNamedDefinition = true;
3688 TagLocation = ED->getLocation();
3689 return Context->getSourceManager().isBeforeInTranslationUnit(
3690 IDecl->getLocation(), TagLocation);
3691
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003692 }
3693 return false;
3694}
3695
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003696/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003697/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003698bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3699 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003700 if (isa<TypedefType>(Type)) {
3701 Result += "\t";
3702 return false;
3703 }
3704
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003705 if (Type->isArrayType()) {
3706 QualType ElemTy = Context->getBaseElementType(Type);
3707 return RewriteObjCFieldDeclType(ElemTy, Result);
3708 }
3709 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003710 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3711 if (RD->isCompleteDefinition()) {
3712 if (RD->isStruct())
3713 Result += "\n\tstruct ";
3714 else if (RD->isUnion())
3715 Result += "\n\tunion ";
3716 else
3717 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003718
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003719 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003720 if (GlobalDefinedTags.count(RD)) {
3721 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003722 Result += " ";
3723 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003724 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003725 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003726 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003727 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003728 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003729 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003730 }
3731 }
3732 else if (Type->isEnumeralType()) {
3733 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3734 if (ED->isCompleteDefinition()) {
3735 Result += "\n\tenum ";
3736 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003737 if (GlobalDefinedTags.count(ED)) {
3738 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003739 Result += " ";
3740 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003741 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003742
3743 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003744 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003745 Result += "\t"; Result += EC->getName(); Result += " = ";
3746 llvm::APSInt Val = EC->getInitVal();
3747 Result += Val.toString(10);
3748 Result += ",\n";
3749 }
3750 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003751 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003752 }
3753 }
3754
3755 Result += "\t";
3756 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003757 return false;
3758}
3759
3760
3761/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3762/// It handles elaborated types, as well as enum types in the process.
3763void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3764 std::string &Result) {
3765 QualType Type = fieldDecl->getType();
3766 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003767
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003768 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3769 if (!EleboratedType)
3770 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003771 Result += Name;
3772 if (fieldDecl->isBitField()) {
3773 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3774 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003775 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003776 const ArrayType *AT = Context->getAsArrayType(Type);
3777 do {
3778 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003779 Result += "[";
3780 llvm::APInt Dim = CAT->getSize();
3781 Result += utostr(Dim.getZExtValue());
3782 Result += "]";
3783 }
Eli Friedman07bab732012-12-13 01:43:21 +00003784 AT = Context->getAsArrayType(AT->getElementType());
3785 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003786 }
3787
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003788 Result += ";\n";
3789}
3790
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003791/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3792/// named aggregate types into the input buffer.
3793void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3794 std::string &Result) {
3795 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003796 if (isa<TypedefType>(Type))
3797 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003798 if (Type->isArrayType())
3799 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003800 ObjCContainerDecl *IDecl =
3801 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003802
3803 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003804 if (Type->isRecordType()) {
3805 TD = Type->getAs<RecordType>()->getDecl();
3806 }
3807 else if (Type->isEnumeralType()) {
3808 TD = Type->getAs<EnumType>()->getDecl();
3809 }
3810
3811 if (TD) {
3812 if (GlobalDefinedTags.count(TD))
3813 return;
3814
3815 bool IsNamedDefinition = false;
3816 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3817 RewriteObjCFieldDeclType(Type, Result);
3818 Result += ";";
3819 }
3820 if (IsNamedDefinition)
3821 GlobalDefinedTags.insert(TD);
3822 }
3823
3824}
3825
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003826unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3827 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3828 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3829 return IvarGroupNumber[IV];
3830 }
3831 unsigned GroupNo = 0;
3832 SmallVector<const ObjCIvarDecl *, 8> IVars;
3833 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3834 IVD; IVD = IVD->getNextIvar())
3835 IVars.push_back(IVD);
3836
3837 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3838 if (IVars[i]->isBitField()) {
3839 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3840 while (i < e && IVars[i]->isBitField())
3841 IvarGroupNumber[IVars[i++]] = GroupNo;
3842 if (i < e)
3843 --i;
3844 }
3845
3846 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3847 return IvarGroupNumber[IV];
3848}
3849
3850QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3851 ObjCIvarDecl *IV,
3852 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3853 std::string StructTagName;
3854 ObjCIvarBitfieldGroupType(IV, StructTagName);
3855 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3856 Context->getTranslationUnitDecl(),
3857 SourceLocation(), SourceLocation(),
3858 &Context->Idents.get(StructTagName));
3859 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3860 ObjCIvarDecl *Ivar = IVars[i];
3861 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3862 &Context->Idents.get(Ivar->getName()),
3863 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003864 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3865 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003866 }
3867 RD->completeDefinition();
3868 return Context->getTagDeclType(RD);
3869}
3870
3871QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3872 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3873 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3874 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3875 if (GroupRecordType.count(tuple))
3876 return GroupRecordType[tuple];
3877
3878 SmallVector<ObjCIvarDecl *, 8> IVars;
3879 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3880 IVD; IVD = IVD->getNextIvar()) {
3881 if (IVD->isBitField())
3882 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3883 else {
3884 if (!IVars.empty()) {
3885 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3886 // Generate the struct type for this group of bitfield ivars.
3887 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3888 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3889 IVars.clear();
3890 }
3891 }
3892 }
3893 if (!IVars.empty()) {
3894 // Do the last one.
3895 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3896 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3897 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3898 }
3899 QualType RetQT = GroupRecordType[tuple];
3900 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3901
3902 return RetQT;
3903}
3904
3905/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3906/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3907void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3908 std::string &Result) {
3909 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3910 Result += CDecl->getName();
3911 Result += "__GRBF_";
3912 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3913 Result += utostr(GroupNo);
3914 return;
3915}
3916
3917/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3918/// Name of the struct would be: classname__T_n where n is the group number for
3919/// this ivar.
3920void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3921 std::string &Result) {
3922 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3923 Result += CDecl->getName();
3924 Result += "__T_";
3925 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3926 Result += utostr(GroupNo);
3927 return;
3928}
3929
3930/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3931/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3932/// this ivar.
3933void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3934 std::string &Result) {
3935 Result += "OBJC_IVAR_$_";
3936 ObjCIvarBitfieldGroupDecl(IV, Result);
3937}
3938
3939#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3940 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3941 ++IX; \
3942 if (IX < ENDIX) \
3943 --IX; \
3944}
3945
Fariborz Jahanian11671902012-02-07 17:11:38 +00003946/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3947/// an objective-c class with ivars.
3948void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3949 std::string &Result) {
3950 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3951 assert(CDecl->getName() != "" &&
3952 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003953 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003954 SmallVector<ObjCIvarDecl *, 8> IVars;
3955 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003956 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003957 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003958
Fariborz Jahanian11671902012-02-07 17:11:38 +00003959 SourceLocation LocStart = CDecl->getLocStart();
3960 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003961
Fariborz Jahanian11671902012-02-07 17:11:38 +00003962 const char *startBuf = SM->getCharacterData(LocStart);
3963 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003964
Fariborz Jahanian11671902012-02-07 17:11:38 +00003965 // If no ivars and no root or if its root, directly or indirectly,
3966 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003967 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003968 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3969 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3970 ReplaceText(LocStart, endBuf-startBuf, Result);
3971 return;
3972 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003973
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003974 // Insert named struct/union definitions inside class to
3975 // outer scope. This follows semantics of locally defined
3976 // struct/unions in objective-c classes.
3977 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3978 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003979
3980 // Insert named structs which are syntheized to group ivar bitfields
3981 // to outer scope as well.
3982 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3983 if (IVars[i]->isBitField()) {
3984 ObjCIvarDecl *IV = IVars[i];
3985 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3986 RewriteObjCFieldDeclType(QT, Result);
3987 Result += ";";
3988 // skip over ivar bitfields in this group.
3989 SKIP_BITFIELDS(i , e, IVars);
3990 }
3991
Fariborz Jahanian11671902012-02-07 17:11:38 +00003992 Result += "\nstruct ";
3993 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003994 Result += "_IMPL {\n";
3995
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003996 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003997 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3998 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3999 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004000 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004001
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004002 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4003 if (IVars[i]->isBitField()) {
4004 ObjCIvarDecl *IV = IVars[i];
4005 Result += "\tstruct ";
4006 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4007 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4008 // skip over ivar bitfields in this group.
4009 SKIP_BITFIELDS(i , e, IVars);
4010 }
4011 else
4012 RewriteObjCFieldDecl(IVars[i], Result);
4013 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004014
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004015 Result += "};\n";
4016 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4017 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004018 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00004019 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004020 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004021}
4022
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004023/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4024/// have been referenced in an ivar access expression.
4025void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4026 std::string &Result) {
4027 // write out ivar offset symbols which have been referenced in an ivar
4028 // access expression.
4029 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4030 if (Ivars.empty())
4031 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004032
4033 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00004034 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004035 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4036 unsigned GroupNo = 0;
4037 if (IvarDecl->isBitField()) {
4038 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4039 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4040 continue;
4041 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004042 Result += "\n";
4043 if (LangOpts.MicrosoftExt)
4044 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004045 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004046 if (LangOpts.MicrosoftExt &&
4047 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004048 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4049 Result += "__declspec(dllimport) ";
4050
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004051 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004052 if (IvarDecl->isBitField()) {
4053 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4054 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4055 }
4056 else
4057 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004058 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004059 }
4060}
4061
Fariborz Jahanian11671902012-02-07 17:11:38 +00004062//===----------------------------------------------------------------------===//
4063// Meta Data Emission
4064//===----------------------------------------------------------------------===//
4065
4066
4067/// RewriteImplementations - This routine rewrites all method implementations
4068/// and emits meta-data.
4069
4070void RewriteModernObjC::RewriteImplementations() {
4071 int ClsDefCount = ClassImplementation.size();
4072 int CatDefCount = CategoryImplementation.size();
4073
4074 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004075 for (int i = 0; i < ClsDefCount; i++) {
4076 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4077 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4078 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004079 assert(false &&
4080 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004081 RewriteImplementationDecl(OIMP);
4082 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004083
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004084 for (int i = 0; i < CatDefCount; i++) {
4085 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4086 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4087 if (CDecl->isImplicitInterfaceDecl())
4088 assert(false &&
4089 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004090 RewriteImplementationDecl(CIMP);
4091 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004092}
4093
4094void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4095 const std::string &Name,
4096 ValueDecl *VD, bool def) {
4097 assert(BlockByRefDeclNo.count(VD) &&
4098 "RewriteByRefString: ByRef decl missing");
4099 if (def)
4100 ResultStr += "struct ";
4101 ResultStr += "__Block_byref_" + Name +
4102 "_" + utostr(BlockByRefDeclNo[VD]) ;
4103}
4104
4105static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4106 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4107 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4108 return false;
4109}
4110
4111std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4112 StringRef funcName,
4113 std::string Tag) {
4114 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004115 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004116 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004117 SourceLocation BlockLoc = CE->getExprLoc();
4118 std::string S;
4119 ConvertSourceLocationToLineDirective(BlockLoc, S);
4120
4121 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4122 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004123
4124 BlockDecl *BD = CE->getBlockDecl();
4125
4126 if (isa<FunctionNoProtoType>(AFT)) {
4127 // No user-supplied arguments. Still need to pass in a pointer to the
4128 // block (to reference imported block decl refs).
4129 S += "(" + StructRef + " *__cself)";
4130 } else if (BD->param_empty()) {
4131 S += "(" + StructRef + " *__cself)";
4132 } else {
4133 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4134 assert(FT && "SynthesizeBlockFunc: No function proto");
4135 S += '(';
4136 // first add the implicit argument.
4137 S += StructRef + " *__cself, ";
4138 std::string ParamStr;
4139 for (BlockDecl::param_iterator AI = BD->param_begin(),
4140 E = BD->param_end(); AI != E; ++AI) {
4141 if (AI != BD->param_begin()) S += ", ";
4142 ParamStr = (*AI)->getNameAsString();
4143 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004144 (void)convertBlockPointerToFunctionPointer(QT);
4145 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004146 S += ParamStr;
4147 }
4148 if (FT->isVariadic()) {
4149 if (!BD->param_empty()) S += ", ";
4150 S += "...";
4151 }
4152 S += ')';
4153 }
4154 S += " {\n";
4155
4156 // Create local declarations to avoid rewriting all closure decl ref exprs.
4157 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004158 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159 E = BlockByRefDecls.end(); I != E; ++I) {
4160 S += " ";
4161 std::string Name = (*I)->getNameAsString();
4162 std::string TypeString;
4163 RewriteByRefString(TypeString, Name, (*I));
4164 TypeString += " *";
4165 Name = TypeString + Name;
4166 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4167 }
4168 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004169 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004170 E = BlockByCopyDecls.end(); I != E; ++I) {
4171 S += " ";
4172 // Handle nested closure invocation. For example:
4173 //
4174 // void (^myImportedClosure)(void);
4175 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4176 //
4177 // void (^anotherClosure)(void);
4178 // anotherClosure = ^(void) {
4179 // myImportedClosure(); // import and invoke the closure
4180 // };
4181 //
4182 if (isTopLevelBlockPointerType((*I)->getType())) {
4183 RewriteBlockPointerTypeVariable(S, (*I));
4184 S += " = (";
4185 RewriteBlockPointerType(S, (*I)->getType());
4186 S += ")";
4187 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4188 }
4189 else {
4190 std::string Name = (*I)->getNameAsString();
4191 QualType QT = (*I)->getType();
4192 if (HasLocalVariableExternalStorage(*I))
4193 QT = Context->getPointerType(QT);
4194 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4195 S += Name + " = __cself->" +
4196 (*I)->getNameAsString() + "; // bound by copy\n";
4197 }
4198 }
4199 std::string RewrittenStr = RewrittenBlockExprs[CE];
4200 const char *cstr = RewrittenStr.c_str();
4201 while (*cstr++ != '{') ;
4202 S += cstr;
4203 S += "\n";
4204 return S;
4205}
4206
4207std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4208 StringRef funcName,
4209 std::string Tag) {
4210 std::string StructRef = "struct " + Tag;
4211 std::string S = "static void __";
4212
4213 S += funcName;
4214 S += "_block_copy_" + utostr(i);
4215 S += "(" + StructRef;
4216 S += "*dst, " + StructRef;
4217 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004218 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004219 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004220 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004221 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004222 S += VD->getNameAsString();
4223 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004224 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4225 else if (VD->getType()->isBlockPointerType())
4226 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4227 else
4228 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4229 }
4230 S += "}\n";
4231
4232 S += "\nstatic void __";
4233 S += funcName;
4234 S += "_block_dispose_" + utostr(i);
4235 S += "(" + StructRef;
4236 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004237 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004238 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004239 S += VD->getNameAsString();
4240 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004241 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4242 else if (VD->getType()->isBlockPointerType())
4243 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4244 else
4245 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4246 }
4247 S += "}\n";
4248 return S;
4249}
4250
4251std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4252 std::string Desc) {
4253 std::string S = "\nstruct " + Tag;
4254 std::string Constructor = " " + Tag;
4255
4256 S += " {\n struct __block_impl impl;\n";
4257 S += " struct " + Desc;
4258 S += "* Desc;\n";
4259
4260 Constructor += "(void *fp, "; // Invoke function pointer.
4261 Constructor += "struct " + Desc; // Descriptor pointer.
4262 Constructor += " *desc";
4263
4264 if (BlockDeclRefs.size()) {
4265 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004266 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004267 E = BlockByCopyDecls.end(); I != E; ++I) {
4268 S += " ";
4269 std::string FieldName = (*I)->getNameAsString();
4270 std::string ArgName = "_" + FieldName;
4271 // Handle nested closure invocation. For example:
4272 //
4273 // void (^myImportedBlock)(void);
4274 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4275 //
4276 // void (^anotherBlock)(void);
4277 // anotherBlock = ^(void) {
4278 // myImportedBlock(); // import and invoke the closure
4279 // };
4280 //
4281 if (isTopLevelBlockPointerType((*I)->getType())) {
4282 S += "struct __block_impl *";
4283 Constructor += ", void *" + ArgName;
4284 } else {
4285 QualType QT = (*I)->getType();
4286 if (HasLocalVariableExternalStorage(*I))
4287 QT = Context->getPointerType(QT);
4288 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4289 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4290 Constructor += ", " + ArgName;
4291 }
4292 S += FieldName + ";\n";
4293 }
4294 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004295 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004296 E = BlockByRefDecls.end(); I != E; ++I) {
4297 S += " ";
4298 std::string FieldName = (*I)->getNameAsString();
4299 std::string ArgName = "_" + FieldName;
4300 {
4301 std::string TypeString;
4302 RewriteByRefString(TypeString, FieldName, (*I));
4303 TypeString += " *";
4304 FieldName = TypeString + FieldName;
4305 ArgName = TypeString + ArgName;
4306 Constructor += ", " + ArgName;
4307 }
4308 S += FieldName + "; // by ref\n";
4309 }
4310 // Finish writing the constructor.
4311 Constructor += ", int flags=0)";
4312 // Initialize all "by copy" arguments.
4313 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004315 E = BlockByCopyDecls.end(); I != E; ++I) {
4316 std::string Name = (*I)->getNameAsString();
4317 if (firsTime) {
4318 Constructor += " : ";
4319 firsTime = false;
4320 }
4321 else
4322 Constructor += ", ";
4323 if (isTopLevelBlockPointerType((*I)->getType()))
4324 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4325 else
4326 Constructor += Name + "(_" + Name + ")";
4327 }
4328 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004329 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004330 E = BlockByRefDecls.end(); I != E; ++I) {
4331 std::string Name = (*I)->getNameAsString();
4332 if (firsTime) {
4333 Constructor += " : ";
4334 firsTime = false;
4335 }
4336 else
4337 Constructor += ", ";
4338 Constructor += Name + "(_" + Name + "->__forwarding)";
4339 }
4340
4341 Constructor += " {\n";
4342 if (GlobalVarDecl)
4343 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4344 else
4345 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4346 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4347
4348 Constructor += " Desc = desc;\n";
4349 } else {
4350 // Finish writing the constructor.
4351 Constructor += ", int flags=0) {\n";
4352 if (GlobalVarDecl)
4353 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4354 else
4355 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4356 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4357 Constructor += " Desc = desc;\n";
4358 }
4359 Constructor += " ";
4360 Constructor += "}\n";
4361 S += Constructor;
4362 S += "};\n";
4363 return S;
4364}
4365
4366std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4367 std::string ImplTag, int i,
4368 StringRef FunName,
4369 unsigned hasCopy) {
4370 std::string S = "\nstatic struct " + DescTag;
4371
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004372 S += " {\n size_t reserved;\n";
4373 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004374 if (hasCopy) {
4375 S += " void (*copy)(struct ";
4376 S += ImplTag; S += "*, struct ";
4377 S += ImplTag; S += "*);\n";
4378
4379 S += " void (*dispose)(struct ";
4380 S += ImplTag; S += "*);\n";
4381 }
4382 S += "} ";
4383
4384 S += DescTag + "_DATA = { 0, sizeof(struct ";
4385 S += ImplTag + ")";
4386 if (hasCopy) {
4387 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4388 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4389 }
4390 S += "};\n";
4391 return S;
4392}
4393
4394void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4395 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004396 bool RewriteSC = (GlobalVarDecl &&
4397 !Blocks.empty() &&
4398 GlobalVarDecl->getStorageClass() == SC_Static &&
4399 GlobalVarDecl->getType().getCVRQualifiers());
4400 if (RewriteSC) {
4401 std::string SC(" void __");
4402 SC += GlobalVarDecl->getNameAsString();
4403 SC += "() {}";
4404 InsertText(FunLocStart, SC);
4405 }
4406
4407 // Insert closures that were part of the function.
4408 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4409 CollectBlockDeclRefInfo(Blocks[i]);
4410 // Need to copy-in the inner copied-in variables not actually used in this
4411 // block.
4412 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004413 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004414 ValueDecl *VD = Exp->getDecl();
4415 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004416 if (!VD->hasAttr<BlocksAttr>()) {
4417 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4418 BlockByCopyDeclsPtrSet.insert(VD);
4419 BlockByCopyDecls.push_back(VD);
4420 }
4421 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004422 }
John McCall113bee02012-03-10 09:33:50 +00004423
4424 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004425 BlockByRefDeclsPtrSet.insert(VD);
4426 BlockByRefDecls.push_back(VD);
4427 }
John McCall113bee02012-03-10 09:33:50 +00004428
Fariborz Jahanian11671902012-02-07 17:11:38 +00004429 // imported objects in the inner blocks not used in the outer
4430 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004431 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004432 VD->getType()->isBlockPointerType())
4433 ImportedBlockDecls.insert(VD);
4434 }
4435
4436 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4437 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4438
4439 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4440
4441 InsertText(FunLocStart, CI);
4442
4443 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4444
4445 InsertText(FunLocStart, CF);
4446
4447 if (ImportedBlockDecls.size()) {
4448 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4449 InsertText(FunLocStart, HF);
4450 }
4451 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4452 ImportedBlockDecls.size() > 0);
4453 InsertText(FunLocStart, BD);
4454
4455 BlockDeclRefs.clear();
4456 BlockByRefDecls.clear();
4457 BlockByRefDeclsPtrSet.clear();
4458 BlockByCopyDecls.clear();
4459 BlockByCopyDeclsPtrSet.clear();
4460 ImportedBlockDecls.clear();
4461 }
4462 if (RewriteSC) {
4463 // Must insert any 'const/volatile/static here. Since it has been
4464 // removed as result of rewriting of block literals.
4465 std::string SC;
4466 if (GlobalVarDecl->getStorageClass() == SC_Static)
4467 SC = "static ";
4468 if (GlobalVarDecl->getType().isConstQualified())
4469 SC += "const ";
4470 if (GlobalVarDecl->getType().isVolatileQualified())
4471 SC += "volatile ";
4472 if (GlobalVarDecl->getType().isRestrictQualified())
4473 SC += "restrict ";
4474 InsertText(FunLocStart, SC);
4475 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004476 if (GlobalConstructionExp) {
4477 // extra fancy dance for global literal expression.
4478
4479 // Always the latest block expression on the block stack.
4480 std::string Tag = "__";
4481 Tag += FunName;
4482 Tag += "_block_impl_";
4483 Tag += utostr(Blocks.size()-1);
4484 std::string globalBuf = "static ";
4485 globalBuf += Tag; globalBuf += " ";
4486 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004487
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004488 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004489 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4490 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004491 globalBuf += constructorExprBuf.str();
4492 globalBuf += ";\n";
4493 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004494 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004495 }
4496
Fariborz Jahanian11671902012-02-07 17:11:38 +00004497 Blocks.clear();
4498 InnerDeclRefsCount.clear();
4499 InnerDeclRefs.clear();
4500 RewrittenBlockExprs.clear();
4501}
4502
4503void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004504 SourceLocation FunLocStart =
4505 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4506 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004507 StringRef FuncName = FD->getName();
4508
4509 SynthesizeBlockLiterals(FunLocStart, FuncName);
4510}
4511
4512static void BuildUniqueMethodName(std::string &Name,
4513 ObjCMethodDecl *MD) {
4514 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4515 Name = IFace->getName();
4516 Name += "__" + MD->getSelector().getAsString();
4517 // Convert colons to underscores.
4518 std::string::size_type loc = 0;
4519 while ((loc = Name.find(":", loc)) != std::string::npos)
4520 Name.replace(loc, 1, "_");
4521}
4522
4523void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4524 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4525 //SourceLocation FunLocStart = MD->getLocStart();
4526 SourceLocation FunLocStart = MD->getLocStart();
4527 std::string FuncName;
4528 BuildUniqueMethodName(FuncName, MD);
4529 SynthesizeBlockLiterals(FunLocStart, FuncName);
4530}
4531
4532void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004533 for (Stmt *SubStmt : S->children())
4534 if (SubStmt) {
4535 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004536 GetBlockDeclRefExprs(CBE->getBody());
4537 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004538 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004539 }
4540 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004541 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004542 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004543 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004544 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004545 BlockDeclRefs.push_back(DRE);
4546
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547 return;
4548}
4549
Craig Topper5603df42013-07-05 19:34:19 +00004550void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4551 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004552 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004553 for (Stmt *SubStmt : S->children())
4554 if (SubStmt) {
4555 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004556 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4557 GetInnerBlockDeclRefExprs(CBE->getBody(),
4558 InnerBlockDeclRefs,
4559 InnerContexts);
4560 }
4561 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004562 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004563 }
4564 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004566 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004567 HasLocalVariableExternalStorage(DRE->getDecl())) {
4568 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004569 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004570 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004571 if (Var->isFunctionOrMethodVarDecl())
4572 ImportedLocalExternalDecls.insert(Var);
4573 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004574 }
4575
4576 return;
4577}
4578
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004579/// convertObjCTypeToCStyleType - This routine converts such objc types
4580/// as qualified objects, and blocks to their closest c/c++ types that
4581/// it can. It returns true if input type was modified.
4582bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4583 QualType oldT = T;
4584 convertBlockPointerToFunctionPointer(T);
4585 if (T->isFunctionPointerType()) {
4586 QualType PointeeTy;
4587 if (const PointerType* PT = T->getAs<PointerType>()) {
4588 PointeeTy = PT->getPointeeType();
4589 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4590 T = convertFunctionTypeOfBlocks(FT);
4591 T = Context->getPointerType(T);
4592 }
4593 }
4594 }
4595
4596 convertToUnqualifiedObjCType(T);
4597 return T != oldT;
4598}
4599
Fariborz Jahanian11671902012-02-07 17:11:38 +00004600/// convertFunctionTypeOfBlocks - This routine converts a function type
4601/// whose result type may be a block pointer or whose argument type(s)
4602/// might be block pointers to an equivalent function type replacing
4603/// all block pointers to function pointers.
4604QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4605 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4606 // FTP will be null for closures that don't take arguments.
4607 // Generate a funky cast.
4608 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004609 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004610 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004611
4612 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004613 for (auto &I : FTP->param_types()) {
4614 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004615 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004616 if (convertObjCTypeToCStyleType(t))
4617 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004618 ArgTypes.push_back(t);
4619 }
4620 }
4621 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004622 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004623 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004624 else FuncType = QualType(FT, 0);
4625 return FuncType;
4626}
4627
4628Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4629 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004630 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004631
4632 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4633 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004634 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4635 CPT = MExpr->getType()->getAs<BlockPointerType>();
4636 }
4637 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4638 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4639 }
4640 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4641 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4642 else if (const ConditionalOperator *CEXPR =
4643 dyn_cast<ConditionalOperator>(BlockExp)) {
4644 Expr *LHSExp = CEXPR->getLHS();
4645 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4646 Expr *RHSExp = CEXPR->getRHS();
4647 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4648 Expr *CONDExp = CEXPR->getCond();
4649 ConditionalOperator *CondExpr =
4650 new (Context) ConditionalOperator(CONDExp,
4651 SourceLocation(), cast<Expr>(LHSStmt),
4652 SourceLocation(), cast<Expr>(RHSStmt),
4653 Exp->getType(), VK_RValue, OK_Ordinary);
4654 return CondExpr;
4655 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4656 CPT = IRE->getType()->getAs<BlockPointerType>();
4657 } else if (const PseudoObjectExpr *POE
4658 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4659 CPT = POE->getType()->castAs<BlockPointerType>();
4660 } else {
4661 assert(1 && "RewriteBlockClass: Bad type");
4662 }
4663 assert(CPT && "RewriteBlockClass: Bad type");
4664 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4665 assert(FT && "RewriteBlockClass: Bad type");
4666 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4667 // FTP will be null for closures that don't take arguments.
4668
4669 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4670 SourceLocation(), SourceLocation(),
4671 &Context->Idents.get("__block_impl"));
4672 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4673
4674 // Generate a funky cast.
4675 SmallVector<QualType, 8> ArgTypes;
4676
4677 // Push the block argument type.
4678 ArgTypes.push_back(PtrBlock);
4679 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004680 for (auto &I : FTP->param_types()) {
4681 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004682 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4683 if (!convertBlockPointerToFunctionPointer(t))
4684 convertToUnqualifiedObjCType(t);
4685 ArgTypes.push_back(t);
4686 }
4687 }
4688 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004689 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004690
4691 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4692
4693 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4694 CK_BitCast,
4695 const_cast<Expr*>(BlockExp));
4696 // Don't forget the parens to enforce the proper binding.
4697 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4698 BlkCast);
4699 //PE->dump();
4700
Craig Topper8ae12032014-05-07 06:21:57 +00004701 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004702 SourceLocation(),
4703 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004704 Context->VoidPtrTy, nullptr,
4705 /*BitWidth=*/nullptr, /*Mutable=*/true,
4706 ICIS_NoInit);
4707 MemberExpr *ME =
4708 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4709 FD->getType(), VK_LValue, OK_Ordinary);
4710
4711 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4712 CK_BitCast, ME);
4713 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004714
4715 SmallVector<Expr*, 8> BlkExprs;
4716 // Add the implicit argument.
4717 BlkExprs.push_back(BlkCast);
4718 // Add the user arguments.
4719 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4720 E = Exp->arg_end(); I != E; ++I) {
4721 BlkExprs.push_back(*I);
4722 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004723 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004724 Exp->getType(), VK_RValue,
4725 SourceLocation());
4726 return CE;
4727}
4728
4729// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004730// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004731// For example:
4732//
4733// int main() {
4734// __block Foo *f;
4735// __block int i;
4736//
4737// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004738// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004739// i = 77;
4740// };
4741//}
John McCall113bee02012-03-10 09:33:50 +00004742Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004743 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4744 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004745 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004746 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004747 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004748
4749 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004750 SourceLocation(),
4751 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004752 Context->VoidPtrTy, nullptr,
4753 /*BitWidth=*/nullptr, /*Mutable=*/true,
4754 ICIS_NoInit);
4755 MemberExpr *ME = new (Context)
4756 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4757 FD->getType(), VK_LValue, OK_Ordinary);
4758
4759 StringRef Name = VD->getName();
4760 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004761 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004762 Context->VoidPtrTy, nullptr,
4763 /*BitWidth=*/nullptr, /*Mutable=*/true,
4764 ICIS_NoInit);
4765 ME =
4766 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4767 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4768
4769 // Need parens to enforce precedence.
4770 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4771 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004772 ME);
4773 ReplaceStmt(DeclRefExp, PE);
4774 return PE;
4775}
4776
4777// Rewrites the imported local variable V with external storage
4778// (static, extern, etc.) as *V
4779//
4780Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4781 ValueDecl *VD = DRE->getDecl();
4782 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4783 if (!ImportedLocalExternalDecls.count(Var))
4784 return DRE;
4785 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4786 VK_LValue, OK_Ordinary,
4787 DRE->getLocation());
4788 // Need parens to enforce precedence.
4789 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4790 Exp);
4791 ReplaceStmt(DRE, PE);
4792 return PE;
4793}
4794
4795void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4796 SourceLocation LocStart = CE->getLParenLoc();
4797 SourceLocation LocEnd = CE->getRParenLoc();
4798
4799 // Need to avoid trying to rewrite synthesized casts.
4800 if (LocStart.isInvalid())
4801 return;
4802 // Need to avoid trying to rewrite casts contained in macros.
4803 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4804 return;
4805
4806 const char *startBuf = SM->getCharacterData(LocStart);
4807 const char *endBuf = SM->getCharacterData(LocEnd);
4808 QualType QT = CE->getType();
4809 const Type* TypePtr = QT->getAs<Type>();
4810 if (isa<TypeOfExprType>(TypePtr)) {
4811 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4812 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4813 std::string TypeAsString = "(";
4814 RewriteBlockPointerType(TypeAsString, QT);
4815 TypeAsString += ")";
4816 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4817 return;
4818 }
4819 // advance the location to startArgList.
4820 const char *argPtr = startBuf;
4821
4822 while (*argPtr++ && (argPtr < endBuf)) {
4823 switch (*argPtr) {
4824 case '^':
4825 // Replace the '^' with '*'.
4826 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4827 ReplaceText(LocStart, 1, "*");
4828 break;
4829 }
4830 }
4831 return;
4832}
4833
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004834void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4835 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004836 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4837 CastKind != CK_AnyPointerToBlockPointerCast)
4838 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004839
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004840 QualType QT = IC->getType();
4841 (void)convertBlockPointerToFunctionPointer(QT);
4842 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4843 std::string Str = "(";
4844 Str += TypeString;
4845 Str += ")";
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004846 InsertText(IC->getSubExpr()->getLocStart(), Str);
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004847
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004848 return;
4849}
4850
Fariborz Jahanian11671902012-02-07 17:11:38 +00004851void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4852 SourceLocation DeclLoc = FD->getLocation();
4853 unsigned parenCount = 0;
4854
4855 // We have 1 or more arguments that have closure pointers.
4856 const char *startBuf = SM->getCharacterData(DeclLoc);
4857 const char *startArgList = strchr(startBuf, '(');
4858
4859 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4860
4861 parenCount++;
4862 // advance the location to startArgList.
4863 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4864 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4865
4866 const char *argPtr = startArgList;
4867
4868 while (*argPtr++ && parenCount) {
4869 switch (*argPtr) {
4870 case '^':
4871 // Replace the '^' with '*'.
4872 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4873 ReplaceText(DeclLoc, 1, "*");
4874 break;
4875 case '(':
4876 parenCount++;
4877 break;
4878 case ')':
4879 parenCount--;
4880 break;
4881 }
4882 }
4883 return;
4884}
4885
4886bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4887 const FunctionProtoType *FTP;
4888 const PointerType *PT = QT->getAs<PointerType>();
4889 if (PT) {
4890 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4891 } else {
4892 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4893 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4894 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4895 }
4896 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004897 for (const auto &I : FTP->param_types())
4898 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004899 return true;
4900 }
4901 return false;
4902}
4903
4904bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4905 const FunctionProtoType *FTP;
4906 const PointerType *PT = QT->getAs<PointerType>();
4907 if (PT) {
4908 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4909 } else {
4910 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4911 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4912 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4913 }
4914 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004915 for (const auto &I : FTP->param_types()) {
4916 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004917 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004918 if (I->isObjCObjectPointerType() &&
4919 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004920 return true;
4921 }
4922
4923 }
4924 return false;
4925}
4926
4927void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4928 const char *&RParen) {
4929 const char *argPtr = strchr(Name, '(');
4930 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4931
4932 LParen = argPtr; // output the start.
4933 argPtr++; // skip past the left paren.
4934 unsigned parenCount = 1;
4935
4936 while (*argPtr && parenCount) {
4937 switch (*argPtr) {
4938 case '(': parenCount++; break;
4939 case ')': parenCount--; break;
4940 default: break;
4941 }
4942 if (parenCount) argPtr++;
4943 }
4944 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4945 RParen = argPtr; // output the end
4946}
4947
4948void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4949 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4950 RewriteBlockPointerFunctionArgs(FD);
4951 return;
4952 }
4953 // Handle Variables and Typedefs.
4954 SourceLocation DeclLoc = ND->getLocation();
4955 QualType DeclT;
4956 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4957 DeclT = VD->getType();
4958 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4959 DeclT = TDD->getUnderlyingType();
4960 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4961 DeclT = FD->getType();
4962 else
4963 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4964
4965 const char *startBuf = SM->getCharacterData(DeclLoc);
4966 const char *endBuf = startBuf;
4967 // scan backward (from the decl location) for the end of the previous decl.
4968 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4969 startBuf--;
4970 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4971 std::string buf;
4972 unsigned OrigLength=0;
4973 // *startBuf != '^' if we are dealing with a pointer to function that
4974 // may take block argument types (which will be handled below).
4975 if (*startBuf == '^') {
4976 // Replace the '^' with '*', computing a negative offset.
4977 buf = '*';
4978 startBuf++;
4979 OrigLength++;
4980 }
4981 while (*startBuf != ')') {
4982 buf += *startBuf;
4983 startBuf++;
4984 OrigLength++;
4985 }
4986 buf += ')';
4987 OrigLength++;
4988
4989 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4990 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4991 // Replace the '^' with '*' for arguments.
4992 // Replace id<P> with id/*<>*/
4993 DeclLoc = ND->getLocation();
4994 startBuf = SM->getCharacterData(DeclLoc);
4995 const char *argListBegin, *argListEnd;
4996 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4997 while (argListBegin < argListEnd) {
4998 if (*argListBegin == '^')
4999 buf += '*';
5000 else if (*argListBegin == '<') {
5001 buf += "/*";
5002 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005003 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005004 while (*argListBegin != '>') {
5005 buf += *argListBegin++;
5006 OrigLength++;
5007 }
5008 buf += *argListBegin;
5009 buf += "*/";
5010 }
5011 else
5012 buf += *argListBegin;
5013 argListBegin++;
5014 OrigLength++;
5015 }
5016 buf += ')';
5017 OrigLength++;
5018 }
5019 ReplaceText(Start, OrigLength, buf);
5020
5021 return;
5022}
5023
5024
5025/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5026/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5027/// struct Block_byref_id_object *src) {
5028/// _Block_object_assign (&_dest->object, _src->object,
5029/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5030/// [|BLOCK_FIELD_IS_WEAK]) // object
5031/// _Block_object_assign(&_dest->object, _src->object,
5032/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5033/// [|BLOCK_FIELD_IS_WEAK]) // block
5034/// }
5035/// And:
5036/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5037/// _Block_object_dispose(_src->object,
5038/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5039/// [|BLOCK_FIELD_IS_WEAK]) // object
5040/// _Block_object_dispose(_src->object,
5041/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5042/// [|BLOCK_FIELD_IS_WEAK]) // block
5043/// }
5044
5045std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5046 int flag) {
5047 std::string S;
5048 if (CopyDestroyCache.count(flag))
5049 return S;
5050 CopyDestroyCache.insert(flag);
5051 S = "static void __Block_byref_id_object_copy_";
5052 S += utostr(flag);
5053 S += "(void *dst, void *src) {\n";
5054
5055 // offset into the object pointer is computed as:
5056 // void * + void* + int + int + void* + void *
5057 unsigned IntSize =
5058 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5059 unsigned VoidPtrSize =
5060 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5061
5062 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5063 S += " _Block_object_assign((char*)dst + ";
5064 S += utostr(offset);
5065 S += ", *(void * *) ((char*)src + ";
5066 S += utostr(offset);
5067 S += "), ";
5068 S += utostr(flag);
5069 S += ");\n}\n";
5070
5071 S += "static void __Block_byref_id_object_dispose_";
5072 S += utostr(flag);
5073 S += "(void *src) {\n";
5074 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5075 S += utostr(offset);
5076 S += "), ";
5077 S += utostr(flag);
5078 S += ");\n}\n";
5079 return S;
5080}
5081
5082/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5083/// the declaration into:
5084/// struct __Block_byref_ND {
5085/// void *__isa; // NULL for everything except __weak pointers
5086/// struct __Block_byref_ND *__forwarding;
5087/// int32_t __flags;
5088/// int32_t __size;
5089/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5090/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5091/// typex ND;
5092/// };
5093///
5094/// It then replaces declaration of ND variable with:
5095/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5096/// __size=sizeof(struct __Block_byref_ND),
5097/// ND=initializer-if-any};
5098///
5099///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005100void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5101 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005102 int flag = 0;
5103 int isa = 0;
5104 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5105 if (DeclLoc.isInvalid())
5106 // If type location is missing, it is because of missing type (a warning).
5107 // Use variable's location which is good for this case.
5108 DeclLoc = ND->getLocation();
5109 const char *startBuf = SM->getCharacterData(DeclLoc);
5110 SourceLocation X = ND->getLocEnd();
5111 X = SM->getExpansionLoc(X);
5112 const char *endBuf = SM->getCharacterData(X);
5113 std::string Name(ND->getNameAsString());
5114 std::string ByrefType;
5115 RewriteByRefString(ByrefType, Name, ND, true);
5116 ByrefType += " {\n";
5117 ByrefType += " void *__isa;\n";
5118 RewriteByRefString(ByrefType, Name, ND);
5119 ByrefType += " *__forwarding;\n";
5120 ByrefType += " int __flags;\n";
5121 ByrefType += " int __size;\n";
5122 // Add void *__Block_byref_id_object_copy;
5123 // void *__Block_byref_id_object_dispose; if needed.
5124 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005125 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005126 if (HasCopyAndDispose) {
5127 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5128 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5129 }
5130
5131 QualType T = Ty;
5132 (void)convertBlockPointerToFunctionPointer(T);
5133 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5134
5135 ByrefType += " " + Name + ";\n";
5136 ByrefType += "};\n";
5137 // Insert this type in global scope. It is needed by helper function.
5138 SourceLocation FunLocStart;
5139 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005140 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005141 else {
5142 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5143 FunLocStart = CurMethodDef->getLocStart();
5144 }
5145 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005146
Fariborz Jahanian11671902012-02-07 17:11:38 +00005147 if (Ty.isObjCGCWeak()) {
5148 flag |= BLOCK_FIELD_IS_WEAK;
5149 isa = 1;
5150 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005151 if (HasCopyAndDispose) {
5152 flag = BLOCK_BYREF_CALLER;
5153 QualType Ty = ND->getType();
5154 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5155 if (Ty->isBlockPointerType())
5156 flag |= BLOCK_FIELD_IS_BLOCK;
5157 else
5158 flag |= BLOCK_FIELD_IS_OBJECT;
5159 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5160 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005161 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005162 }
5163
5164 // struct __Block_byref_ND ND =
5165 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5166 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005167 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005168 // FIXME. rewriter does not support __block c++ objects which
5169 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005170 if (hasInit)
5171 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5172 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5173 if (CXXDecl && CXXDecl->isDefaultConstructor())
5174 hasInit = false;
5175 }
5176
Fariborz Jahanian11671902012-02-07 17:11:38 +00005177 unsigned flags = 0;
5178 if (HasCopyAndDispose)
5179 flags |= BLOCK_HAS_COPY_DISPOSE;
5180 Name = ND->getNameAsString();
5181 ByrefType.clear();
5182 RewriteByRefString(ByrefType, Name, ND);
5183 std::string ForwardingCastType("(");
5184 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005185 ByrefType += " " + Name + " = {(void*)";
5186 ByrefType += utostr(isa);
5187 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5188 ByrefType += utostr(flags);
5189 ByrefType += ", ";
5190 ByrefType += "sizeof(";
5191 RewriteByRefString(ByrefType, Name, ND);
5192 ByrefType += ")";
5193 if (HasCopyAndDispose) {
5194 ByrefType += ", __Block_byref_id_object_copy_";
5195 ByrefType += utostr(flag);
5196 ByrefType += ", __Block_byref_id_object_dispose_";
5197 ByrefType += utostr(flag);
5198 }
5199
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005200 if (!firstDecl) {
5201 // In multiple __block declarations, and for all but 1st declaration,
5202 // find location of the separating comma. This would be start location
5203 // where new text is to be inserted.
5204 DeclLoc = ND->getLocation();
5205 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5206 const char *commaBuf = startDeclBuf;
5207 while (*commaBuf != ',')
5208 commaBuf--;
5209 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5210 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5211 startBuf = commaBuf;
5212 }
5213
Fariborz Jahanian11671902012-02-07 17:11:38 +00005214 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005215 ByrefType += "};\n";
5216 unsigned nameSize = Name.size();
5217 // for block or function pointer declaration. Name is aleady
5218 // part of the declaration.
5219 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5220 nameSize = 1;
5221 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5222 }
5223 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005224 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005225 SourceLocation startLoc;
5226 Expr *E = ND->getInit();
5227 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5228 startLoc = ECE->getLParenLoc();
5229 else
5230 startLoc = E->getLocStart();
5231 startLoc = SM->getExpansionLoc(startLoc);
5232 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005233 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005234
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005235 const char separator = lastDecl ? ';' : ',';
5236 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5237 const char *separatorBuf = strchr(startInitializerBuf, separator);
5238 assert((*separatorBuf == separator) &&
5239 "RewriteByRefVar: can't find ';' or ','");
5240 SourceLocation separatorLoc =
5241 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5242
5243 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005244 }
5245 return;
5246}
5247
5248void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5249 // Add initializers for any closure decl refs.
5250 GetBlockDeclRefExprs(Exp->getBody());
5251 if (BlockDeclRefs.size()) {
5252 // Unique all "by copy" declarations.
5253 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005254 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005255 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5256 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5257 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5258 }
5259 }
5260 // Unique all "by ref" declarations.
5261 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005262 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005263 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5264 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5265 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5266 }
5267 }
5268 // Find any imported blocks...they will need special attention.
5269 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005270 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005271 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5272 BlockDeclRefs[i]->getType()->isBlockPointerType())
5273 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5274 }
5275}
5276
5277FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5278 IdentifierInfo *ID = &Context->Idents.get(name);
5279 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5280 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005281 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005282 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005283}
5284
5285Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005286 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005287
Fariborz Jahanian11671902012-02-07 17:11:38 +00005288 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005289
Fariborz Jahanian11671902012-02-07 17:11:38 +00005290 Blocks.push_back(Exp);
5291
5292 CollectBlockDeclRefInfo(Exp);
5293
5294 // Add inner imported variables now used in current block.
5295 int countOfInnerDecls = 0;
5296 if (!InnerBlockDeclRefs.empty()) {
5297 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005298 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005299 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005300 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005301 // We need to save the copied-in variables in nested
5302 // blocks because it is needed at the end for some of the API generations.
5303 // See SynthesizeBlockLiterals routine.
5304 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5305 BlockDeclRefs.push_back(Exp);
5306 BlockByCopyDeclsPtrSet.insert(VD);
5307 BlockByCopyDecls.push_back(VD);
5308 }
John McCall113bee02012-03-10 09:33:50 +00005309 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005310 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5311 BlockDeclRefs.push_back(Exp);
5312 BlockByRefDeclsPtrSet.insert(VD);
5313 BlockByRefDecls.push_back(VD);
5314 }
5315 }
5316 // Find any imported blocks...they will need special attention.
5317 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005318 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005319 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5320 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5321 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5322 }
5323 InnerDeclRefsCount.push_back(countOfInnerDecls);
5324
5325 std::string FuncName;
5326
5327 if (CurFunctionDef)
5328 FuncName = CurFunctionDef->getNameAsString();
5329 else if (CurMethodDef)
5330 BuildUniqueMethodName(FuncName, CurMethodDef);
5331 else if (GlobalVarDecl)
5332 FuncName = std::string(GlobalVarDecl->getNameAsString());
5333
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005334 bool GlobalBlockExpr =
5335 block->getDeclContext()->getRedeclContext()->isFileContext();
5336
5337 if (GlobalBlockExpr && !GlobalVarDecl) {
5338 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5339 GlobalBlockExpr = false;
5340 }
5341
Fariborz Jahanian11671902012-02-07 17:11:38 +00005342 std::string BlockNumber = utostr(Blocks.size()-1);
5343
Fariborz Jahanian11671902012-02-07 17:11:38 +00005344 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5345
5346 // Get a pointer to the function type so we can cast appropriately.
5347 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5348 QualType FType = Context->getPointerType(BFT);
5349
5350 FunctionDecl *FD;
5351 Expr *NewRep;
5352
Benjamin Kramer60509af2013-09-09 14:48:42 +00005353 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005354 std::string Tag;
5355
5356 if (GlobalBlockExpr)
5357 Tag = "__global_";
5358 else
5359 Tag = "__";
5360 Tag += FuncName + "_block_impl_" + BlockNumber;
5361
Fariborz Jahanian11671902012-02-07 17:11:38 +00005362 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005363 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005364 SourceLocation());
5365
5366 SmallVector<Expr*, 4> InitExprs;
5367
5368 // Initialize the block function.
5369 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005370 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5371 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005372 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5373 CK_BitCast, Arg);
5374 InitExprs.push_back(castExpr);
5375
5376 // Initialize the block descriptor.
5377 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5378
5379 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5380 SourceLocation(), SourceLocation(),
5381 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005382 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005383 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005384 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005385 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 Context->VoidPtrTy,
5387 VK_LValue,
5388 SourceLocation()),
5389 UO_AddrOf,
5390 Context->getPointerType(Context->VoidPtrTy),
5391 VK_RValue, OK_Ordinary,
5392 SourceLocation());
5393 InitExprs.push_back(DescRefExpr);
5394
5395 // Add initializers for any closure decl refs.
5396 if (BlockDeclRefs.size()) {
5397 Expr *Exp;
5398 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005399 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005400 E = BlockByCopyDecls.end(); I != E; ++I) {
5401 if (isObjCType((*I)->getType())) {
5402 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5403 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005404 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5405 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005406 if (HasLocalVariableExternalStorage(*I)) {
5407 QualType QT = (*I)->getType();
5408 QT = Context->getPointerType(QT);
5409 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5410 OK_Ordinary, SourceLocation());
5411 }
5412 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5413 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005414 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5415 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005416 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5417 CK_BitCast, Arg);
5418 } else {
5419 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005420 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5421 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 if (HasLocalVariableExternalStorage(*I)) {
5423 QualType QT = (*I)->getType();
5424 QT = Context->getPointerType(QT);
5425 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5426 OK_Ordinary, SourceLocation());
5427 }
5428
5429 }
5430 InitExprs.push_back(Exp);
5431 }
5432 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005433 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005434 E = BlockByRefDecls.end(); I != E; ++I) {
5435 ValueDecl *ND = (*I);
5436 std::string Name(ND->getNameAsString());
5437 std::string RecName;
5438 RewriteByRefString(RecName, Name, ND, true);
5439 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5440 + sizeof("struct"));
5441 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5442 SourceLocation(), SourceLocation(),
5443 II);
5444 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5445 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5446
5447 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005448 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005449 SourceLocation());
5450 bool isNestedCapturedVar = false;
5451 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005452 for (const auto &CI : block->captures()) {
5453 const VarDecl *variable = CI.getVariable();
5454 if (variable == ND && CI.isNested()) {
5455 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005456 "SynthBlockInitExpr - captured block variable is not byref");
5457 isNestedCapturedVar = true;
5458 break;
5459 }
5460 }
5461 // captured nested byref variable has its address passed. Do not take
5462 // its address again.
5463 if (!isNestedCapturedVar)
5464 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5465 Context->getPointerType(Exp->getType()),
5466 VK_RValue, OK_Ordinary, SourceLocation());
5467 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5468 InitExprs.push_back(Exp);
5469 }
5470 }
5471 if (ImportedBlockDecls.size()) {
5472 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5473 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5474 unsigned IntSize =
5475 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5476 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5477 Context->IntTy, SourceLocation());
5478 InitExprs.push_back(FlagExp);
5479 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005480 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005481 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005482
5483 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005484 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005485 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5486 GlobalConstructionExp = NewRep;
5487 NewRep = DRE;
5488 }
5489
Fariborz Jahanian11671902012-02-07 17:11:38 +00005490 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5491 Context->getPointerType(NewRep->getType()),
5492 VK_RValue, OK_Ordinary, SourceLocation());
5493 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5494 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005495 // Put Paren around the call.
5496 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5497 NewRep);
5498
Fariborz Jahanian11671902012-02-07 17:11:38 +00005499 BlockDeclRefs.clear();
5500 BlockByRefDecls.clear();
5501 BlockByRefDeclsPtrSet.clear();
5502 BlockByCopyDecls.clear();
5503 BlockByCopyDeclsPtrSet.clear();
5504 ImportedBlockDecls.clear();
5505 return NewRep;
5506}
5507
5508bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5509 if (const ObjCForCollectionStmt * CS =
5510 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5511 return CS->getElement() == DS;
5512 return false;
5513}
5514
5515//===----------------------------------------------------------------------===//
5516// Function Body / Expression rewriting
5517//===----------------------------------------------------------------------===//
5518
5519Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5520 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5521 isa<DoStmt>(S) || isa<ForStmt>(S))
5522 Stmts.push_back(S);
5523 else if (isa<ObjCForCollectionStmt>(S)) {
5524 Stmts.push_back(S);
5525 ObjCBcLabelNo.push_back(++BcLabelCount);
5526 }
5527
5528 // Pseudo-object operations and ivar references need special
5529 // treatment because we're going to recursively rewrite them.
5530 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5531 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5532 return RewritePropertyOrImplicitSetter(PseudoOp);
5533 } else {
5534 return RewritePropertyOrImplicitGetter(PseudoOp);
5535 }
5536 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5537 return RewriteObjCIvarRefExpr(IvarRefExpr);
5538 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005539 else if (isa<OpaqueValueExpr>(S))
5540 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005541
5542 SourceRange OrigStmtRange = S->getSourceRange();
5543
5544 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005545 for (Stmt *&childStmt : S->children())
5546 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005547 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5548 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005549 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005550 }
5551 }
5552
5553 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005554 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005555 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5556 InnerContexts.insert(BE->getBlockDecl());
5557 ImportedLocalExternalDecls.clear();
5558 GetInnerBlockDeclRefExprs(BE->getBody(),
5559 InnerBlockDeclRefs, InnerContexts);
5560 // Rewrite the block body in place.
5561 Stmt *SaveCurrentBody = CurrentBody;
5562 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005563 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005564 // block literal on rhs of a property-dot-sytax assignment
5565 // must be replaced by its synthesize ast so getRewrittenText
5566 // works as expected. In this case, what actually ends up on RHS
5567 // is the blockTranscribed which is the helper function for the
5568 // block literal; as in: self.c = ^() {[ace ARR];};
5569 bool saveDisableReplaceStmt = DisableReplaceStmt;
5570 DisableReplaceStmt = false;
5571 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5572 DisableReplaceStmt = saveDisableReplaceStmt;
5573 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005574 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005575 ImportedLocalExternalDecls.clear();
5576 // Now we snarf the rewritten text and stash it away for later use.
5577 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5578 RewrittenBlockExprs[BE] = Str;
5579
5580 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5581
5582 //blockTranscribed->dump();
5583 ReplaceStmt(S, blockTranscribed);
5584 return blockTranscribed;
5585 }
5586 // Handle specific things.
5587 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5588 return RewriteAtEncode(AtEncode);
5589
5590 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5591 return RewriteAtSelector(AtSelector);
5592
5593 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5594 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005595
5596 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5597 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005598
Patrick Beard0caa3942012-04-19 00:25:12 +00005599 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5600 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005601
5602 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5603 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005604
5605 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5606 dyn_cast<ObjCDictionaryLiteral>(S))
5607 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005608
5609 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5610#if 0
5611 // Before we rewrite it, put the original message expression in a comment.
5612 SourceLocation startLoc = MessExpr->getLocStart();
5613 SourceLocation endLoc = MessExpr->getLocEnd();
5614
5615 const char *startBuf = SM->getCharacterData(startLoc);
5616 const char *endBuf = SM->getCharacterData(endLoc);
5617
5618 std::string messString;
5619 messString += "// ";
5620 messString.append(startBuf, endBuf-startBuf+1);
5621 messString += "\n";
5622
5623 // FIXME: Missing definition of
5624 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005625 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005626 // Tried this, but it didn't work either...
5627 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5628#endif
5629 return RewriteMessageExpr(MessExpr);
5630 }
5631
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005632 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5633 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5634 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5635 }
5636
Fariborz Jahanian11671902012-02-07 17:11:38 +00005637 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5638 return RewriteObjCTryStmt(StmtTry);
5639
5640 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5641 return RewriteObjCSynchronizedStmt(StmtTry);
5642
5643 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5644 return RewriteObjCThrowStmt(StmtThrow);
5645
5646 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5647 return RewriteObjCProtocolExpr(ProtocolExp);
5648
5649 if (ObjCForCollectionStmt *StmtForCollection =
5650 dyn_cast<ObjCForCollectionStmt>(S))
5651 return RewriteObjCForCollectionStmt(StmtForCollection,
5652 OrigStmtRange.getEnd());
5653 if (BreakStmt *StmtBreakStmt =
5654 dyn_cast<BreakStmt>(S))
5655 return RewriteBreakStmt(StmtBreakStmt);
5656 if (ContinueStmt *StmtContinueStmt =
5657 dyn_cast<ContinueStmt>(S))
5658 return RewriteContinueStmt(StmtContinueStmt);
5659
5660 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5661 // and cast exprs.
5662 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5663 // FIXME: What we're doing here is modifying the type-specifier that
5664 // precedes the first Decl. In the future the DeclGroup should have
5665 // a separate type-specifier that we can rewrite.
5666 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5667 // the context of an ObjCForCollectionStmt. For example:
5668 // NSArray *someArray;
5669 // for (id <FooProtocol> index in someArray) ;
5670 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5671 // and it depends on the original text locations/positions.
5672 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5673 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5674
5675 // Blocks rewrite rules.
5676 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5677 DI != DE; ++DI) {
5678 Decl *SD = *DI;
5679 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5680 if (isTopLevelBlockPointerType(ND->getType()))
5681 RewriteBlockPointerDecl(ND);
5682 else if (ND->getType()->isFunctionPointerType())
5683 CheckFunctionPointerDecl(ND->getType(), ND);
5684 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5685 if (VD->hasAttr<BlocksAttr>()) {
5686 static unsigned uniqueByrefDeclCount = 0;
5687 assert(!BlockByRefDeclNo.count(ND) &&
5688 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5689 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005690 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005691 }
5692 else
5693 RewriteTypeOfDecl(VD);
5694 }
5695 }
5696 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5697 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5698 RewriteBlockPointerDecl(TD);
5699 else if (TD->getUnderlyingType()->isFunctionPointerType())
5700 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5701 }
5702 }
5703 }
5704
5705 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5706 RewriteObjCQualifiedInterfaceTypes(CE);
5707
5708 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5709 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5710 assert(!Stmts.empty() && "Statement stack is empty");
5711 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5712 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5713 && "Statement stack mismatch");
5714 Stmts.pop_back();
5715 }
5716 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5718 ValueDecl *VD = DRE->getDecl();
5719 if (VD->hasAttr<BlocksAttr>())
5720 return RewriteBlockDeclRefExpr(DRE);
5721 if (HasLocalVariableExternalStorage(VD))
5722 return RewriteLocalVariableExternalStorage(DRE);
5723 }
5724
5725 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5726 if (CE->getCallee()->getType()->isBlockPointerType()) {
5727 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5728 ReplaceStmt(S, BlockCall);
5729 return BlockCall;
5730 }
5731 }
5732 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5733 RewriteCastExpr(CE);
5734 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005735 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5736 RewriteImplicitCastObjCExpr(ICE);
5737 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005738#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005739
Fariborz Jahanian11671902012-02-07 17:11:38 +00005740 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5741 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5742 ICE->getSubExpr(),
5743 SourceLocation());
5744 // Get the new text.
5745 std::string SStr;
5746 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005747 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005748 const std::string &Str = Buf.str();
5749
5750 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005751 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005752 delete S;
5753 return Replacement;
5754 }
5755#endif
5756 // Return this stmt unmodified.
5757 return S;
5758}
5759
5760void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005761 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005762 if (isTopLevelBlockPointerType(FD->getType()))
5763 RewriteBlockPointerDecl(FD);
5764 if (FD->getType()->isObjCQualifiedIdType() ||
5765 FD->getType()->isObjCQualifiedInterfaceType())
5766 RewriteObjCQualifiedInterfaceTypes(FD);
5767 }
5768}
5769
5770/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5771/// main file of the input.
5772void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5773 switch (D->getKind()) {
5774 case Decl::Function: {
5775 FunctionDecl *FD = cast<FunctionDecl>(D);
5776 if (FD->isOverloadedOperator())
5777 return;
5778
5779 // Since function prototypes don't have ParmDecl's, we check the function
5780 // prototype. This enables us to rewrite function declarations and
5781 // definitions using the same code.
5782 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5783
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005784 if (!FD->isThisDeclarationADefinition())
5785 break;
5786
Fariborz Jahanian11671902012-02-07 17:11:38 +00005787 // FIXME: If this should support Obj-C++, support CXXTryStmt
5788 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5789 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005790 CurrentBody = Body;
5791 Body =
5792 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5793 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005794 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005795 if (PropParentMap) {
5796 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005797 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005798 }
5799 // This synthesizes and inserts the block "impl" struct, invoke function,
5800 // and any copy/dispose helper functions.
5801 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005802 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005803 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005804 }
5805 break;
5806 }
5807 case Decl::ObjCMethod: {
5808 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5809 if (CompoundStmt *Body = MD->getCompoundBody()) {
5810 CurMethodDef = MD;
5811 CurrentBody = Body;
5812 Body =
5813 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5814 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005815 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005816 if (PropParentMap) {
5817 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005818 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005819 }
5820 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005821 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005822 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005823 }
5824 break;
5825 }
5826 case Decl::ObjCImplementation: {
5827 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5828 ClassImplementation.push_back(CI);
5829 break;
5830 }
5831 case Decl::ObjCCategoryImpl: {
5832 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5833 CategoryImplementation.push_back(CI);
5834 break;
5835 }
5836 case Decl::Var: {
5837 VarDecl *VD = cast<VarDecl>(D);
5838 RewriteObjCQualifiedInterfaceTypes(VD);
5839 if (isTopLevelBlockPointerType(VD->getType()))
5840 RewriteBlockPointerDecl(VD);
5841 else if (VD->getType()->isFunctionPointerType()) {
5842 CheckFunctionPointerDecl(VD->getType(), VD);
5843 if (VD->getInit()) {
5844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5845 RewriteCastExpr(CE);
5846 }
5847 }
5848 } else if (VD->getType()->isRecordType()) {
5849 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5850 if (RD->isCompleteDefinition())
5851 RewriteRecordBody(RD);
5852 }
5853 if (VD->getInit()) {
5854 GlobalVarDecl = VD;
5855 CurrentBody = VD->getInit();
5856 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
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 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005863 GlobalVarDecl = nullptr;
5864
Fariborz Jahanian11671902012-02-07 17:11:38 +00005865 // This is needed for blocks.
5866 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5867 RewriteCastExpr(CE);
5868 }
5869 }
5870 break;
5871 }
5872 case Decl::TypeAlias:
5873 case Decl::Typedef: {
5874 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5875 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5876 RewriteBlockPointerDecl(TD);
5877 else if (TD->getUnderlyingType()->isFunctionPointerType())
5878 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005879 else
5880 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005881 }
5882 break;
5883 }
5884 case Decl::CXXRecord:
5885 case Decl::Record: {
5886 RecordDecl *RD = cast<RecordDecl>(D);
5887 if (RD->isCompleteDefinition())
5888 RewriteRecordBody(RD);
5889 break;
5890 }
5891 default:
5892 break;
5893 }
5894 // Nothing yet.
5895}
5896
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005897/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5898/// protocol reference symbols in the for of:
5899/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5900static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5901 ObjCProtocolDecl *PDecl,
5902 std::string &Result) {
5903 // Also output .objc_protorefs$B section and its meta-data.
5904 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005905 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005906 Result += "struct _protocol_t *";
5907 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5908 Result += PDecl->getNameAsString();
5909 Result += " = &";
5910 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5911 Result += ";\n";
5912}
5913
Fariborz Jahanian11671902012-02-07 17:11:38 +00005914void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5915 if (Diags.hasErrorOccurred())
5916 return;
5917
5918 RewriteInclude();
5919
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005920 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005921 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005922 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005923 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005924 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5925 HandleTopLevelSingleDecl(FDecl);
5926 }
5927
Fariborz Jahanian11671902012-02-07 17:11:38 +00005928 // Here's a great place to add any extra declarations that may be needed.
5929 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005930 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5931 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5932 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005933 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005934
5935 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005936
5937 if (ClassImplementation.size() || CategoryImplementation.size())
5938 RewriteImplementations();
5939
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005940 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5941 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5942 // Write struct declaration for the class matching its ivar declarations.
5943 // Note that for modern abi, this is postponed until the end of TU
5944 // because class extensions and the implementation might declare their own
5945 // private ivars.
5946 RewriteInterfaceDecl(CDecl);
5947 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005948
Fariborz Jahanian11671902012-02-07 17:11:38 +00005949 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5950 // we are done.
5951 if (const RewriteBuffer *RewriteBuf =
5952 Rewrite.getRewriteBufferFor(MainFileID)) {
5953 //printf("Changed:\n");
5954 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5955 } else {
5956 llvm::errs() << "No changes\n";
5957 }
5958
5959 if (ClassImplementation.size() || CategoryImplementation.size() ||
5960 ProtocolExprDecls.size()) {
5961 // Rewrite Objective-c meta data*
5962 std::string ResultStr;
5963 RewriteMetaDataIntoBuffer(ResultStr);
5964 // Emit metadata.
5965 *OutFile << ResultStr;
5966 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005967 // Emit ImageInfo;
5968 {
5969 std::string ResultStr;
5970 WriteImageInfo(ResultStr);
5971 *OutFile << ResultStr;
5972 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005973 OutFile->flush();
5974}
5975
5976void RewriteModernObjC::Initialize(ASTContext &context) {
5977 InitializeCommon(context);
5978
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005979 Preamble += "#ifndef __OBJC2__\n";
5980 Preamble += "#define __OBJC2__\n";
5981 Preamble += "#endif\n";
5982
Fariborz Jahanian11671902012-02-07 17:11:38 +00005983 // declaring objc_selector outside the parameter list removes a silly
5984 // scope related warning...
5985 if (IsHeader)
5986 Preamble = "#pragma once\n";
5987 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005988 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5989 Preamble += "\n\tstruct objc_object *superClass; ";
5990 // Add a constructor for creating temporary objects.
5991 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5992 Preamble += ": object(o), superClass(s) {} ";
5993 Preamble += "\n};\n";
5994
Fariborz Jahanian11671902012-02-07 17:11:38 +00005995 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005996 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005997 // These are currently generated.
5998 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005999 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006000 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006001 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6002 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006003 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006004 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006005 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6006 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006007 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006008
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006009 // These need be generated for performance. Currently they are not,
6010 // using API calls instead.
6011 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6012 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6013 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6014
Fariborz Jahanian11671902012-02-07 17:11:38 +00006015 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006016 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6017 Preamble += "typedef struct objc_object Protocol;\n";
6018 Preamble += "#define _REWRITER_typedef_Protocol\n";
6019 Preamble += "#endif\n";
6020 if (LangOpts.MicrosoftExt) {
6021 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6022 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006023 }
6024 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006025 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006026
6027 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6028 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6029 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6030 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6031 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6032
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006033 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006034 Preamble += "(const char *);\n";
6035 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6036 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006037 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006038 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006039 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006040 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006041 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6042 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006043 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006044 Preamble += "#ifdef _WIN64\n";
6045 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6046 Preamble += "#else\n";
6047 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6048 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006049 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6050 Preamble += "struct __objcFastEnumerationState {\n\t";
6051 Preamble += "unsigned long state;\n\t";
6052 Preamble += "void **itemsPtr;\n\t";
6053 Preamble += "unsigned long *mutationsPtr;\n\t";
6054 Preamble += "unsigned long extra[5];\n};\n";
6055 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6056 Preamble += "#define __FASTENUMERATIONSTATE\n";
6057 Preamble += "#endif\n";
6058 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6059 Preamble += "struct __NSConstantStringImpl {\n";
6060 Preamble += " int *isa;\n";
6061 Preamble += " int flags;\n";
6062 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00006063 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006064 Preamble += " long long length;\n";
6065 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006066 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006067 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006068 Preamble += "};\n";
6069 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6070 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6071 Preamble += "#else\n";
6072 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6073 Preamble += "#endif\n";
6074 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6075 Preamble += "#endif\n";
6076 // Blocks preamble.
6077 Preamble += "#ifndef BLOCK_IMPL\n";
6078 Preamble += "#define BLOCK_IMPL\n";
6079 Preamble += "struct __block_impl {\n";
6080 Preamble += " void *isa;\n";
6081 Preamble += " int Flags;\n";
6082 Preamble += " int Reserved;\n";
6083 Preamble += " void *FuncPtr;\n";
6084 Preamble += "};\n";
6085 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6086 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6087 Preamble += "extern \"C\" __declspec(dllexport) "
6088 "void _Block_object_assign(void *, const void *, const int);\n";
6089 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6090 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6091 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6092 Preamble += "#else\n";
6093 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6094 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6095 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6096 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6097 Preamble += "#endif\n";
6098 Preamble += "#endif\n";
6099 if (LangOpts.MicrosoftExt) {
6100 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6101 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6102 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6103 Preamble += "#define __attribute__(X)\n";
6104 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006105 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006106 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006107 Preamble += "#endif\n";
6108 Preamble += "#ifndef __block\n";
6109 Preamble += "#define __block\n";
6110 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006111 }
6112 else {
6113 Preamble += "#define __block\n";
6114 Preamble += "#define __weak\n";
6115 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006116
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006117 // Declarations required for modern objective-c array and dictionary literals.
6118 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006119 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006120 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006121 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006122 Preamble += "\tva_list marker;\n";
6123 Preamble += "\tva_start(marker, count);\n";
6124 Preamble += "\tarr = new void *[count];\n";
6125 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6126 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6127 Preamble += "\tva_end( marker );\n";
6128 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006129 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006130 Preamble += "\tdelete[] arr;\n";
6131 Preamble += " }\n";
6132 Preamble += "};\n";
6133
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006134 // Declaration required for implementation of @autoreleasepool statement.
6135 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6136 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6137 Preamble += "struct __AtAutoreleasePool {\n";
6138 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6139 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6140 Preamble += " void * atautoreleasepoolobj;\n";
6141 Preamble += "};\n";
6142
Fariborz Jahanian11671902012-02-07 17:11:38 +00006143 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6144 // as this avoids warning in any 64bit/32bit compilation model.
6145 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6146}
6147
6148/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6149/// ivar offset.
6150void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6151 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006152 Result += "__OFFSETOFIVAR__(struct ";
6153 Result += ivar->getContainingInterface()->getNameAsString();
6154 if (LangOpts.MicrosoftExt)
6155 Result += "_IMPL";
6156 Result += ", ";
6157 if (ivar->isBitField())
6158 ObjCIvarBitfieldGroupDecl(ivar, Result);
6159 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006160 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006161 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006162}
6163
6164/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6165/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006166/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006167/// char *attributes;
6168/// }
6169
6170/// struct _prop_list_t {
6171/// uint32_t entsize; // sizeof(struct _prop_t)
6172/// uint32_t count_of_properties;
6173/// struct _prop_t prop_list[count_of_properties];
6174/// }
6175
6176/// struct _protocol_t;
6177
6178/// struct _protocol_list_t {
6179/// long protocol_count; // Note, this is 32/64 bit
6180/// struct _protocol_t * protocol_list[protocol_count];
6181/// }
6182
6183/// struct _objc_method {
6184/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006185/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006186/// char *_imp;
6187/// }
6188
6189/// struct _method_list_t {
6190/// uint32_t entsize; // sizeof(struct _objc_method)
6191/// uint32_t method_count;
6192/// struct _objc_method method_list[method_count];
6193/// }
6194
6195/// struct _protocol_t {
6196/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006197/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006198/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006199/// const struct method_list_t *instance_methods;
6200/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006201/// const struct method_list_t *optionalInstanceMethods;
6202/// const struct method_list_t *optionalClassMethods;
6203/// const struct _prop_list_t * properties;
6204/// const uint32_t size; // sizeof(struct _protocol_t)
6205/// const uint32_t flags; // = 0
6206/// const char ** extendedMethodTypes;
6207/// }
6208
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006209/// struct _ivar_t {
6210/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006211/// const char *name;
6212/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006213/// uint32_t alignment;
6214/// uint32_t size;
6215/// }
6216
6217/// struct _ivar_list_t {
6218/// uint32 entsize; // sizeof(struct _ivar_t)
6219/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006220/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006221/// }
6222
6223/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006224/// uint32_t flags;
6225/// uint32_t instanceStart;
6226/// uint32_t instanceSize;
6227/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006228/// const uint8_t *ivarLayout;
6229/// const char *name;
6230/// const struct _method_list_t *baseMethods;
6231/// const struct _protocol_list_t *baseProtocols;
6232/// const struct _ivar_list_t *ivars;
6233/// const uint8_t *weakIvarLayout;
6234/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006235/// }
6236
6237/// struct _class_t {
6238/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006239/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006240/// void *cache;
6241/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006242/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006243/// }
6244
6245/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006246/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006247/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006248/// const struct _method_list_t *instance_methods;
6249/// const struct _method_list_t *class_methods;
6250/// const struct _protocol_list_t *protocols;
6251/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006252/// }
6253
6254/// MessageRefTy - LLVM for:
6255/// struct _message_ref_t {
6256/// IMP messenger;
6257/// SEL name;
6258/// };
6259
6260/// SuperMessageRefTy - LLVM for:
6261/// struct _super_message_ref_t {
6262/// SUPER_IMP messenger;
6263/// SEL name;
6264/// };
6265
Fariborz Jahanian45489622012-03-14 18:09:23 +00006266static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006267 static bool meta_data_declared = false;
6268 if (meta_data_declared)
6269 return;
6270
6271 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006272 Result += "\tconst char *name;\n";
6273 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006274 Result += "};\n";
6275
6276 Result += "\nstruct _protocol_t;\n";
6277
Fariborz Jahanian11671902012-02-07 17:11:38 +00006278 Result += "\nstruct _objc_method {\n";
6279 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006280 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006281 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006282 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006283
6284 Result += "\nstruct _protocol_t {\n";
6285 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006286 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006287 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006288 Result += "\tconst struct method_list_t *instance_methods;\n";
6289 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006290 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6291 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6292 Result += "\tconst struct _prop_list_t * properties;\n";
6293 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6294 Result += "\tconst unsigned int flags; // = 0\n";
6295 Result += "\tconst char ** extendedMethodTypes;\n";
6296 Result += "};\n";
6297
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006298 Result += "\nstruct _ivar_t {\n";
6299 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006300 Result += "\tconst char *name;\n";
6301 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006302 Result += "\tunsigned int alignment;\n";
6303 Result += "\tunsigned int size;\n";
6304 Result += "};\n";
6305
6306 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006307 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006308 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006309 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006310 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6311 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006312 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006313 Result += "\tconst unsigned char *ivarLayout;\n";
6314 Result += "\tconst char *name;\n";
6315 Result += "\tconst struct _method_list_t *baseMethods;\n";
6316 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6317 Result += "\tconst struct _ivar_list_t *ivars;\n";
6318 Result += "\tconst unsigned char *weakIvarLayout;\n";
6319 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006320 Result += "};\n";
6321
6322 Result += "\nstruct _class_t {\n";
6323 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006324 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006325 Result += "\tvoid *cache;\n";
6326 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006327 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006328 Result += "};\n";
6329
6330 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006331 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006332 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006333 Result += "\tconst struct _method_list_t *instance_methods;\n";
6334 Result += "\tconst struct _method_list_t *class_methods;\n";
6335 Result += "\tconst struct _protocol_list_t *protocols;\n";
6336 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006337 Result += "};\n";
6338
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006339 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006340 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006341 meta_data_declared = true;
6342}
6343
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006344static void Write_protocol_list_t_TypeDecl(std::string &Result,
6345 long super_protocol_count) {
6346 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6347 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6348 Result += "\tstruct _protocol_t *super_protocols[";
6349 Result += utostr(super_protocol_count); Result += "];\n";
6350 Result += "}";
6351}
6352
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006353static void Write_method_list_t_TypeDecl(std::string &Result,
6354 unsigned int method_count) {
6355 Result += "struct /*_method_list_t*/"; Result += " {\n";
6356 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6357 Result += "\tunsigned int method_count;\n";
6358 Result += "\tstruct _objc_method method_list[";
6359 Result += utostr(method_count); Result += "];\n";
6360 Result += "}";
6361}
6362
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006363static void Write__prop_list_t_TypeDecl(std::string &Result,
6364 unsigned int property_count) {
6365 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6366 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6367 Result += "\tunsigned int count_of_properties;\n";
6368 Result += "\tstruct _prop_t prop_list[";
6369 Result += utostr(property_count); Result += "];\n";
6370 Result += "}";
6371}
6372
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006373static void Write__ivar_list_t_TypeDecl(std::string &Result,
6374 unsigned int ivar_count) {
6375 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6376 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6377 Result += "\tunsigned int count;\n";
6378 Result += "\tstruct _ivar_t ivar_list[";
6379 Result += utostr(ivar_count); Result += "];\n";
6380 Result += "}";
6381}
6382
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006383static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6384 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6385 StringRef VarName,
6386 StringRef ProtocolName) {
6387 if (SuperProtocols.size() > 0) {
6388 Result += "\nstatic ";
6389 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6390 Result += " "; Result += VarName;
6391 Result += ProtocolName;
6392 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6393 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6394 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6395 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6396 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6397 Result += SuperPD->getNameAsString();
6398 if (i == e-1)
6399 Result += "\n};\n";
6400 else
6401 Result += ",\n";
6402 }
6403 }
6404}
6405
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006406static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6407 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006408 ArrayRef<ObjCMethodDecl *> Methods,
6409 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006410 StringRef TopLevelDeclName,
6411 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006412 if (Methods.size() > 0) {
6413 Result += "\nstatic ";
6414 Write_method_list_t_TypeDecl(Result, Methods.size());
6415 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006416 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006417 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6418 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6419 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6420 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6421 ObjCMethodDecl *MD = Methods[i];
6422 if (i == 0)
6423 Result += "\t{{(struct objc_selector *)\"";
6424 else
6425 Result += "\t{(struct objc_selector *)\"";
6426 Result += (MD)->getSelector().getAsString(); Result += "\"";
6427 Result += ", ";
6428 std::string MethodTypeString;
6429 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6430 Result += "\""; Result += MethodTypeString; Result += "\"";
6431 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006432 if (!MethodImpl)
6433 Result += "0";
6434 else {
6435 Result += "(void *)";
6436 Result += RewriteObj.MethodInternalNames[MD];
6437 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006438 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006439 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006440 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006441 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006442 }
6443 Result += "};\n";
6444 }
6445}
6446
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006447static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006448 ASTContext *Context, std::string &Result,
6449 ArrayRef<ObjCPropertyDecl *> Properties,
6450 const Decl *Container,
6451 StringRef VarName,
6452 StringRef ProtocolName) {
6453 if (Properties.size() > 0) {
6454 Result += "\nstatic ";
6455 Write__prop_list_t_TypeDecl(Result, Properties.size());
6456 Result += " "; Result += VarName;
6457 Result += ProtocolName;
6458 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6459 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6460 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6461 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6462 ObjCPropertyDecl *PropDecl = Properties[i];
6463 if (i == 0)
6464 Result += "\t{{\"";
6465 else
6466 Result += "\t{\"";
6467 Result += PropDecl->getName(); Result += "\",";
6468 std::string PropertyTypeString, QuotePropertyTypeString;
6469 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6470 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6471 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6472 if (i == e-1)
6473 Result += "}}\n";
6474 else
6475 Result += "},\n";
6476 }
6477 Result += "};\n";
6478 }
6479}
6480
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006481// Metadata flags
6482enum MetaDataDlags {
6483 CLS = 0x0,
6484 CLS_META = 0x1,
6485 CLS_ROOT = 0x2,
6486 OBJC2_CLS_HIDDEN = 0x10,
6487 CLS_EXCEPTION = 0x20,
6488
6489 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6490 CLS_HAS_IVAR_RELEASER = 0x40,
6491 /// class was compiled with -fobjc-arr
6492 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6493};
6494
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006495static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6496 unsigned int flags,
6497 const std::string &InstanceStart,
6498 const std::string &InstanceSize,
6499 ArrayRef<ObjCMethodDecl *>baseMethods,
6500 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6501 ArrayRef<ObjCIvarDecl *>ivars,
6502 ArrayRef<ObjCPropertyDecl *>Properties,
6503 StringRef VarName,
6504 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006505 Result += "\nstatic struct _class_ro_t ";
6506 Result += VarName; Result += ClassName;
6507 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6508 Result += "\t";
6509 Result += llvm::utostr(flags); Result += ", ";
6510 Result += InstanceStart; Result += ", ";
6511 Result += InstanceSize; Result += ", \n";
6512 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006513 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6514 if (Triple.getArch() == llvm::Triple::x86_64)
6515 // uint32_t const reserved; // only when building for 64bit targets
6516 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006517 // const uint8_t * const ivarLayout;
6518 Result += "0, \n\t";
6519 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006520 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006521 if (baseMethods.size() > 0) {
6522 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006523 if (metaclass)
6524 Result += "_OBJC_$_CLASS_METHODS_";
6525 else
6526 Result += "_OBJC_$_INSTANCE_METHODS_";
6527 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006528 Result += ",\n\t";
6529 }
6530 else
6531 Result += "0, \n\t";
6532
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006533 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006534 Result += "(const struct _objc_protocol_list *)&";
6535 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6536 Result += ",\n\t";
6537 }
6538 else
6539 Result += "0, \n\t";
6540
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006541 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006542 Result += "(const struct _ivar_list_t *)&";
6543 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6544 Result += ",\n\t";
6545 }
6546 else
6547 Result += "0, \n\t";
6548
6549 // weakIvarLayout
6550 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006551 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006552 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006553 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006554 Result += ",\n";
6555 }
6556 else
6557 Result += "0, \n";
6558
6559 Result += "};\n";
6560}
6561
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006562static void Write_class_t(ASTContext *Context, std::string &Result,
6563 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006564 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6565 bool rootClass = (!CDecl->getSuperClass());
6566 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006567
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006568 if (!rootClass) {
6569 // Find the Root class
6570 RootClass = CDecl->getSuperClass();
6571 while (RootClass->getSuperClass()) {
6572 RootClass = RootClass->getSuperClass();
6573 }
6574 }
6575
6576 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006577 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006578 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006579 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006580 if (CDecl->getImplementation())
6581 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006582 else
6583 Result += "__declspec(dllimport) ";
6584
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006585 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006586 Result += CDecl->getNameAsString();
6587 Result += ";\n";
6588 }
6589 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006590 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006591 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006592 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006593 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006594 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006595 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006596 else
6597 Result += "__declspec(dllimport) ";
6598
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006599 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006600 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006601 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006602 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006603
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006604 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006605 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006606 if (RootClass->getImplementation())
6607 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006608 else
6609 Result += "__declspec(dllimport) ";
6610
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006611 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006612 Result += VarName;
6613 Result += RootClass->getNameAsString();
6614 Result += ";\n";
6615 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006616 }
6617
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006618 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6619 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006620 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6621 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006622 if (metaclass) {
6623 if (!rootClass) {
6624 Result += "0, // &"; Result += VarName;
6625 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006626 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006627 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006628 Result += CDecl->getSuperClass()->getNameAsString();
6629 Result += ",\n\t";
6630 }
6631 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006632 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006633 Result += CDecl->getNameAsString();
6634 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006635 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006636 Result += ",\n\t";
6637 }
6638 }
6639 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006640 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006641 Result += CDecl->getNameAsString();
6642 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006643 if (!rootClass) {
6644 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006645 Result += CDecl->getSuperClass()->getNameAsString();
6646 Result += ",\n\t";
6647 }
6648 else
6649 Result += "0,\n\t";
6650 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006651 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6652 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6653 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006654 Result += "&_OBJC_METACLASS_RO_$_";
6655 else
6656 Result += "&_OBJC_CLASS_RO_$_";
6657 Result += CDecl->getNameAsString();
6658 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006659
6660 // Add static function to initialize some of the meta-data fields.
6661 // avoid doing it twice.
6662 if (metaclass)
6663 return;
6664
6665 const ObjCInterfaceDecl *SuperClass =
6666 rootClass ? CDecl : CDecl->getSuperClass();
6667
6668 Result += "static void OBJC_CLASS_SETUP_$_";
6669 Result += CDecl->getNameAsString();
6670 Result += "(void ) {\n";
6671 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6672 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006673 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006674
6675 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006676 Result += ".superclass = ";
6677 if (rootClass)
6678 Result += "&OBJC_CLASS_$_";
6679 else
6680 Result += "&OBJC_METACLASS_$_";
6681
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006682 Result += SuperClass->getNameAsString(); Result += ";\n";
6683
6684 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6685 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6686
6687 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6688 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6689 Result += CDecl->getNameAsString(); Result += ";\n";
6690
6691 if (!rootClass) {
6692 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6693 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6694 Result += SuperClass->getNameAsString(); Result += ";\n";
6695 }
6696
6697 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6698 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6699 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006700}
6701
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006702static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6703 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006704 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006705 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006706 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6707 ArrayRef<ObjCMethodDecl *> ClassMethods,
6708 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6709 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006710 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006711 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006712 // must declare an extern class object in case this class is not implemented
6713 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006714 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006715 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006716 if (ClassDecl->getImplementation())
6717 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006718 else
6719 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006720
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006721 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006722 Result += "OBJC_CLASS_$_"; Result += ClassName;
6723 Result += ";\n";
6724
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006725 Result += "\nstatic struct _category_t ";
6726 Result += "_OBJC_$_CATEGORY_";
6727 Result += ClassName; Result += "_$_"; Result += CatName;
6728 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6729 Result += "{\n";
6730 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006731 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006732 Result += ",\n";
6733 if (InstanceMethods.size() > 0) {
6734 Result += "\t(const struct _method_list_t *)&";
6735 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6736 Result += ClassName; Result += "_$_"; Result += CatName;
6737 Result += ",\n";
6738 }
6739 else
6740 Result += "\t0,\n";
6741
6742 if (ClassMethods.size() > 0) {
6743 Result += "\t(const struct _method_list_t *)&";
6744 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6745 Result += ClassName; Result += "_$_"; Result += CatName;
6746 Result += ",\n";
6747 }
6748 else
6749 Result += "\t0,\n";
6750
6751 if (RefedProtocols.size() > 0) {
6752 Result += "\t(const struct _protocol_list_t *)&";
6753 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6754 Result += ClassName; Result += "_$_"; Result += CatName;
6755 Result += ",\n";
6756 }
6757 else
6758 Result += "\t0,\n";
6759
6760 if (ClassProperties.size() > 0) {
6761 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6762 Result += ClassName; Result += "_$_"; Result += CatName;
6763 Result += ",\n";
6764 }
6765 else
6766 Result += "\t0,\n";
6767
6768 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006769
6770 // Add static function to initialize the class pointer in the category structure.
6771 Result += "static void OBJC_CATEGORY_SETUP_$_";
6772 Result += ClassDecl->getNameAsString();
6773 Result += "_$_";
6774 Result += CatName;
6775 Result += "(void ) {\n";
6776 Result += "\t_OBJC_$_CATEGORY_";
6777 Result += ClassDecl->getNameAsString();
6778 Result += "_$_";
6779 Result += CatName;
6780 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6781 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006782}
6783
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006784static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6785 ASTContext *Context, std::string &Result,
6786 ArrayRef<ObjCMethodDecl *> Methods,
6787 StringRef VarName,
6788 StringRef ProtocolName) {
6789 if (Methods.size() == 0)
6790 return;
6791
6792 Result += "\nstatic const char *";
6793 Result += VarName; Result += ProtocolName;
6794 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6795 Result += "{\n";
6796 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6797 ObjCMethodDecl *MD = Methods[i];
6798 std::string MethodTypeString, QuoteMethodTypeString;
6799 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6800 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6801 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6802 if (i == e-1)
6803 Result += "\n};\n";
6804 else {
6805 Result += ",\n";
6806 }
6807 }
6808}
6809
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006810static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6811 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006812 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006813 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006814 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006815 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6816 // this is what happens:
6817 /**
6818 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6819 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6820 Class->getVisibility() == HiddenVisibility)
6821 Visibility shoud be: HiddenVisibility;
6822 else
6823 Visibility shoud be: DefaultVisibility;
6824 */
6825
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006826 Result += "\n";
6827 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6828 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006829 if (Context->getLangOpts().MicrosoftExt)
6830 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6831
6832 if (!Context->getLangOpts().MicrosoftExt ||
6833 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006834 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006835 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006836 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006837 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006838 if (Ivars[i]->isBitField())
6839 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6840 else
6841 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006842 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6843 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006844 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6845 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006846 if (Ivars[i]->isBitField()) {
6847 // skip over rest of the ivar bitfields.
6848 SKIP_BITFIELDS(i , e, Ivars);
6849 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006850 }
6851}
6852
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006853static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6854 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006855 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006856 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006857 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006858 if (OriginalIvars.size() > 0) {
6859 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6860 SmallVector<ObjCIvarDecl *, 8> Ivars;
6861 // strip off all but the first ivar bitfield from each group of ivars.
6862 // Such ivars in the ivar list table will be replaced by their grouping struct
6863 // 'ivar'.
6864 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6865 if (OriginalIvars[i]->isBitField()) {
6866 Ivars.push_back(OriginalIvars[i]);
6867 // skip over rest of the ivar bitfields.
6868 SKIP_BITFIELDS(i , e, OriginalIvars);
6869 }
6870 else
6871 Ivars.push_back(OriginalIvars[i]);
6872 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006873
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006874 Result += "\nstatic ";
6875 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6876 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006877 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006878 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6879 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6880 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6881 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6882 ObjCIvarDecl *IvarDecl = Ivars[i];
6883 if (i == 0)
6884 Result += "\t{{";
6885 else
6886 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006887 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006888 if (Ivars[i]->isBitField())
6889 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6890 else
6891 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006892 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006893
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006894 Result += "\"";
6895 if (Ivars[i]->isBitField())
6896 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6897 else
6898 Result += IvarDecl->getName();
6899 Result += "\", ";
6900
6901 QualType IVQT = IvarDecl->getType();
6902 if (IvarDecl->isBitField())
6903 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6904
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006905 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006906 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006907 IvarDecl);
6908 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6909 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6910
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006911 // FIXME. this alignment represents the host alignment and need be changed to
6912 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006913 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006914 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006915 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006916 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006917 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006918 if (i == e-1)
6919 Result += "}}\n";
6920 else
6921 Result += "},\n";
6922 }
6923 Result += "};\n";
6924 }
6925}
6926
Fariborz Jahanian11671902012-02-07 17:11:38 +00006927/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006928void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6929 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006930
Fariborz Jahanian11671902012-02-07 17:11:38 +00006931 // Do not synthesize the protocol more than once.
6932 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6933 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006934 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006935
6936 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6937 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006938 // Must write out all protocol definitions in current qualifier list,
6939 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006940 for (auto *I : PDecl->protocols())
6941 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006942
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006943 // Construct method lists.
6944 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6945 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006946 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006947 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6948 OptInstanceMethods.push_back(MD);
6949 } else {
6950 InstanceMethods.push_back(MD);
6951 }
6952 }
6953
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006954 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006955 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6956 OptClassMethods.push_back(MD);
6957 } else {
6958 ClassMethods.push_back(MD);
6959 }
6960 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006961 std::vector<ObjCMethodDecl *> AllMethods;
6962 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6963 AllMethods.push_back(InstanceMethods[i]);
6964 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6965 AllMethods.push_back(ClassMethods[i]);
6966 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6967 AllMethods.push_back(OptInstanceMethods[i]);
6968 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6969 AllMethods.push_back(OptClassMethods[i]);
6970
6971 Write__extendedMethodTypes_initializer(*this, Context, Result,
6972 AllMethods,
6973 "_OBJC_PROTOCOL_METHOD_TYPES_",
6974 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006975 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006976 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006977 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6978 "_OBJC_PROTOCOL_REFS_",
6979 PDecl->getNameAsString());
6980
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006981 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006982 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006983 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006984
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006985 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006986 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006987 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006988
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006989 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006990 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006991 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006992
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006993 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006994 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006995 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006996
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006997 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00006998 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006999 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00007000 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007001 "_OBJC_PROTOCOL_PROPERTIES_",
7002 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00007003
Fariborz Jahanian48985802012-02-08 00:50:52 +00007004 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007005 Result += "\n";
7006 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007007 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007008 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007009 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007010 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7011 Result += "\t0,\n"; // id is; is null
7012 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007013 if (SuperProtocols.size() > 0) {
7014 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7015 Result += PDecl->getNameAsString(); Result += ",\n";
7016 }
7017 else
7018 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007019 if (InstanceMethods.size() > 0) {
7020 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7021 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007022 }
7023 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007024 Result += "\t0,\n";
7025
7026 if (ClassMethods.size() > 0) {
7027 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7028 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007029 }
7030 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007031 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007032
Fariborz Jahanian48985802012-02-08 00:50:52 +00007033 if (OptInstanceMethods.size() > 0) {
7034 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7035 Result += PDecl->getNameAsString(); Result += ",\n";
7036 }
7037 else
7038 Result += "\t0,\n";
7039
7040 if (OptClassMethods.size() > 0) {
7041 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7042 Result += PDecl->getNameAsString(); Result += ",\n";
7043 }
7044 else
7045 Result += "\t0,\n";
7046
7047 if (ProtocolProperties.size() > 0) {
7048 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7049 Result += PDecl->getNameAsString(); Result += ",\n";
7050 }
7051 else
7052 Result += "\t0,\n";
7053
7054 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7055 Result += "\t0,\n";
7056
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007057 if (AllMethods.size() > 0) {
7058 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7059 Result += PDecl->getNameAsString();
7060 Result += "\n};\n";
7061 }
7062 else
7063 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007064
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007065 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007066 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007067 Result += "struct _protocol_t *";
7068 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7069 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7070 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007071
Fariborz Jahanian11671902012-02-07 17:11:38 +00007072 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00007073 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007074 llvm_unreachable("protocol already synthesized");
7075
7076}
7077
7078void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7079 const ObjCList<ObjCProtocolDecl> &Protocols,
7080 StringRef prefix, StringRef ClassName,
7081 std::string &Result) {
7082 if (Protocols.empty()) return;
7083
7084 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007085 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007086
7087 // Output the top lovel protocol meta-data for the class.
7088 /* struct _objc_protocol_list {
7089 struct _objc_protocol_list *next;
7090 int protocol_count;
7091 struct _objc_protocol *class_protocols[];
7092 }
7093 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007094 Result += "\n";
7095 if (LangOpts.MicrosoftExt)
7096 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7097 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007098 Result += "\tstruct _objc_protocol_list *next;\n";
7099 Result += "\tint protocol_count;\n";
7100 Result += "\tstruct _objc_protocol *class_protocols[";
7101 Result += utostr(Protocols.size());
7102 Result += "];\n} _OBJC_";
7103 Result += prefix;
7104 Result += "_PROTOCOLS_";
7105 Result += ClassName;
7106 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7107 "{\n\t0, ";
7108 Result += utostr(Protocols.size());
7109 Result += "\n";
7110
7111 Result += "\t,{&_OBJC_PROTOCOL_";
7112 Result += Protocols[0]->getNameAsString();
7113 Result += " \n";
7114
7115 for (unsigned i = 1; i != Protocols.size(); i++) {
7116 Result += "\t ,&_OBJC_PROTOCOL_";
7117 Result += Protocols[i]->getNameAsString();
7118 Result += "\n";
7119 }
7120 Result += "\t }\n};\n";
7121}
7122
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007123/// hasObjCExceptionAttribute - Return true if this class or any super
7124/// class has the __objc_exception__ attribute.
7125/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7126static bool hasObjCExceptionAttribute(ASTContext &Context,
7127 const ObjCInterfaceDecl *OID) {
7128 if (OID->hasAttr<ObjCExceptionAttr>())
7129 return true;
7130 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7131 return hasObjCExceptionAttribute(Context, Super);
7132 return false;
7133}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007134
Fariborz Jahanian11671902012-02-07 17:11:38 +00007135void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7136 std::string &Result) {
7137 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7138
7139 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007140 if (CDecl->isImplicitInterfaceDecl())
7141 assert(false &&
7142 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007143
Fariborz Jahanian45489622012-03-14 18:09:23 +00007144 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007145 SmallVector<ObjCIvarDecl *, 8> IVars;
7146
7147 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7148 IVD; IVD = IVD->getNextIvar()) {
7149 // Ignore unnamed bit-fields.
7150 if (!IVD->getDeclName())
7151 continue;
7152 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007153 }
7154
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007155 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007156 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007157 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007158
7159 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007160 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007161
7162 // If any of our property implementations have associated getters or
7163 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007164 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007165 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007166 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007167 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007168 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007169 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007170 if (!PD)
7171 continue;
7172 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007173 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007174 InstanceMethods.push_back(Getter);
7175 if (PD->isReadOnly())
7176 continue;
7177 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007178 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007179 InstanceMethods.push_back(Setter);
7180 }
7181
7182 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7183 "_OBJC_$_INSTANCE_METHODS_",
7184 IDecl->getNameAsString(), true);
7185
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007186 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007187
7188 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7189 "_OBJC_$_CLASS_METHODS_",
7190 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007191
7192 // Protocols referenced in class declaration?
7193 // Protocol's super protocol list
7194 std::vector<ObjCProtocolDecl *> RefedProtocols;
7195 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7196 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7197 E = Protocols.end();
7198 I != E; ++I) {
7199 RefedProtocols.push_back(*I);
7200 // Must write out all protocol definitions in current qualifier list,
7201 // and in their nested qualifiers before writing out current definition.
7202 RewriteObjCProtocolMetaData(*I, Result);
7203 }
7204
7205 Write_protocol_list_initializer(Context, Result,
7206 RefedProtocols,
7207 "_OBJC_CLASS_PROTOCOLS_$_",
7208 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007209
7210 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007211 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007212 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007213 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007214 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007215 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007216
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007217
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007218 // Data for initializing _class_ro_t metaclass meta-data
7219 uint32_t flags = CLS_META;
7220 std::string InstanceSize;
7221 std::string InstanceStart;
7222
7223
7224 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7225 if (classIsHidden)
7226 flags |= OBJC2_CLS_HIDDEN;
7227
7228 if (!CDecl->getSuperClass())
7229 // class is root
7230 flags |= CLS_ROOT;
7231 InstanceSize = "sizeof(struct _class_t)";
7232 InstanceStart = InstanceSize;
7233 Write__class_ro_t_initializer(Context, Result, flags,
7234 InstanceStart, InstanceSize,
7235 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007236 nullptr,
7237 nullptr,
7238 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007239 "_OBJC_METACLASS_RO_$_",
7240 CDecl->getNameAsString());
7241
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007242 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007243 flags = CLS;
7244 if (classIsHidden)
7245 flags |= OBJC2_CLS_HIDDEN;
7246
7247 if (hasObjCExceptionAttribute(*Context, CDecl))
7248 flags |= CLS_EXCEPTION;
7249
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007250 if (!CDecl->getSuperClass())
7251 // class is root
7252 flags |= CLS_ROOT;
7253
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007254 InstanceSize.clear();
7255 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007256 if (!ObjCSynthesizedStructs.count(CDecl)) {
7257 InstanceSize = "0";
7258 InstanceStart = "0";
7259 }
7260 else {
7261 InstanceSize = "sizeof(struct ";
7262 InstanceSize += CDecl->getNameAsString();
7263 InstanceSize += "_IMPL)";
7264
7265 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7266 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007267 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007268 }
7269 else
7270 InstanceStart = InstanceSize;
7271 }
7272 Write__class_ro_t_initializer(Context, Result, flags,
7273 InstanceStart, InstanceSize,
7274 InstanceMethods,
7275 RefedProtocols,
7276 IVars,
7277 ClassProperties,
7278 "_OBJC_CLASS_RO_$_",
7279 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007280
7281 Write_class_t(Context, Result,
7282 "OBJC_METACLASS_$_",
7283 CDecl, /*metaclass*/true);
7284
7285 Write_class_t(Context, Result,
7286 "OBJC_CLASS_$_",
7287 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007288
7289 if (ImplementationIsNonLazy(IDecl))
7290 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007291
Fariborz Jahanian11671902012-02-07 17:11:38 +00007292}
7293
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007294void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7295 int ClsDefCount = ClassImplementation.size();
7296 if (!ClsDefCount)
7297 return;
7298 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7299 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7300 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7301 for (int i = 0; i < ClsDefCount; i++) {
7302 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7303 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7304 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7305 Result += CDecl->getName(); Result += ",\n";
7306 }
7307 Result += "};\n";
7308}
7309
Fariborz Jahanian11671902012-02-07 17:11:38 +00007310void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7311 int ClsDefCount = ClassImplementation.size();
7312 int CatDefCount = CategoryImplementation.size();
7313
7314 // For each implemented class, write out all its meta data.
7315 for (int i = 0; i < ClsDefCount; i++)
7316 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7317
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007318 RewriteClassSetupInitHook(Result);
7319
Fariborz Jahanian11671902012-02-07 17:11:38 +00007320 // For each implemented category, write out all its meta data.
7321 for (int i = 0; i < CatDefCount; i++)
7322 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7323
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007324 RewriteCategorySetupInitHook(Result);
7325
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007326 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007327 if (LangOpts.MicrosoftExt)
7328 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007329 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7330 Result += llvm::utostr(ClsDefCount); Result += "]";
7331 Result +=
7332 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7333 "regular,no_dead_strip\")))= {\n";
7334 for (int i = 0; i < ClsDefCount; i++) {
7335 Result += "\t&OBJC_CLASS_$_";
7336 Result += ClassImplementation[i]->getNameAsString();
7337 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007338 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007339 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007340
7341 if (!DefinedNonLazyClasses.empty()) {
7342 if (LangOpts.MicrosoftExt)
7343 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7344 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7345 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7346 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7347 Result += ",\n";
7348 }
7349 Result += "};\n";
7350 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007351 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007352
7353 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007354 if (LangOpts.MicrosoftExt)
7355 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007356 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7357 Result += llvm::utostr(CatDefCount); Result += "]";
7358 Result +=
7359 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7360 "regular,no_dead_strip\")))= {\n";
7361 for (int i = 0; i < CatDefCount; i++) {
7362 Result += "\t&_OBJC_$_CATEGORY_";
7363 Result +=
7364 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7365 Result += "_$_";
7366 Result += CategoryImplementation[i]->getNameAsString();
7367 Result += ",\n";
7368 }
7369 Result += "};\n";
7370 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007371
7372 if (!DefinedNonLazyCategories.empty()) {
7373 if (LangOpts.MicrosoftExt)
7374 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7375 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7376 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7377 Result += "\t&_OBJC_$_CATEGORY_";
7378 Result +=
7379 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7380 Result += "_$_";
7381 Result += DefinedNonLazyCategories[i]->getNameAsString();
7382 Result += ",\n";
7383 }
7384 Result += "};\n";
7385 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007386}
7387
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007388void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7389 if (LangOpts.MicrosoftExt)
7390 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7391
7392 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7393 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007394 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007395}
7396
Fariborz Jahanian11671902012-02-07 17:11:38 +00007397/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7398/// implementation.
7399void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7400 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007401 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007402 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7403 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007404 ObjCCategoryDecl *CDecl
7405 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007406
7407 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007408 FullCategoryName += "_$_";
7409 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007410
7411 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007412 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007413
7414 // If any of our property implementations have associated getters or
7415 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007416 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007417 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007418 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007419 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007420 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007421 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007422 if (!PD)
7423 continue;
7424 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7425 InstanceMethods.push_back(Getter);
7426 if (PD->isReadOnly())
7427 continue;
7428 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7429 InstanceMethods.push_back(Setter);
7430 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007431
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007432 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7433 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7434 FullCategoryName, true);
7435
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007436 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007437
7438 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7439 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7440 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007441
7442 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007443 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007444 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7445 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007446 // Must write out all protocol definitions in current qualifier list,
7447 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007448 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007449
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007450 Write_protocol_list_initializer(Context, Result,
7451 RefedProtocols,
7452 "_OBJC_CATEGORY_PROTOCOLS_$_",
7453 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007454
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007455 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007456 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007457 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007458 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007459 "_OBJC_$_PROP_LIST_",
7460 FullCategoryName);
7461
7462 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007463 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007464 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007465 InstanceMethods,
7466 ClassMethods,
7467 RefedProtocols,
7468 ClassProperties);
7469
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007470 // Determine if this category is also "non-lazy".
7471 if (ImplementationIsNonLazy(IDecl))
7472 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007473
7474}
7475
7476void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7477 int CatDefCount = CategoryImplementation.size();
7478 if (!CatDefCount)
7479 return;
7480 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7481 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7482 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7483 for (int i = 0; i < CatDefCount; i++) {
7484 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7485 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7486 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7487 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7488 Result += ClassDecl->getName();
7489 Result += "_$_";
7490 Result += CatDecl->getName();
7491 Result += ",\n";
7492 }
7493 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007494}
7495
7496// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7497/// class methods.
7498template<typename MethodIterator>
7499void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7500 MethodIterator MethodEnd,
7501 bool IsInstanceMethod,
7502 StringRef prefix,
7503 StringRef ClassName,
7504 std::string &Result) {
7505 if (MethodBegin == MethodEnd) return;
7506
7507 if (!objc_impl_method) {
7508 /* struct _objc_method {
7509 SEL _cmd;
7510 char *method_types;
7511 void *_imp;
7512 }
7513 */
7514 Result += "\nstruct _objc_method {\n";
7515 Result += "\tSEL _cmd;\n";
7516 Result += "\tchar *method_types;\n";
7517 Result += "\tvoid *_imp;\n";
7518 Result += "};\n";
7519
7520 objc_impl_method = true;
7521 }
7522
7523 // Build _objc_method_list for class's methods if needed
7524
7525 /* struct {
7526 struct _objc_method_list *next_method;
7527 int method_count;
7528 struct _objc_method method_list[];
7529 }
7530 */
7531 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007532 Result += "\n";
7533 if (LangOpts.MicrosoftExt) {
7534 if (IsInstanceMethod)
7535 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7536 else
7537 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7538 }
7539 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007540 Result += "\tstruct _objc_method_list *next_method;\n";
7541 Result += "\tint method_count;\n";
7542 Result += "\tstruct _objc_method method_list[";
7543 Result += utostr(NumMethods);
7544 Result += "];\n} _OBJC_";
7545 Result += prefix;
7546 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7547 Result += "_METHODS_";
7548 Result += ClassName;
7549 Result += " __attribute__ ((used, section (\"__OBJC, __";
7550 Result += IsInstanceMethod ? "inst" : "cls";
7551 Result += "_meth\")))= ";
7552 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7553
7554 Result += "\t,{{(SEL)\"";
7555 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7556 std::string MethodTypeString;
7557 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7558 Result += "\", \"";
7559 Result += MethodTypeString;
7560 Result += "\", (void *)";
7561 Result += MethodInternalNames[*MethodBegin];
7562 Result += "}\n";
7563 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7564 Result += "\t ,{(SEL)\"";
7565 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7566 std::string MethodTypeString;
7567 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7568 Result += "\", \"";
7569 Result += MethodTypeString;
7570 Result += "\", (void *)";
7571 Result += MethodInternalNames[*MethodBegin];
7572 Result += "}\n";
7573 }
7574 Result += "\t }\n};\n";
7575}
7576
7577Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7578 SourceRange OldRange = IV->getSourceRange();
7579 Expr *BaseExpr = IV->getBase();
7580
7581 // Rewrite the base, but without actually doing replaces.
7582 {
7583 DisableReplaceStmtScope S(*this);
7584 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7585 IV->setBase(BaseExpr);
7586 }
7587
7588 ObjCIvarDecl *D = IV->getDecl();
7589
7590 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007591
Fariborz Jahanian11671902012-02-07 17:11:38 +00007592 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7593 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007594 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007595 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7596 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007597 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007598 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7599 clsDeclared);
7600 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7601
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007602 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007603 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007604 if (D->isBitField())
7605 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7606 else
7607 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007608
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007609 ReferencedIvars[clsDeclared].insert(D);
7610
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007611 // cast offset to "char *".
7612 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7613 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007614 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007615 BaseExpr);
7616 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7617 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007618 Context->UnsignedLongTy, nullptr,
7619 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007620 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7621 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007622 SourceLocation());
7623 BinaryOperator *addExpr =
7624 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7625 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007626 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007627 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007628 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7629 SourceLocation(),
7630 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007631 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007632 if (D->isBitField())
7633 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007634
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007635 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007636 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007637 RD = RD->getDefinition();
7638 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007639 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007640 ObjCContainerDecl *CDecl =
7641 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7642 // ivar in class extensions requires special treatment.
7643 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7644 CDecl = CatDecl->getClassInterface();
7645 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007646 RecName += "_IMPL";
7647 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7648 SourceLocation(), SourceLocation(),
7649 &Context->Idents.get(RecName.c_str()));
7650 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7651 unsigned UnsignedIntSize =
7652 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7653 Expr *Zero = IntegerLiteral::Create(*Context,
7654 llvm::APInt(UnsignedIntSize, 0),
7655 Context->UnsignedIntTy, SourceLocation());
7656 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7657 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7658 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007659 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007660 SourceLocation(),
7661 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007662 IvarT, nullptr,
7663 /*BitWidth=*/nullptr,
7664 /*Mutable=*/true, ICIS_NoInit);
7665 MemberExpr *ME = new (Context)
7666 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7667 FD->getType(), VK_LValue, OK_Ordinary);
7668 IvarT = Context->getDecltypeType(ME, ME->getType());
7669 }
7670 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007671 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007672 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007673
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007674 castExpr = NoTypeInfoCStyleCastExpr(Context,
7675 castT,
7676 CK_BitCast,
7677 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007678
7679
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007680 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007681 VK_LValue, OK_Ordinary,
7682 SourceLocation());
7683 PE = new (Context) ParenExpr(OldRange.getBegin(),
7684 OldRange.getEnd(),
7685 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007686
7687 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007688 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007689 SourceLocation(),
7690 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007691 D->getType(), nullptr,
7692 /*BitWidth=*/D->getBitWidth(),
7693 /*Mutable=*/true, ICIS_NoInit);
7694 MemberExpr *ME = new (Context)
7695 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7696 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7697 Replacement = ME;
7698
7699 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007700 else
7701 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007702 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007703
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007704 ReplaceStmtWithRange(IV, Replacement, OldRange);
7705 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007706}
Alp Toker0621cb22014-07-16 16:48:33 +00007707
7708#endif