blob: 3cacbdddf3b43ad5d3a75f8a160d8346f89f4a12 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-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 Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070031#include <memory>
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramere5753592013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahanianada71912013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 // Top Level Driver code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700188 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700224
225 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahanian040cd822013-10-07 19:54:22 +0000226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700246
247 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700283 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000379
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000412
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700417
418 void Initialize(ASTContext &context) override;
419
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000465
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
602 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000603 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000609 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700610
611 StringLiteral *getStringLiteral(StringRef Str) {
612 QualType StrType = Context->getConstantArrayType(
613 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
614 0);
615 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
616 /*Pascal=*/false, StrType, SourceLocation());
617 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000618 };
619
620}
621
622void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
623 NamedDecl *D) {
624 if (const FunctionProtoType *fproto
625 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700626 for (const auto &I : fproto->param_types())
627 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000628 // All the args are checked/rewritten. Don't call twice!
629 RewriteBlockPointerDecl(D);
630 break;
631 }
632 }
633}
634
635void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
636 const PointerType *PT = funcType->getAs<PointerType>();
637 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
638 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
639}
640
641static bool IsHeaderFile(const std::string &Filename) {
642 std::string::size_type DotPos = Filename.rfind('.');
643
644 if (DotPos == std::string::npos) {
645 // no file extension
646 return false;
647 }
648
649 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
650 // C header: .h
651 // C++ header: .hh or .H;
652 return Ext == "h" || Ext == "hh" || Ext == "H";
653}
654
655RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
656 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000657 bool silenceMacroWarn,
658 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000659 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000660 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000661 IsHeader = IsHeaderFile(inFile);
662 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
663 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000664 // FIXME. This should be an error. But if block is not called, it is OK. And it
665 // may break including some headers.
666 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
667 "rewriting block literal declared in global scope is not implemented");
668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000669 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
670 DiagnosticsEngine::Warning,
671 "rewriter doesn't support user-specified control flow semantics "
672 "for @try/@finally (code may not execute properly)");
673}
674
675ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
676 raw_ostream* OS,
677 DiagnosticsEngine &Diags,
678 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000679 bool SilenceRewriteMacroWarning,
680 bool LineInfo) {
681 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
682 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683}
684
685void RewriteModernObjC::InitializeCommon(ASTContext &context) {
686 Context = &context;
687 SM = &Context->getSourceManager();
688 TUDecl = Context->getTranslationUnitDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700689 MsgSendFunctionDecl = nullptr;
690 MsgSendSuperFunctionDecl = nullptr;
691 MsgSendStretFunctionDecl = nullptr;
692 MsgSendSuperStretFunctionDecl = nullptr;
693 MsgSendFpretFunctionDecl = nullptr;
694 GetClassFunctionDecl = nullptr;
695 GetMetaClassFunctionDecl = nullptr;
696 GetSuperClassFunctionDecl = nullptr;
697 SelGetUidFunctionDecl = nullptr;
698 CFStringFunctionDecl = nullptr;
699 ConstantStringClassReference = nullptr;
700 NSStringRecord = nullptr;
701 CurMethodDef = nullptr;
702 CurFunctionDef = nullptr;
703 GlobalVarDecl = nullptr;
704 GlobalConstructionExp = nullptr;
705 SuperStructDecl = nullptr;
706 ProtocolTypeDecl = nullptr;
707 ConstantStringDecl = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000708 BcLabelCount = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700709 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000710 NumObjCStringLiterals = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700711 PropParentMap = nullptr;
712 CurrentBody = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000713 DisableReplaceStmt = false;
714 objc_impl_method = false;
715
716 // Get the ID and start/end of the main file.
717 MainFileID = SM->getMainFileID();
718 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
719 MainFileStart = MainBuf->getBufferStart();
720 MainFileEnd = MainBuf->getBufferEnd();
721
David Blaikie4e4d0842012-03-11 07:00:24 +0000722 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000723}
724
725//===----------------------------------------------------------------------===//
726// Top Level Driver Code
727//===----------------------------------------------------------------------===//
728
729void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
730 if (Diags.hasErrorOccurred())
731 return;
732
733 // Two cases: either the decl could be in the main file, or it could be in a
734 // #included file. If the former, rewrite it now. If the later, check to see
735 // if we rewrote the #include/#import.
736 SourceLocation Loc = D->getLocation();
737 Loc = SM->getExpansionLoc(Loc);
738
739 // If this is for a builtin, ignore it.
740 if (Loc.isInvalid()) return;
741
742 // Look for built-in declarations that we need to refer during the rewrite.
743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
744 RewriteFunctionDecl(FD);
745 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
746 // declared in <Foundation/NSString.h>
747 if (FVD->getName() == "_NSConstantStringClassReference") {
748 ConstantStringClassReference = FVD;
749 return;
750 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000751 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
752 RewriteCategoryDecl(CD);
753 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
754 if (PD->isThisDeclarationADefinition())
755 RewriteProtocolDecl(PD);
756 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000757 // FIXME. This will not work in all situations and leaving it out
758 // is harmless.
759 // RewriteLinkageSpec(LSD);
760
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000761 // Recurse into linkage specifications
762 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
763 DIEnd = LSD->decls_end();
764 DI != DIEnd; ) {
765 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
766 if (!IFace->isThisDeclarationADefinition()) {
767 SmallVector<Decl *, 8> DG;
768 SourceLocation StartLoc = IFace->getLocStart();
769 do {
770 if (isa<ObjCInterfaceDecl>(*DI) &&
771 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
772 StartLoc == (*DI)->getLocStart())
773 DG.push_back(*DI);
774 else
775 break;
776
777 ++DI;
778 } while (DI != DIEnd);
779 RewriteForwardClassDecl(DG);
780 continue;
781 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000782 else {
783 // Keep track of all interface declarations seen.
784 ObjCInterfacesSeen.push_back(IFace);
785 ++DI;
786 continue;
787 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000788 }
789
790 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
791 if (!Proto->isThisDeclarationADefinition()) {
792 SmallVector<Decl *, 8> DG;
793 SourceLocation StartLoc = Proto->getLocStart();
794 do {
795 if (isa<ObjCProtocolDecl>(*DI) &&
796 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
797 StartLoc == (*DI)->getLocStart())
798 DG.push_back(*DI);
799 else
800 break;
801
802 ++DI;
803 } while (DI != DIEnd);
804 RewriteForwardProtocolDecl(DG);
805 continue;
806 }
807 }
808
809 HandleTopLevelSingleDecl(*DI);
810 ++DI;
811 }
812 }
813 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000814 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000815 return HandleDeclInMainFile(D);
816}
817
818//===----------------------------------------------------------------------===//
819// Syntactic (non-AST) Rewriting Code
820//===----------------------------------------------------------------------===//
821
822void RewriteModernObjC::RewriteInclude() {
823 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
824 StringRef MainBuf = SM->getBufferData(MainFileID);
825 const char *MainBufStart = MainBuf.begin();
826 const char *MainBufEnd = MainBuf.end();
827 size_t ImportLen = strlen("import");
828
829 // Loop over the whole file, looking for includes.
830 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
831 if (*BufPtr == '#') {
832 if (++BufPtr == MainBufEnd)
833 return;
834 while (*BufPtr == ' ' || *BufPtr == '\t')
835 if (++BufPtr == MainBufEnd)
836 return;
837 if (!strncmp(BufPtr, "import", ImportLen)) {
838 // replace import with include
839 SourceLocation ImportLoc =
840 LocStart.getLocWithOffset(BufPtr-MainBufStart);
841 ReplaceText(ImportLoc, ImportLen, "include");
842 BufPtr += ImportLen;
843 }
844 }
845 }
846}
847
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000848static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
849 ObjCIvarDecl *IvarDecl, std::string &Result) {
850 Result += "OBJC_IVAR_$_";
851 Result += IDecl->getName();
852 Result += "$";
853 Result += IvarDecl->getName();
854}
855
856std::string
857RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
858 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
859
860 // Build name of symbol holding ivar offset.
861 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000862 if (D->isBitField())
863 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
864 else
865 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000866
867
868 std::string S = "(*(";
869 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000870 if (D->isBitField())
871 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000872
873 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
874 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
875 RD = RD->getDefinition();
876 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
877 // decltype(((Foo_IMPL*)0)->bar) *
878 ObjCContainerDecl *CDecl =
879 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
880 // ivar in class extensions requires special treatment.
881 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
882 CDecl = CatDecl->getClassInterface();
883 std::string RecName = CDecl->getName();
884 RecName += "_IMPL";
885 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
886 SourceLocation(), SourceLocation(),
887 &Context->Idents.get(RecName.c_str()));
888 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
889 unsigned UnsignedIntSize =
890 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
891 Expr *Zero = IntegerLiteral::Create(*Context,
892 llvm::APInt(UnsignedIntSize, 0),
893 Context->UnsignedIntTy, SourceLocation());
894 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
895 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
896 Zero);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700897 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000898 SourceLocation(),
899 &Context->Idents.get(D->getNameAsString()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700900 IvarT, nullptr,
901 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000902 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000903 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
904 FD->getType(), VK_LValue,
905 OK_Ordinary);
906 IvarT = Context->getDecltypeType(ME, ME->getType());
907 }
908 }
909 convertObjCTypeToCStyleType(IvarT);
910 QualType castT = Context->getPointerType(IvarT);
911 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
912 S += TypeString;
913 S += ")";
914
915 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
916 S += "((char *)self + ";
917 S += IvarOffsetName;
918 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000919 if (D->isBitField()) {
920 S += ".";
921 S += D->getNameAsString();
922 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000923 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000924 return S;
925}
926
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000927/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
928/// been found in the class implementation. In this case, it must be synthesized.
929static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
930 ObjCPropertyDecl *PD,
931 bool getter) {
932 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
933 : !IMP->getInstanceMethod(PD->getSetterName());
934
935}
936
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000937void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
938 ObjCImplementationDecl *IMD,
939 ObjCCategoryImplDecl *CID) {
940 static bool objcGetPropertyDefined = false;
941 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000942 SourceLocation startGetterSetterLoc;
943
944 if (PID->getLocStart().isValid()) {
945 SourceLocation startLoc = PID->getLocStart();
946 InsertText(startLoc, "// ");
947 const char *startBuf = SM->getCharacterData(startLoc);
948 assert((*startBuf == '@') && "bogus @synthesize location");
949 const char *semiBuf = strchr(startBuf, ';');
950 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
951 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
952 }
953 else
954 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000955
956 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
957 return; // FIXME: is this correct?
958
959 // Generate the 'getter' function.
960 ObjCPropertyDecl *PD = PID->getPropertyDecl();
961 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose62bbe072013-03-15 21:41:35 +0000962 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000963
Bill Wendlingad017fa2012-12-20 19:22:21 +0000964 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000965 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000966 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
967 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000968 ObjCPropertyDecl::OBJC_PR_copy));
969 std::string Getr;
970 if (GenGetProperty && !objcGetPropertyDefined) {
971 objcGetPropertyDefined = true;
972 // FIXME. Is this attribute correct in all cases?
973 Getr = "\nextern \"C\" __declspec(dllimport) "
974 "id objc_getProperty(id, SEL, long, bool);\n";
975 }
976 RewriteObjCMethodDecl(OID->getContainingInterface(),
977 PD->getGetterMethodDecl(), Getr);
978 Getr += "{ ";
979 // Synthesize an explicit cast to gain access to the ivar.
980 // See objc-act.c:objc_synthesize_new_getter() for details.
981 if (GenGetProperty) {
982 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
983 Getr += "typedef ";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700984 const FunctionType *FPRetType = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700985 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000986 FPRetType);
987 Getr += " _TYPE";
988 if (FPRetType) {
989 Getr += ")"; // close the precedence "scope" for "*".
990
991 // Now, emit the argument types (if any).
992 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
993 Getr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -0700994 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000995 if (i) Getr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -0700996 std::string ParamStr =
997 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000998 Getr += ParamStr;
999 }
1000 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001001 if (FT->getNumParams())
1002 Getr += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001003 Getr += "...";
1004 }
1005 Getr += ")";
1006 } else
1007 Getr += "()";
1008 }
1009 Getr += ";\n";
1010 Getr += "return (_TYPE)";
1011 Getr += "objc_getProperty(self, _cmd, ";
1012 RewriteIvarOffsetComputation(OID, Getr);
1013 Getr += ", 1)";
1014 }
1015 else
1016 Getr += "return " + getIvarAccessString(OID);
1017 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001018 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001019 }
1020
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001021 if (PD->isReadOnly() ||
1022 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001023 return;
1024
1025 // Generate the 'setter' function.
1026 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001027 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001028 ObjCPropertyDecl::OBJC_PR_copy);
1029 if (GenSetProperty && !objcSetPropertyDefined) {
1030 objcSetPropertyDefined = true;
1031 // FIXME. Is this attribute correct in all cases?
1032 Setr = "\nextern \"C\" __declspec(dllimport) "
1033 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1034 }
1035
1036 RewriteObjCMethodDecl(OID->getContainingInterface(),
1037 PD->getSetterMethodDecl(), Setr);
1038 Setr += "{ ";
1039 // Synthesize an explicit cast to initialize the ivar.
1040 // See objc-act.c:objc_synthesize_new_setter() for details.
1041 if (GenSetProperty) {
1042 Setr += "objc_setProperty (self, _cmd, ";
1043 RewriteIvarOffsetComputation(OID, Setr);
1044 Setr += ", (id)";
1045 Setr += PD->getName();
1046 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001047 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001048 Setr += "0, ";
1049 else
1050 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001051 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001052 Setr += "1)";
1053 else
1054 Setr += "0)";
1055 }
1056 else {
1057 Setr += getIvarAccessString(OID) + " = ";
1058 Setr += PD->getName();
1059 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001060 Setr += "; }\n";
1061 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001062}
1063
1064static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1065 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001066 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001067 typedefString += ForwardDecl->getNameAsString();
1068 typedefString += "\n";
1069 typedefString += "#define _REWRITER_typedef_";
1070 typedefString += ForwardDecl->getNameAsString();
1071 typedefString += "\n";
1072 typedefString += "typedef struct objc_object ";
1073 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001074 // typedef struct { } _objc_exc_Classname;
1075 typedefString += ";\ntypedef struct {} _objc_exc_";
1076 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001077 typedefString += ";\n#endif\n";
1078}
1079
1080void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1081 const std::string &typedefString) {
1082 SourceLocation startLoc = ClassDecl->getLocStart();
1083 const char *startBuf = SM->getCharacterData(startLoc);
1084 const char *semiPtr = strchr(startBuf, ';');
1085 // Replace the @class with typedefs corresponding to the classes.
1086 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1087}
1088
1089void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1090 std::string typedefString;
1091 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian2330df42013-09-24 17:03:07 +00001092 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1093 if (I == D.begin()) {
1094 // Translate to typedef's that forward reference structs with the same name
1095 // as the class. As a convenience, we include the original declaration
1096 // as a comment.
1097 typedefString += "// @class ";
1098 typedefString += ForwardDecl->getNameAsString();
1099 typedefString += ";";
1100 }
1101 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001102 }
Fariborz Jahanian2330df42013-09-24 17:03:07 +00001103 else
1104 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001105 }
1106 DeclGroupRef::iterator I = D.begin();
1107 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1108}
1109
1110void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper6b9240e2013-07-05 19:34:19 +00001111 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001112 std::string typedefString;
1113 for (unsigned i = 0; i < D.size(); i++) {
1114 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1115 if (i == 0) {
1116 typedefString += "// @class ";
1117 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001118 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001119 }
1120 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1121 }
1122 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1123}
1124
1125void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1126 // When method is a synthesized one, such as a getter/setter there is
1127 // nothing to rewrite.
1128 if (Method->isImplicit())
1129 return;
1130 SourceLocation LocStart = Method->getLocStart();
1131 SourceLocation LocEnd = Method->getLocEnd();
1132
1133 if (SM->getExpansionLineNumber(LocEnd) >
1134 SM->getExpansionLineNumber(LocStart)) {
1135 InsertText(LocStart, "#if 0\n");
1136 ReplaceText(LocEnd, 1, ";\n#endif\n");
1137 } else {
1138 InsertText(LocStart, "// ");
1139 }
1140}
1141
1142void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1143 SourceLocation Loc = prop->getAtLoc();
1144
1145 ReplaceText(Loc, 0, "// ");
1146 // FIXME: handle properties that are declared across multiple lines.
1147}
1148
1149void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1150 SourceLocation LocStart = CatDecl->getLocStart();
1151
1152 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001153 if (CatDecl->getIvarRBraceLoc().isValid()) {
1154 ReplaceText(LocStart, 1, "/** ");
1155 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1156 }
1157 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001158 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001159 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001160
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 for (auto *I : CatDecl->properties())
1162 RewriteProperty(I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001163
Stephen Hines651f13c2014-04-23 16:59:28 -07001164 for (auto *I : CatDecl->instance_methods())
1165 RewriteMethodDeclaration(I);
1166 for (auto *I : CatDecl->class_methods())
1167 RewriteMethodDeclaration(I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001168
1169 // Lastly, comment out the @end.
1170 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001171 strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001172}
1173
1174void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1175 SourceLocation LocStart = PDecl->getLocStart();
1176 assert(PDecl->isThisDeclarationADefinition());
1177
1178 // FIXME: handle protocol headers that are declared across multiple lines.
1179 ReplaceText(LocStart, 0, "// ");
1180
Stephen Hines651f13c2014-04-23 16:59:28 -07001181 for (auto *I : PDecl->instance_methods())
1182 RewriteMethodDeclaration(I);
1183 for (auto *I : PDecl->class_methods())
1184 RewriteMethodDeclaration(I);
1185 for (auto *I : PDecl->properties())
1186 RewriteProperty(I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001187
1188 // Lastly, comment out the @end.
1189 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001190 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001191
1192 // Must comment out @optional/@required
1193 const char *startBuf = SM->getCharacterData(LocStart);
1194 const char *endBuf = SM->getCharacterData(LocEnd);
1195 for (const char *p = startBuf; p < endBuf; p++) {
1196 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1197 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1198 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1199
1200 }
1201 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1202 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1203 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1204
1205 }
1206 }
1207}
1208
1209void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1210 SourceLocation LocStart = (*D.begin())->getLocStart();
1211 if (LocStart.isInvalid())
1212 llvm_unreachable("Invalid SourceLocation");
1213 // FIXME: handle forward protocol that are declared across multiple lines.
1214 ReplaceText(LocStart, 0, "// ");
1215}
1216
1217void
Craig Topper6b9240e2013-07-05 19:34:19 +00001218RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001219 SourceLocation LocStart = DG[0]->getLocStart();
1220 if (LocStart.isInvalid())
1221 llvm_unreachable("Invalid SourceLocation");
1222 // FIXME: handle forward protocol that are declared across multiple lines.
1223 ReplaceText(LocStart, 0, "// ");
1224}
1225
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001226void
1227RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1228 SourceLocation LocStart = LSD->getExternLoc();
1229 if (LocStart.isInvalid())
1230 llvm_unreachable("Invalid extern SourceLocation");
1231
1232 ReplaceText(LocStart, 0, "// ");
1233 if (!LSD->hasBraces())
1234 return;
1235 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1236 SourceLocation LocRBrace = LSD->getRBraceLoc();
1237 if (LocRBrace.isInvalid())
1238 llvm_unreachable("Invalid rbrace SourceLocation");
1239 ReplaceText(LocRBrace, 0, "// ");
1240}
1241
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001242void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1243 const FunctionType *&FPRetType) {
1244 if (T->isObjCQualifiedIdType())
1245 ResultStr += "id";
1246 else if (T->isFunctionPointerType() ||
1247 T->isBlockPointerType()) {
1248 // needs special handling, since pointer-to-functions have special
1249 // syntax (where a decaration models use).
1250 QualType retType = T;
1251 QualType PointeeTy;
1252 if (const PointerType* PT = retType->getAs<PointerType>())
1253 PointeeTy = PT->getPointeeType();
1254 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1255 PointeeTy = BPT->getPointeeType();
1256 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001257 ResultStr +=
1258 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 ResultStr += "(*";
1260 }
1261 } else
1262 ResultStr += T.getAsString(Context->getPrintingPolicy());
1263}
1264
1265void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1266 ObjCMethodDecl *OMD,
1267 std::string &ResultStr) {
1268 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001269 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001270 ResultStr += "\nstatic ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001271 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001272 ResultStr += " ";
1273
1274 // Unique method name
1275 std::string NameStr;
1276
1277 if (OMD->isInstanceMethod())
1278 NameStr += "_I_";
1279 else
1280 NameStr += "_C_";
1281
1282 NameStr += IDecl->getNameAsString();
1283 NameStr += "_";
1284
1285 if (ObjCCategoryImplDecl *CID =
1286 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1287 NameStr += CID->getNameAsString();
1288 NameStr += "_";
1289 }
1290 // Append selector names, replacing ':' with '_'
1291 {
1292 std::string selString = OMD->getSelector().getAsString();
1293 int len = selString.size();
1294 for (int i = 0; i < len; i++)
1295 if (selString[i] == ':')
1296 selString[i] = '_';
1297 NameStr += selString;
1298 }
1299 // Remember this name for metadata emission
1300 MethodInternalNames[OMD] = NameStr;
1301 ResultStr += NameStr;
1302
1303 // Rewrite arguments
1304 ResultStr += "(";
1305
1306 // invisible arguments
1307 if (OMD->isInstanceMethod()) {
1308 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1309 selfTy = Context->getPointerType(selfTy);
1310 if (!LangOpts.MicrosoftExt) {
1311 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1312 ResultStr += "struct ";
1313 }
1314 // When rewriting for Microsoft, explicitly omit the structure name.
1315 ResultStr += IDecl->getNameAsString();
1316 ResultStr += " *";
1317 }
1318 else
1319 ResultStr += Context->getObjCClassType().getAsString(
1320 Context->getPrintingPolicy());
1321
1322 ResultStr += " self, ";
1323 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1324 ResultStr += " _cmd";
1325
1326 // Method arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07001327 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001328 ResultStr += ", ";
1329 if (PDecl->getType()->isObjCQualifiedIdType()) {
1330 ResultStr += "id ";
1331 ResultStr += PDecl->getNameAsString();
1332 } else {
1333 std::string Name = PDecl->getNameAsString();
1334 QualType QT = PDecl->getType();
1335 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001336 (void)convertBlockPointerToFunctionPointer(QT);
1337 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001338 ResultStr += Name;
1339 }
1340 }
1341 if (OMD->isVariadic())
1342 ResultStr += ", ...";
1343 ResultStr += ") ";
1344
1345 if (FPRetType) {
1346 ResultStr += ")"; // close the precedence "scope" for "*".
1347
1348 // Now, emit the argument types (if any).
1349 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1350 ResultStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07001351 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001352 if (i) ResultStr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001353 std::string ParamStr =
1354 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001355 ResultStr += ParamStr;
1356 }
1357 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001358 if (FT->getNumParams())
1359 ResultStr += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001360 ResultStr += "...";
1361 }
1362 ResultStr += ")";
1363 } else {
1364 ResultStr += "()";
1365 }
1366 }
1367}
1368void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1369 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1370 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1371
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001372 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001373 if (IMD->getIvarRBraceLoc().isValid()) {
1374 ReplaceText(IMD->getLocStart(), 1, "/** ");
1375 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001376 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001377 else {
1378 InsertText(IMD->getLocStart(), "// ");
1379 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001380 }
1381 else
1382 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383
Stephen Hines651f13c2014-04-23 16:59:28 -07001384 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001385 std::string ResultStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001386 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1387 SourceLocation LocStart = OMD->getLocStart();
1388 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1389
1390 const char *startBuf = SM->getCharacterData(LocStart);
1391 const char *endBuf = SM->getCharacterData(LocEnd);
1392 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1393 }
1394
Stephen Hines651f13c2014-04-23 16:59:28 -07001395 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001396 std::string ResultStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001397 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1398 SourceLocation LocStart = OMD->getLocStart();
1399 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1400
1401 const char *startBuf = SM->getCharacterData(LocStart);
1402 const char *endBuf = SM->getCharacterData(LocEnd);
1403 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1404 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001405 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1406 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001407
1408 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1409}
1410
1411void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001412 // Do not synthesize more than once.
1413 if (ObjCSynthesizedStructs.count(ClassDecl))
1414 return;
1415 // Make sure super class's are written before current class is written.
1416 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1417 while (SuperClass) {
1418 RewriteInterfaceDecl(SuperClass);
1419 SuperClass = SuperClass->getSuperClass();
1420 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001421 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001422 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001423 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001424 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001425 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1426
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001427 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001428 // Mark this typedef as having been written into its c++ equivalent.
1429 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001430
Stephen Hines651f13c2014-04-23 16:59:28 -07001431 for (auto *I : ClassDecl->properties())
1432 RewriteProperty(I);
1433 for (auto *I : ClassDecl->instance_methods())
1434 RewriteMethodDeclaration(I);
1435 for (auto *I : ClassDecl->class_methods())
1436 RewriteMethodDeclaration(I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001437
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001438 // Lastly, comment out the @end.
1439 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001440 "/* @end */\n");
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001441 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001442}
1443
1444Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1445 SourceRange OldRange = PseudoOp->getSourceRange();
1446
1447 // We just magically know some things about the structure of this
1448 // expression.
1449 ObjCMessageExpr *OldMsg =
1450 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1451 PseudoOp->getNumSemanticExprs() - 1));
1452
1453 // Because the rewriter doesn't allow us to rewrite rewritten code,
1454 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001455 Expr *Base;
1456 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001457 {
1458 DisableReplaceStmtScope S(*this);
1459
1460 // Rebuild the base expression if we have one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001461 Base = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001462 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1463 Base = OldMsg->getInstanceReceiver();
1464 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1465 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1466 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001467
1468 unsigned numArgs = OldMsg->getNumArgs();
1469 for (unsigned i = 0; i < numArgs; i++) {
1470 Expr *Arg = OldMsg->getArg(i);
1471 if (isa<OpaqueValueExpr>(Arg))
1472 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1473 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1474 Args.push_back(Arg);
1475 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001476 }
1477
1478 // TODO: avoid this copy.
1479 SmallVector<SourceLocation, 1> SelLocs;
1480 OldMsg->getSelectorLocs(SelLocs);
1481
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001482 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001483 switch (OldMsg->getReceiverKind()) {
1484 case ObjCMessageExpr::Class:
1485 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1486 OldMsg->getValueKind(),
1487 OldMsg->getLeftLoc(),
1488 OldMsg->getClassReceiverTypeInfo(),
1489 OldMsg->getSelector(),
1490 SelLocs,
1491 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001492 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001493 OldMsg->getRightLoc(),
1494 OldMsg->isImplicit());
1495 break;
1496
1497 case ObjCMessageExpr::Instance:
1498 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1499 OldMsg->getValueKind(),
1500 OldMsg->getLeftLoc(),
1501 Base,
1502 OldMsg->getSelector(),
1503 SelLocs,
1504 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001505 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001506 OldMsg->getRightLoc(),
1507 OldMsg->isImplicit());
1508 break;
1509
1510 case ObjCMessageExpr::SuperClass:
1511 case ObjCMessageExpr::SuperInstance:
1512 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1513 OldMsg->getValueKind(),
1514 OldMsg->getLeftLoc(),
1515 OldMsg->getSuperLoc(),
1516 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1517 OldMsg->getSuperType(),
1518 OldMsg->getSelector(),
1519 SelLocs,
1520 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001521 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001522 OldMsg->getRightLoc(),
1523 OldMsg->isImplicit());
1524 break;
1525 }
1526
1527 Stmt *Replacement = SynthMessageExpr(NewMsg);
1528 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1529 return Replacement;
1530}
1531
1532Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1533 SourceRange OldRange = PseudoOp->getSourceRange();
1534
1535 // We just magically know some things about the structure of this
1536 // expression.
1537 ObjCMessageExpr *OldMsg =
1538 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1539
1540 // Because the rewriter doesn't allow us to rewrite rewritten code,
1541 // we need to suppress rewriting the sub-statements.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001542 Expr *Base = nullptr;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001543 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001544 {
1545 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001546 // Rebuild the base expression if we have one.
1547 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1548 Base = OldMsg->getInstanceReceiver();
1549 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1550 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1551 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001552 unsigned numArgs = OldMsg->getNumArgs();
1553 for (unsigned i = 0; i < numArgs; i++) {
1554 Expr *Arg = OldMsg->getArg(i);
1555 if (isa<OpaqueValueExpr>(Arg))
1556 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1557 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1558 Args.push_back(Arg);
1559 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001560 }
1561
1562 // Intentionally empty.
1563 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001564
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001565 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001566 switch (OldMsg->getReceiverKind()) {
1567 case ObjCMessageExpr::Class:
1568 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1569 OldMsg->getValueKind(),
1570 OldMsg->getLeftLoc(),
1571 OldMsg->getClassReceiverTypeInfo(),
1572 OldMsg->getSelector(),
1573 SelLocs,
1574 OldMsg->getMethodDecl(),
1575 Args,
1576 OldMsg->getRightLoc(),
1577 OldMsg->isImplicit());
1578 break;
1579
1580 case ObjCMessageExpr::Instance:
1581 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1582 OldMsg->getValueKind(),
1583 OldMsg->getLeftLoc(),
1584 Base,
1585 OldMsg->getSelector(),
1586 SelLocs,
1587 OldMsg->getMethodDecl(),
1588 Args,
1589 OldMsg->getRightLoc(),
1590 OldMsg->isImplicit());
1591 break;
1592
1593 case ObjCMessageExpr::SuperClass:
1594 case ObjCMessageExpr::SuperInstance:
1595 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1596 OldMsg->getValueKind(),
1597 OldMsg->getLeftLoc(),
1598 OldMsg->getSuperLoc(),
1599 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1600 OldMsg->getSuperType(),
1601 OldMsg->getSelector(),
1602 SelLocs,
1603 OldMsg->getMethodDecl(),
1604 Args,
1605 OldMsg->getRightLoc(),
1606 OldMsg->isImplicit());
1607 break;
1608 }
1609
1610 Stmt *Replacement = SynthMessageExpr(NewMsg);
1611 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1612 return Replacement;
1613}
1614
1615/// SynthCountByEnumWithState - To print:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001616/// ((NSUInteger (*)
1617/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001618/// (void *)objc_msgSend)((id)l_collection,
1619/// sel_registerName(
1620/// "countByEnumeratingWithState:objects:count:"),
1621/// &enumState,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001622/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001623///
1624void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001625 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1626 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001627 buf += "\n\t\t";
1628 buf += "((id)l_collection,\n\t\t";
1629 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1630 buf += "\n\t\t";
1631 buf += "&enumState, "
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001632 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001633}
1634
1635/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1636/// statement to exit to its outer synthesized loop.
1637///
1638Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1639 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1640 return S;
1641 // replace break with goto __break_label
1642 std::string buf;
1643
1644 SourceLocation startLoc = S->getLocStart();
1645 buf = "goto __break_label_";
1646 buf += utostr(ObjCBcLabelNo.back());
1647 ReplaceText(startLoc, strlen("break"), buf);
1648
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001649 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001650}
1651
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001652void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1653 SourceLocation Loc,
1654 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001655 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001656 LineString += "\n#line ";
1657 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1658 LineString += utostr(PLoc.getLine());
1659 LineString += " \"";
1660 LineString += Lexer::Stringify(PLoc.getFilename());
1661 LineString += "\"\n";
1662 }
1663}
1664
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001665/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1666/// statement to continue with its inner synthesized loop.
1667///
1668Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1669 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1670 return S;
1671 // replace continue with goto __continue_label
1672 std::string buf;
1673
1674 SourceLocation startLoc = S->getLocStart();
1675 buf = "goto __continue_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 ReplaceText(startLoc, strlen("continue"), buf);
1678
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001679 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001680}
1681
1682/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1683/// It rewrites:
1684/// for ( type elem in collection) { stmts; }
1685
1686/// Into:
1687/// {
1688/// type elem;
1689/// struct __objcFastEnumerationState enumState = { 0 };
1690/// id __rw_items[16];
1691/// id l_collection = (id)collection;
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001692/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001693/// objects:__rw_items count:16];
1694/// if (limit) {
1695/// unsigned long startMutations = *enumState.mutationsPtr;
1696/// do {
1697/// unsigned long counter = 0;
1698/// do {
1699/// if (startMutations != *enumState.mutationsPtr)
1700/// objc_enumerationMutation(l_collection);
1701/// elem = (type)enumState.itemsPtr[counter++];
1702/// stmts;
1703/// __continue_label: ;
1704/// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001705/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1706/// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001707/// elem = nil;
1708/// __break_label: ;
1709/// }
1710/// else
1711/// elem = nil;
1712/// }
1713///
1714Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1715 SourceLocation OrigEnd) {
1716 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1717 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1718 "ObjCForCollectionStmt Statement stack mismatch");
1719 assert(!ObjCBcLabelNo.empty() &&
1720 "ObjCForCollectionStmt - Label No stack empty");
1721
1722 SourceLocation startLoc = S->getLocStart();
1723 const char *startBuf = SM->getCharacterData(startLoc);
1724 StringRef elementName;
1725 std::string elementTypeAsString;
1726 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001727 // line directive first.
1728 SourceLocation ForEachLoc = S->getForLoc();
1729 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1730 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001731 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1732 // type elem;
1733 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1734 QualType ElementType = cast<ValueDecl>(D)->getType();
1735 if (ElementType->isObjCQualifiedIdType() ||
1736 ElementType->isObjCQualifiedInterfaceType())
1737 // Simply use 'id' for all qualified types.
1738 elementTypeAsString = "id";
1739 else
1740 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1741 buf += elementTypeAsString;
1742 buf += " ";
1743 elementName = D->getName();
1744 buf += elementName;
1745 buf += ";\n\t";
1746 }
1747 else {
1748 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1749 elementName = DR->getDecl()->getName();
1750 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1751 if (VD->getType()->isObjCQualifiedIdType() ||
1752 VD->getType()->isObjCQualifiedInterfaceType())
1753 // Simply use 'id' for all qualified types.
1754 elementTypeAsString = "id";
1755 else
1756 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1757 }
1758
1759 // struct __objcFastEnumerationState enumState = { 0 };
1760 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1761 // id __rw_items[16];
1762 buf += "id __rw_items[16];\n\t";
1763 // id l_collection = (id)
1764 buf += "id l_collection = (id)";
1765 // Find start location of 'collection' the hard way!
1766 const char *startCollectionBuf = startBuf;
1767 startCollectionBuf += 3; // skip 'for'
1768 startCollectionBuf = strchr(startCollectionBuf, '(');
1769 startCollectionBuf++; // skip '('
1770 // find 'in' and skip it.
1771 while (*startCollectionBuf != ' ' ||
1772 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1773 (*(startCollectionBuf+3) != ' ' &&
1774 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1775 startCollectionBuf++;
1776 startCollectionBuf += 3;
1777
1778 // Replace: "for (type element in" with string constructed thus far.
1779 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1780 // Replace ')' in for '(' type elem in collection ')' with ';'
1781 SourceLocation rightParenLoc = S->getRParenLoc();
1782 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1783 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1784 buf = ";\n\t";
1785
1786 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1787 // objects:__rw_items count:16];
1788 // which is synthesized into:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001789 // NSUInteger limit =
1790 // ((NSUInteger (*)
1791 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001792 // (void *)objc_msgSend)((id)l_collection,
1793 // sel_registerName(
1794 // "countByEnumeratingWithState:objects:count:"),
1795 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001796 // (id *)__rw_items, (NSUInteger)16);
1797 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001798 SynthCountByEnumWithState(buf);
1799 buf += ";\n\t";
1800 /// if (limit) {
1801 /// unsigned long startMutations = *enumState.mutationsPtr;
1802 /// do {
1803 /// unsigned long counter = 0;
1804 /// do {
1805 /// if (startMutations != *enumState.mutationsPtr)
1806 /// objc_enumerationMutation(l_collection);
1807 /// elem = (type)enumState.itemsPtr[counter++];
1808 buf += "if (limit) {\n\t";
1809 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1810 buf += "do {\n\t\t";
1811 buf += "unsigned long counter = 0;\n\t\t";
1812 buf += "do {\n\t\t\t";
1813 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1814 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1815 buf += elementName;
1816 buf += " = (";
1817 buf += elementTypeAsString;
1818 buf += ")enumState.itemsPtr[counter++];";
1819 // Replace ')' in for '(' type elem in collection ')' with all of these.
1820 ReplaceText(lparenLoc, 1, buf);
1821
1822 /// __continue_label: ;
1823 /// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001824 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1825 /// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001826 /// elem = nil;
1827 /// __break_label: ;
1828 /// }
1829 /// else
1830 /// elem = nil;
1831 /// }
1832 ///
1833 buf = ";\n\t";
1834 buf += "__continue_label_";
1835 buf += utostr(ObjCBcLabelNo.back());
1836 buf += ": ;";
1837 buf += "\n\t\t";
1838 buf += "} while (counter < limit);\n\t";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001839 buf += "} while ((limit = ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001840 SynthCountByEnumWithState(buf);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001841 buf += "));\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001842 buf += elementName;
1843 buf += " = ((";
1844 buf += elementTypeAsString;
1845 buf += ")0);\n\t";
1846 buf += "__break_label_";
1847 buf += utostr(ObjCBcLabelNo.back());
1848 buf += ": ;\n\t";
1849 buf += "}\n\t";
1850 buf += "else\n\t\t";
1851 buf += elementName;
1852 buf += " = ((";
1853 buf += elementTypeAsString;
1854 buf += ")0);\n\t";
1855 buf += "}\n";
1856
1857 // Insert all these *after* the statement body.
1858 // FIXME: If this should support Obj-C++, support CXXTryStmt
1859 if (isa<CompoundStmt>(S->getBody())) {
1860 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1861 InsertText(endBodyLoc, buf);
1862 } else {
1863 /* Need to treat single statements specially. For example:
1864 *
1865 * for (A *a in b) if (stuff()) break;
1866 * for (A *a in b) xxxyy;
1867 *
1868 * The following code simply scans ahead to the semi to find the actual end.
1869 */
1870 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1871 const char *semiBuf = strchr(stmtBuf, ';');
1872 assert(semiBuf && "Can't find ';'");
1873 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1874 InsertText(endBodyLoc, buf);
1875 }
1876 Stmts.pop_back();
1877 ObjCBcLabelNo.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001878 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001879}
1880
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001881static void Write_RethrowObject(std::string &buf) {
1882 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1883 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1884 buf += "\tid rethrow;\n";
1885 buf += "\t} _fin_force_rethow(_rethrow);";
1886}
1887
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001888/// RewriteObjCSynchronizedStmt -
1889/// This routine rewrites @synchronized(expr) stmt;
1890/// into:
1891/// objc_sync_enter(expr);
1892/// @try stmt @finally { objc_sync_exit(expr); }
1893///
1894Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1895 // Get the start location and compute the semi location.
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 assert((*startBuf == '@') && "bogus @synchronized location");
1900
1901 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001902 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1903 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanian786e56f2013-09-17 17:51:48 +00001904 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001905
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001906 const char *lparenBuf = startBuf;
1907 while (*lparenBuf != '(') lparenBuf++;
1908 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001909
1910 buf = "; objc_sync_enter(_sync_obj);\n";
1911 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1912 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1913 buf += "\n\tid sync_exit;";
1914 buf += "\n\t} _sync_exit(_sync_obj);\n";
1915
1916 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1917 // the sync expression is typically a message expression that's already
1918 // been rewritten! (which implies the SourceLocation's are invalid).
1919 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1920 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1921 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1922 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1923
1924 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1925 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1926 assert (*LBraceLocBuf == '{');
1927 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001928
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001929 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001930 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1931 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001932
1933 buf = "} catch (id e) {_rethrow = e;}\n";
1934 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001935 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001936 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001937
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001938 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001939
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001940 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001941}
1942
1943void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1944{
1945 // Perform a bottom up traversal of all children.
1946 for (Stmt::child_range CI = S->children(); CI; ++CI)
1947 if (*CI)
1948 WarnAboutReturnGotoStmts(*CI);
1949
1950 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1951 Diags.Report(Context->getFullLoc(S->getLocStart()),
1952 TryFinallyContainsReturnDiag);
1953 }
1954 return;
1955}
1956
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001957Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1958 SourceLocation startLoc = S->getAtLoc();
1959 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001960 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1961 "{ __AtAutoreleasePool __autoreleasepool; ");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001962
1963 return nullptr;
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001964}
1965
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001966Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001967 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001968 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001969 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001970 SourceLocation TryLocation = S->getAtTryLoc();
1971 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001972
1973 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001974 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001975 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001976 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001977 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001978 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001979 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001980 // Get the start location and compute the semi location.
1981 SourceLocation startLoc = S->getLocStart();
1982 const char *startBuf = SM->getCharacterData(startLoc);
1983
1984 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001985 if (finalStmt)
1986 ReplaceText(startLoc, 1, buf);
1987 else
1988 // @try -> try
1989 ReplaceText(startLoc, 1, "");
1990
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001991 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1992 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001993 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001994
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001995 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001996 bool AtRemoved = false;
1997 if (catchDecl) {
1998 QualType t = catchDecl->getType();
1999 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2000 // Should be a pointer to a class.
2001 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2002 if (IDecl) {
2003 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002004 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2005
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002006 startBuf = SM->getCharacterData(startLoc);
2007 assert((*startBuf == '@') && "bogus @catch location");
2008 SourceLocation rParenLoc = Catch->getRParenLoc();
2009 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2010
2011 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002012 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002013 Result += " *_"; Result += catchDecl->getNameAsString();
2014 Result += ")";
2015 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2016 // Foo *e = (Foo *)_e;
2017 Result.clear();
2018 Result = "{ ";
2019 Result += IDecl->getNameAsString();
2020 Result += " *"; Result += catchDecl->getNameAsString();
2021 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2022 Result += "_"; Result += catchDecl->getNameAsString();
2023
2024 Result += "; ";
2025 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2026 ReplaceText(lBraceLoc, 1, Result);
2027 AtRemoved = true;
2028 }
2029 }
2030 }
2031 if (!AtRemoved)
2032 // @catch -> catch
2033 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002034
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002035 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002036 if (finalStmt) {
2037 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002038 SourceLocation FinallyLoc = finalStmt->getLocStart();
2039
2040 if (noCatch) {
2041 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2042 buf += "catch (id e) {_rethrow = e;}\n";
2043 }
2044 else {
2045 buf += "}\n";
2046 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2047 buf += "catch (id e) {_rethrow = e;}\n";
2048 }
2049
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002050 SourceLocation startFinalLoc = finalStmt->getLocStart();
2051 ReplaceText(startFinalLoc, 8, buf);
2052 Stmt *body = finalStmt->getFinallyBody();
2053 SourceLocation startFinalBodyLoc = body->getLocStart();
2054 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002055 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002056 ReplaceText(startFinalBodyLoc, 1, buf);
2057
2058 SourceLocation endFinalBodyLoc = body->getLocEnd();
2059 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002060 // Now check for any return/continue/go statements within the @try.
2061 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002062 }
2063
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002064 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002065}
2066
2067// This can't be done with ReplaceStmt(S, ThrowExpr), since
2068// the throw expression is typically a message expression that's already
2069// been rewritten! (which implies the SourceLocation's are invalid).
2070Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2071 // Get the start location and compute the semi location.
2072 SourceLocation startLoc = S->getLocStart();
2073 const char *startBuf = SM->getCharacterData(startLoc);
2074
2075 assert((*startBuf == '@') && "bogus @throw location");
2076
2077 std::string buf;
2078 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2079 if (S->getThrowExpr())
2080 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002081 else
2082 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002083
2084 // handle "@ throw" correctly.
2085 const char *wBuf = strchr(startBuf, 'w');
2086 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2087 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2088
Fariborz Jahaniana09cd812013-02-11 19:30:33 +00002089 SourceLocation endLoc = S->getLocEnd();
2090 const char *endBuf = SM->getCharacterData(endLoc);
2091 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002092 assert((*semiBuf == ';') && "@throw: can't find ';'");
2093 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002094 if (S->getThrowExpr())
2095 ReplaceText(semiLoc, 1, ");");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002096 return nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002097}
2098
2099Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2100 // Create a new string expression.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002101 std::string StrEncoding;
2102 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Stephen Hines651f13c2014-04-23 16:59:28 -07002103 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002104 ReplaceStmt(Exp, Replacement);
2105
2106 // Replace this subexpr in the parent.
2107 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2108 return Replacement;
2109}
2110
2111Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2112 if (!SelGetUidFunctionDecl)
2113 SynthSelGetUidFunctionDecl();
2114 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2115 // Create a call to sel_registerName("selName").
2116 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002117 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002118 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2119 &SelExprs[0], SelExprs.size());
2120 ReplaceStmt(Exp, SelExp);
2121 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2122 return SelExp;
2123}
2124
2125CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2126 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2127 SourceLocation EndLoc) {
2128 // Get the type, we will need to reference it in a couple spots.
2129 QualType msgSendType = FD->getType();
2130
2131 // Create a reference to the objc_msgSend() declaration.
2132 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002133 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002134
2135 // Now, we cast the reference to a pointer to the objc_msgSend type.
2136 QualType pToFunc = Context->getPointerType(msgSendType);
2137 ImplicitCastExpr *ICE =
2138 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002139 DRE, nullptr, VK_RValue);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002140
2141 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2142
2143 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002144 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002145 FT->getCallResultType(*Context),
2146 VK_RValue, EndLoc);
2147 return Exp;
2148}
2149
2150static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2151 const char *&startRef, const char *&endRef) {
2152 while (startBuf < endBuf) {
2153 if (*startBuf == '<')
2154 startRef = startBuf; // mark the start.
2155 if (*startBuf == '>') {
2156 if (startRef && *startRef == '<') {
2157 endRef = startBuf; // mark the end.
2158 return true;
2159 }
2160 return false;
2161 }
2162 startBuf++;
2163 }
2164 return false;
2165}
2166
2167static void scanToNextArgument(const char *&argRef) {
2168 int angle = 0;
2169 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2170 if (*argRef == '<')
2171 angle++;
2172 else if (*argRef == '>')
2173 angle--;
2174 argRef++;
2175 }
2176 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2177}
2178
2179bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2180 if (T->isObjCQualifiedIdType())
2181 return true;
2182 if (const PointerType *PT = T->getAs<PointerType>()) {
2183 if (PT->getPointeeType()->isObjCQualifiedIdType())
2184 return true;
2185 }
2186 if (T->isObjCObjectPointerType()) {
2187 T = T->getPointeeType();
2188 return T->isObjCQualifiedInterfaceType();
2189 }
2190 if (T->isArrayType()) {
2191 QualType ElemTy = Context->getBaseElementType(T);
2192 return needToScanForQualifiers(ElemTy);
2193 }
2194 return false;
2195}
2196
2197void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2198 QualType Type = E->getType();
2199 if (needToScanForQualifiers(Type)) {
2200 SourceLocation Loc, EndLoc;
2201
2202 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2203 Loc = ECE->getLParenLoc();
2204 EndLoc = ECE->getRParenLoc();
2205 } else {
2206 Loc = E->getLocStart();
2207 EndLoc = E->getLocEnd();
2208 }
2209 // This will defend against trying to rewrite synthesized expressions.
2210 if (Loc.isInvalid() || EndLoc.isInvalid())
2211 return;
2212
2213 const char *startBuf = SM->getCharacterData(Loc);
2214 const char *endBuf = SM->getCharacterData(EndLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002215 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002216 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2217 // Get the locations of the startRef, endRef.
2218 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2219 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2220 // Comment out the protocol references.
2221 InsertText(LessLoc, "/*");
2222 InsertText(GreaterLoc, "*/");
2223 }
2224 }
2225}
2226
2227void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2228 SourceLocation Loc;
2229 QualType Type;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002230 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002231 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2232 Loc = VD->getLocation();
2233 Type = VD->getType();
2234 }
2235 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2236 Loc = FD->getLocation();
2237 // Check for ObjC 'id' and class types that have been adorned with protocol
2238 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2239 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2240 assert(funcType && "missing function type");
2241 proto = dyn_cast<FunctionProtoType>(funcType);
2242 if (!proto)
2243 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002244 Type = proto->getReturnType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002245 }
2246 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2247 Loc = FD->getLocation();
2248 Type = FD->getType();
2249 }
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00002250 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2251 Loc = TD->getLocation();
2252 Type = TD->getUnderlyingType();
2253 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002254 else
2255 return;
2256
2257 if (needToScanForQualifiers(Type)) {
2258 // Since types are unique, we need to scan the buffer.
2259
2260 const char *endBuf = SM->getCharacterData(Loc);
2261 const char *startBuf = endBuf;
2262 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2263 startBuf--; // scan backward (from the decl location) for return type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002264 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002265 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2266 // Get the locations of the startRef, endRef.
2267 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2268 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2269 // Comment out the protocol references.
2270 InsertText(LessLoc, "/*");
2271 InsertText(GreaterLoc, "*/");
2272 }
2273 }
2274 if (!proto)
2275 return; // most likely, was a variable
2276 // Now check arguments.
2277 const char *startBuf = SM->getCharacterData(Loc);
2278 const char *startFuncBuf = startBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07002279 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2280 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002281 // Since types are unique, we need to scan the buffer.
2282
2283 const char *endBuf = startBuf;
2284 // scan forward (from the decl location) for argument types.
2285 scanToNextArgument(endBuf);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002286 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002287 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2288 // Get the locations of the startRef, endRef.
2289 SourceLocation LessLoc =
2290 Loc.getLocWithOffset(startRef-startFuncBuf);
2291 SourceLocation GreaterLoc =
2292 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2293 // Comment out the protocol references.
2294 InsertText(LessLoc, "/*");
2295 InsertText(GreaterLoc, "*/");
2296 }
2297 startBuf = ++endBuf;
2298 }
2299 else {
2300 // If the function name is derived from a macro expansion, then the
2301 // argument buffer will not follow the name. Need to speak with Chris.
2302 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2303 startBuf++; // scan forward (from the decl location) for argument types.
2304 startBuf++;
2305 }
2306 }
2307}
2308
2309void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2310 QualType QT = ND->getType();
2311 const Type* TypePtr = QT->getAs<Type>();
2312 if (!isa<TypeOfExprType>(TypePtr))
2313 return;
2314 while (isa<TypeOfExprType>(TypePtr)) {
2315 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2316 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2317 TypePtr = QT->getAs<Type>();
2318 }
2319 // FIXME. This will not work for multiple declarators; as in:
2320 // __typeof__(a) b,c,d;
2321 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2322 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2323 const char *startBuf = SM->getCharacterData(DeclLoc);
2324 if (ND->getInit()) {
2325 std::string Name(ND->getNameAsString());
2326 TypeAsString += " " + Name + " = ";
2327 Expr *E = ND->getInit();
2328 SourceLocation startLoc;
2329 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2330 startLoc = ECE->getLParenLoc();
2331 else
2332 startLoc = E->getLocStart();
2333 startLoc = SM->getExpansionLoc(startLoc);
2334 const char *endBuf = SM->getCharacterData(startLoc);
2335 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2336 }
2337 else {
2338 SourceLocation X = ND->getLocEnd();
2339 X = SM->getExpansionLoc(X);
2340 const char *endBuf = SM->getCharacterData(X);
2341 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2342 }
2343}
2344
2345// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2346void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2347 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2348 SmallVector<QualType, 16> ArgTys;
2349 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2350 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002351 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002352 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002353 SourceLocation(),
2354 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002355 SelGetUidIdent, getFuncType,
2356 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002357}
2358
2359void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2360 // declared in <objc/objc.h>
2361 if (FD->getIdentifier() &&
2362 FD->getName() == "sel_registerName") {
2363 SelGetUidFunctionDecl = FD;
2364 return;
2365 }
2366 RewriteObjCQualifiedInterfaceTypes(FD);
2367}
2368
2369void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2370 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2371 const char *argPtr = TypeString.c_str();
2372 if (!strchr(argPtr, '^')) {
2373 Str += TypeString;
2374 return;
2375 }
2376 while (*argPtr) {
2377 Str += (*argPtr == '^' ? '*' : *argPtr);
2378 argPtr++;
2379 }
2380}
2381
2382// FIXME. Consolidate this routine with RewriteBlockPointerType.
2383void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2384 ValueDecl *VD) {
2385 QualType Type = VD->getType();
2386 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2387 const char *argPtr = TypeString.c_str();
2388 int paren = 0;
2389 while (*argPtr) {
2390 switch (*argPtr) {
2391 case '(':
2392 Str += *argPtr;
2393 paren++;
2394 break;
2395 case ')':
2396 Str += *argPtr;
2397 paren--;
2398 break;
2399 case '^':
2400 Str += '*';
2401 if (paren == 1)
2402 Str += VD->getNameAsString();
2403 break;
2404 default:
2405 Str += *argPtr;
2406 break;
2407 }
2408 argPtr++;
2409 }
2410}
2411
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002412void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2413 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2414 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2415 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2416 if (!proto)
2417 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002418 QualType Type = proto->getReturnType();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002419 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2420 FdStr += " ";
2421 FdStr += FD->getName();
2422 FdStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07002423 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002424 for (unsigned i = 0; i < numArgs; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002425 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002426 RewriteBlockPointerType(FdStr, ArgType);
2427 if (i+1 < numArgs)
2428 FdStr += ", ";
2429 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002430 if (FD->isVariadic()) {
2431 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2432 }
2433 else
2434 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002435 InsertText(FunLocStart, FdStr);
2436}
2437
Benjamin Kramere5753592013-09-09 14:48:42 +00002438// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2439void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2440 if (SuperConstructorFunctionDecl)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002441 return;
2442 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2443 SmallVector<QualType, 16> ArgTys;
2444 QualType argT = Context->getObjCIdType();
2445 assert(!argT.isNull() && "Can't find 'id' type");
2446 ArgTys.push_back(argT);
2447 ArgTys.push_back(argT);
2448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002449 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002450 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002451 SourceLocation(),
2452 SourceLocation(),
2453 msgSendIdent, msgSendType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002454 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002455}
2456
2457// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002468 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002469 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002472 msgSendIdent, msgSendType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002473 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002474}
2475
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002476// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002477void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2478 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002479 SmallVector<QualType, 2> ArgTys;
2480 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002481 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002482 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002484 SourceLocation(),
2485 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002486 msgSendIdent, msgSendType,
2487 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002488}
2489
2490// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2491void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2493 SmallVector<QualType, 16> ArgTys;
2494 QualType argT = Context->getObjCIdType();
2495 assert(!argT.isNull() && "Can't find 'id' type");
2496 ArgTys.push_back(argT);
2497 argT = Context->getObjCSelType();
2498 assert(!argT.isNull() && "Can't find 'SEL' type");
2499 ArgTys.push_back(argT);
2500 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002501 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002502 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002503 SourceLocation(),
2504 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002505 msgSendIdent, msgSendType,
2506 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002507}
2508
2509// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002510// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002511void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2512 IdentifierInfo *msgSendIdent =
2513 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002514 SmallVector<QualType, 2> ArgTys;
2515 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002516 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002517 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002518 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519 SourceLocation(),
2520 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002521 msgSendIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002522 msgSendType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002523 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002524}
2525
2526// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2527void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2528 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2529 SmallVector<QualType, 16> ArgTys;
2530 QualType argT = Context->getObjCIdType();
2531 assert(!argT.isNull() && "Can't find 'id' type");
2532 ArgTys.push_back(argT);
2533 argT = Context->getObjCSelType();
2534 assert(!argT.isNull() && "Can't find 'SEL' type");
2535 ArgTys.push_back(argT);
2536 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002537 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002538 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002539 SourceLocation(),
2540 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002541 msgSendIdent, msgSendType,
2542 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002543}
2544
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002545// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002546void RewriteModernObjC::SynthGetClassFunctionDecl() {
2547 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2548 SmallVector<QualType, 16> ArgTys;
2549 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002550 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002551 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002552 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002553 SourceLocation(),
2554 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002555 getClassIdent, getClassType,
2556 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002557}
2558
2559// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2560void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2561 IdentifierInfo *getSuperClassIdent =
2562 &Context->Idents.get("class_getSuperclass");
2563 SmallVector<QualType, 16> ArgTys;
2564 ArgTys.push_back(Context->getObjCClassType());
2565 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002566 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002567 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2568 SourceLocation(),
2569 SourceLocation(),
2570 getSuperClassIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002571 getClassType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002572 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002573}
2574
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002575// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002576void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2577 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2578 SmallVector<QualType, 16> ArgTys;
2579 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002580 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002581 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002582 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002583 SourceLocation(),
2584 SourceLocation(),
2585 getClassIdent, getClassType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002586 nullptr, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002587}
2588
2589Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2590 QualType strType = getConstantStringStructType();
2591
2592 std::string S = "__NSConstantStringImpl_";
2593
2594 std::string tmpName = InFileName;
2595 unsigned i;
2596 for (i=0; i < tmpName.length(); i++) {
2597 char c = tmpName.at(i);
Stephen Hines651f13c2014-04-23 16:59:28 -07002598 // replace any non-alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002599 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002600 tmpName[i] = '_';
2601 }
2602 S += tmpName;
2603 S += "_";
2604 S += utostr(NumObjCStringLiterals++);
2605
2606 Preamble += "static __NSConstantStringImpl " + S;
2607 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2608 Preamble += "0x000007c8,"; // utf8_str
2609 // The pretty printer for StringLiteral handles escape characters properly.
2610 std::string prettyBufS;
2611 llvm::raw_string_ostream prettyBuf(prettyBufS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002612 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002613 Preamble += prettyBuf.str();
2614 Preamble += ",";
2615 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2616
2617 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2618 SourceLocation(), &Context->Idents.get(S),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002619 strType, nullptr, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002620 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002621 SourceLocation());
2622 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2623 Context->getPointerType(DRE->getType()),
2624 VK_RValue, OK_Ordinary,
2625 SourceLocation());
2626 // cast to NSConstantString *
2627 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2628 CK_CPointerToObjCPointerCast, Unop);
2629 ReplaceStmt(Exp, cast);
2630 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2631 return cast;
2632}
2633
Fariborz Jahanian55947042012-03-27 20:17:30 +00002634Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2635 unsigned IntSize =
2636 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2637
2638 Expr *FlagExp = IntegerLiteral::Create(*Context,
2639 llvm::APInt(IntSize, Exp->getValue()),
2640 Context->IntTy, Exp->getLocation());
2641 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2642 CK_BitCast, FlagExp);
2643 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2644 cast);
2645 ReplaceStmt(Exp, PE);
2646 return PE;
2647}
2648
Patrick Beardeb382ec2012-04-19 00:25:12 +00002649Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002650 // synthesize declaration of helper functions needed in this routine.
2651 if (!SelGetUidFunctionDecl)
2652 SynthSelGetUidFunctionDecl();
2653 // use objc_msgSend() for all.
2654 if (!MsgSendFunctionDecl)
2655 SynthMsgSendFunctionDecl();
2656 if (!GetClassFunctionDecl)
2657 SynthGetClassFunctionDecl();
2658
2659 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2660 SourceLocation StartLoc = Exp->getLocStart();
2661 SourceLocation EndLoc = Exp->getLocEnd();
2662
2663 // Synthesize a call to objc_msgSend().
2664 SmallVector<Expr*, 4> MsgExprs;
2665 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002666
Patrick Beardeb382ec2012-04-19 00:25:12 +00002667 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2668 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2669 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002670
Patrick Beardeb382ec2012-04-19 00:25:12 +00002671 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002672 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002673 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2674 &ClsExprs[0],
2675 ClsExprs.size(),
2676 StartLoc, EndLoc);
2677 MsgExprs.push_back(Cls);
2678
Patrick Beardeb382ec2012-04-19 00:25:12 +00002679 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002680 // it will be the 2nd argument.
2681 SmallVector<Expr*, 4> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002682 SelExprs.push_back(
2683 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002684 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2685 &SelExprs[0], SelExprs.size(),
2686 StartLoc, EndLoc);
2687 MsgExprs.push_back(SelExp);
2688
Patrick Beardeb382ec2012-04-19 00:25:12 +00002689 // User provided sub-expression is the 3rd, and last, argument.
2690 Expr *subExpr = Exp->getSubExpr();
2691 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002692 QualType type = ICE->getType();
2693 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2694 CastKind CK = CK_BitCast;
2695 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2696 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002697 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002698 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002699 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002700
2701 SmallVector<QualType, 4> ArgTypes;
2702 ArgTypes.push_back(Context->getObjCIdType());
2703 ArgTypes.push_back(Context->getObjCSelType());
Stephen Hines651f13c2014-04-23 16:59:28 -07002704 for (const auto PI : BoxingMethod->parameters())
2705 ArgTypes.push_back(PI->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002706
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002707 QualType returnType = Exp->getType();
2708 // Get the type, we will need to reference it in a couple spots.
2709 QualType msgSendType = MsgSendFlavor->getType();
2710
2711 // Create a reference to the objc_msgSend() declaration.
2712 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2713 VK_LValue, SourceLocation());
2714
2715 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002716 Context->getPointerType(Context->VoidTy),
2717 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002718
2719 // Now do the "normal" pointer to function cast.
2720 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002721 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002722 castType = Context->getPointerType(castType);
2723 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2724 cast);
2725
2726 // Don't forget the parens to enforce the proper binding.
2727 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2728
2729 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002730 CallExpr *CE = new (Context)
2731 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002732 ReplaceStmt(Exp, CE);
2733 return CE;
2734}
2735
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002736Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2737 // synthesize declaration of helper functions needed in this routine.
2738 if (!SelGetUidFunctionDecl)
2739 SynthSelGetUidFunctionDecl();
2740 // use objc_msgSend() for all.
2741 if (!MsgSendFunctionDecl)
2742 SynthMsgSendFunctionDecl();
2743 if (!GetClassFunctionDecl)
2744 SynthGetClassFunctionDecl();
2745
2746 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2747 SourceLocation StartLoc = Exp->getLocStart();
2748 SourceLocation EndLoc = Exp->getLocEnd();
2749
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002750 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002751 QualType IntQT = Context->IntTy;
2752 QualType NSArrayFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002753 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002754 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002755 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2756 DeclRefExpr *NSArrayDRE =
2757 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2758 SourceLocation());
2759
2760 SmallVector<Expr*, 16> InitExprs;
2761 unsigned NumElements = Exp->getNumElements();
2762 unsigned UnsignedIntSize =
2763 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2764 Expr *count = IntegerLiteral::Create(*Context,
2765 llvm::APInt(UnsignedIntSize, NumElements),
2766 Context->UnsignedIntTy, SourceLocation());
2767 InitExprs.push_back(count);
2768 for (unsigned i = 0; i < NumElements; i++)
2769 InitExprs.push_back(Exp->getElement(i));
2770 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002771 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002772 NSArrayFType, VK_LValue, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002773
2774 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002775 SourceLocation(),
2776 &Context->Idents.get("arr"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002777 Context->getPointerType(Context->VoidPtrTy),
2778 nullptr, /*BitWidth=*/nullptr,
2779 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002780 MemberExpr *ArrayLiteralME =
2781 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2782 SourceLocation(),
2783 ARRFD->getType(), VK_LValue,
2784 OK_Ordinary);
2785 QualType ConstIdT = Context->getObjCIdType().withConst();
2786 CStyleCastExpr * ArrayLiteralObjects =
2787 NoTypeInfoCStyleCastExpr(Context,
2788 Context->getPointerType(ConstIdT),
2789 CK_BitCast,
2790 ArrayLiteralME);
2791
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002792 // Synthesize a call to objc_msgSend().
2793 SmallVector<Expr*, 32> MsgExprs;
2794 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002795 QualType expType = Exp->getType();
2796
2797 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2798 ObjCInterfaceDecl *Class =
2799 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2800
2801 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002802 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002803 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2804 &ClsExprs[0],
2805 ClsExprs.size(),
2806 StartLoc, EndLoc);
2807 MsgExprs.push_back(Cls);
2808
2809 // Create a call to sel_registerName("arrayWithObjects:count:").
2810 // it will be the 2nd argument.
2811 SmallVector<Expr*, 4> SelExprs;
2812 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Stephen Hines651f13c2014-04-23 16:59:28 -07002813 SelExprs.push_back(
2814 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002815 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2816 &SelExprs[0], SelExprs.size(),
2817 StartLoc, EndLoc);
2818 MsgExprs.push_back(SelExp);
2819
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002820 // (const id [])objects
2821 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002822
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002823 // (NSUInteger)cnt
2824 Expr *cnt = IntegerLiteral::Create(*Context,
2825 llvm::APInt(UnsignedIntSize, NumElements),
2826 Context->UnsignedIntTy, SourceLocation());
2827 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002828
2829
2830 SmallVector<QualType, 4> ArgTypes;
2831 ArgTypes.push_back(Context->getObjCIdType());
2832 ArgTypes.push_back(Context->getObjCSelType());
Stephen Hines651f13c2014-04-23 16:59:28 -07002833 for (const auto *PI : ArrayMethod->params())
2834 ArgTypes.push_back(PI->getType());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002835
2836 QualType returnType = Exp->getType();
2837 // Get the type, we will need to reference it in a couple spots.
2838 QualType msgSendType = MsgSendFlavor->getType();
2839
2840 // Create a reference to the objc_msgSend() declaration.
2841 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2842 VK_LValue, SourceLocation());
2843
2844 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2845 Context->getPointerType(Context->VoidTy),
2846 CK_BitCast, DRE);
2847
2848 // Now do the "normal" pointer to function cast.
2849 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002850 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002851 castType = Context->getPointerType(castType);
2852 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2853 cast);
2854
2855 // Don't forget the parens to enforce the proper binding.
2856 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2857
2858 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002859 CallExpr *CE = new (Context)
2860 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002861 ReplaceStmt(Exp, CE);
2862 return CE;
2863}
2864
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002865Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2866 // synthesize declaration of helper functions needed in this routine.
2867 if (!SelGetUidFunctionDecl)
2868 SynthSelGetUidFunctionDecl();
2869 // use objc_msgSend() for all.
2870 if (!MsgSendFunctionDecl)
2871 SynthMsgSendFunctionDecl();
2872 if (!GetClassFunctionDecl)
2873 SynthGetClassFunctionDecl();
2874
2875 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2876 SourceLocation StartLoc = Exp->getLocStart();
2877 SourceLocation EndLoc = Exp->getLocEnd();
2878
2879 // Build the expression: __NSContainer_literal(int, ...).arr
2880 QualType IntQT = Context->IntTy;
2881 QualType NSDictFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002882 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002883 std::string NSDictFName("__NSContainer_literal");
2884 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2885 DeclRefExpr *NSDictDRE =
2886 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2887 SourceLocation());
2888
2889 SmallVector<Expr*, 16> KeyExprs;
2890 SmallVector<Expr*, 16> ValueExprs;
2891
2892 unsigned NumElements = Exp->getNumElements();
2893 unsigned UnsignedIntSize =
2894 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2895 Expr *count = IntegerLiteral::Create(*Context,
2896 llvm::APInt(UnsignedIntSize, NumElements),
2897 Context->UnsignedIntTy, SourceLocation());
2898 KeyExprs.push_back(count);
2899 ValueExprs.push_back(count);
2900 for (unsigned i = 0; i < NumElements; i++) {
2901 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2902 KeyExprs.push_back(Element.Key);
2903 ValueExprs.push_back(Element.Value);
2904 }
2905
2906 // (const id [])objects
2907 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002908 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002909 NSDictFType, VK_LValue, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002910
2911 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002912 SourceLocation(),
2913 &Context->Idents.get("arr"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002914 Context->getPointerType(Context->VoidPtrTy),
2915 nullptr, /*BitWidth=*/nullptr,
2916 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002917 MemberExpr *DictLiteralValueME =
2918 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2919 SourceLocation(),
2920 ARRFD->getType(), VK_LValue,
2921 OK_Ordinary);
2922 QualType ConstIdT = Context->getObjCIdType().withConst();
2923 CStyleCastExpr * DictValueObjects =
2924 NoTypeInfoCStyleCastExpr(Context,
2925 Context->getPointerType(ConstIdT),
2926 CK_BitCast,
2927 DictLiteralValueME);
2928 // (const id <NSCopying> [])keys
2929 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002930 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002931 NSDictFType, VK_LValue, SourceLocation());
2932
2933 MemberExpr *DictLiteralKeyME =
2934 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2935 SourceLocation(),
2936 ARRFD->getType(), VK_LValue,
2937 OK_Ordinary);
2938
2939 CStyleCastExpr * DictKeyObjects =
2940 NoTypeInfoCStyleCastExpr(Context,
2941 Context->getPointerType(ConstIdT),
2942 CK_BitCast,
2943 DictLiteralKeyME);
2944
2945
2946
2947 // Synthesize a call to objc_msgSend().
2948 SmallVector<Expr*, 32> MsgExprs;
2949 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002950 QualType expType = Exp->getType();
2951
2952 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2953 ObjCInterfaceDecl *Class =
2954 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2955
2956 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002957 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002958 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2959 &ClsExprs[0],
2960 ClsExprs.size(),
2961 StartLoc, EndLoc);
2962 MsgExprs.push_back(Cls);
2963
2964 // Create a call to sel_registerName("arrayWithObjects:count:").
2965 // it will be the 2nd argument.
2966 SmallVector<Expr*, 4> SelExprs;
2967 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Stephen Hines651f13c2014-04-23 16:59:28 -07002968 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002969 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2970 &SelExprs[0], SelExprs.size(),
2971 StartLoc, EndLoc);
2972 MsgExprs.push_back(SelExp);
2973
2974 // (const id [])objects
2975 MsgExprs.push_back(DictValueObjects);
2976
2977 // (const id <NSCopying> [])keys
2978 MsgExprs.push_back(DictKeyObjects);
2979
2980 // (NSUInteger)cnt
2981 Expr *cnt = IntegerLiteral::Create(*Context,
2982 llvm::APInt(UnsignedIntSize, NumElements),
2983 Context->UnsignedIntTy, SourceLocation());
2984 MsgExprs.push_back(cnt);
2985
2986
2987 SmallVector<QualType, 8> ArgTypes;
2988 ArgTypes.push_back(Context->getObjCIdType());
2989 ArgTypes.push_back(Context->getObjCSelType());
Stephen Hines651f13c2014-04-23 16:59:28 -07002990 for (const auto *PI : DictMethod->params()) {
2991 QualType T = PI->getType();
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002992 if (const PointerType* PT = T->getAs<PointerType>()) {
2993 QualType PointeeTy = PT->getPointeeType();
2994 convertToUnqualifiedObjCType(PointeeTy);
2995 T = Context->getPointerType(PointeeTy);
2996 }
2997 ArgTypes.push_back(T);
2998 }
2999
3000 QualType returnType = Exp->getType();
3001 // Get the type, we will need to reference it in a couple spots.
3002 QualType msgSendType = MsgSendFlavor->getType();
3003
3004 // Create a reference to the objc_msgSend() declaration.
3005 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3006 VK_LValue, SourceLocation());
3007
3008 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3009 Context->getPointerType(Context->VoidTy),
3010 CK_BitCast, DRE);
3011
3012 // Now do the "normal" pointer to function cast.
3013 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003014 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003015 castType = Context->getPointerType(castType);
3016 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3017 cast);
3018
3019 // Don't forget the parens to enforce the proper binding.
3020 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3021
3022 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07003023 CallExpr *CE = new (Context)
3024 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003025 ReplaceStmt(Exp, CE);
3026 return CE;
3027}
3028
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003029// struct __rw_objc_super {
3030// struct objc_object *object; struct objc_object *superClass;
3031// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003032QualType RewriteModernObjC::getSuperStructType() {
3033 if (!SuperStructDecl) {
3034 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3035 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003036 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003037 QualType FieldTypes[2];
3038
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003039 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003040 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003041 // struct objc_object *superClass;
3042 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003043
3044 // Create fields
3045 for (unsigned i = 0; i < 2; ++i) {
3046 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3047 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003048 SourceLocation(), nullptr,
3049 FieldTypes[i], nullptr,
3050 /*BitWidth=*/nullptr,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003051 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003052 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003053 }
3054
3055 SuperStructDecl->completeDefinition();
3056 }
3057 return Context->getTagDeclType(SuperStructDecl);
3058}
3059
3060QualType RewriteModernObjC::getConstantStringStructType() {
3061 if (!ConstantStringDecl) {
3062 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3063 SourceLocation(), SourceLocation(),
3064 &Context->Idents.get("__NSConstantStringImpl"));
3065 QualType FieldTypes[4];
3066
3067 // struct objc_object *receiver;
3068 FieldTypes[0] = Context->getObjCIdType();
3069 // int flags;
3070 FieldTypes[1] = Context->IntTy;
3071 // char *str;
3072 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3073 // long length;
3074 FieldTypes[3] = Context->LongTy;
3075
3076 // Create fields
3077 for (unsigned i = 0; i < 4; ++i) {
3078 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3079 ConstantStringDecl,
3080 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003081 SourceLocation(), nullptr,
3082 FieldTypes[i], nullptr,
3083 /*BitWidth=*/nullptr,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003084 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003085 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003086 }
3087
3088 ConstantStringDecl->completeDefinition();
3089 }
3090 return Context->getTagDeclType(ConstantStringDecl);
3091}
3092
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003093/// getFunctionSourceLocation - returns start location of a function
3094/// definition. Complication arises when function has declared as
3095/// extern "C" or extern "C" {...}
3096static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3097 FunctionDecl *FD) {
3098 if (FD->isExternC() && !FD->isMain()) {
3099 const DeclContext *DC = FD->getDeclContext();
3100 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3101 // if it is extern "C" {...}, return function decl's own location.
3102 if (!LSD->getRBraceLoc().isValid())
3103 return LSD->getExternLoc();
3104 }
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003105 if (FD->getStorageClass() != SC_None)
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003106 R.RewriteBlockLiteralFunctionDecl(FD);
3107 return FD->getTypeSpecStartLoc();
3108}
3109
Fariborz Jahanian96205962012-11-06 17:30:23 +00003110void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3111
3112 SourceLocation Location = D->getLocation();
3113
Fariborz Jahanianada71912013-02-08 00:27:34 +00003114 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003115 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003116 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3117 LineString += utostr(PLoc.getLine());
3118 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003119 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003120 if (isa<ObjCMethodDecl>(D))
3121 LineString += "\"";
3122 else LineString += "\"\n";
3123
3124 Location = D->getLocStart();
3125 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3126 if (FD->isExternC() && !FD->isMain()) {
3127 const DeclContext *DC = FD->getDeclContext();
3128 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3129 // if it is extern "C" {...}, return function decl's own location.
3130 if (!LSD->getRBraceLoc().isValid())
3131 Location = LSD->getExternLoc();
3132 }
3133 }
3134 InsertText(Location, LineString);
3135 }
3136}
3137
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003138/// SynthMsgSendStretCallExpr - This routine translates message expression
3139/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3140/// nil check on receiver must be performed before calling objc_msgSend_stret.
3141/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3142/// msgSendType - function type of objc_msgSend_stret(...)
3143/// returnType - Result type of the method being synthesized.
3144/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3145/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3146/// starting with receiver.
3147/// Method - Method being rewritten.
3148Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003149 QualType returnType,
3150 SmallVectorImpl<QualType> &ArgTypes,
3151 SmallVectorImpl<Expr*> &MsgExprs,
3152 ObjCMethodDecl *Method) {
3153 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003154 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3155 Method ? Method->isVariadic()
3156 : false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003157 castType = Context->getPointerType(castType);
3158
3159 // build type for containing the objc_msgSend_stret object.
3160 static unsigned stretCount=0;
3161 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003162 std::string str =
3163 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003164 str += "namespace {\n";
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003165 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003166 str += " {\n\t";
3167 str += name;
3168 str += "(id receiver, SEL sel";
3169 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003170 std::string ArgName = "arg"; ArgName += utostr(i);
3171 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3172 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003173 }
3174 // could be vararg.
3175 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003176 std::string ArgName = "arg"; ArgName += utostr(i);
3177 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3178 Context->getPrintingPolicy());
3179 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003180 }
3181
3182 str += ") {\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003183 str += "\t unsigned size = sizeof(";
3184 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3185
3186 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3187
3188 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3189 str += ")(void *)objc_msgSend)(receiver, sel";
3190 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3191 str += ", arg"; str += utostr(i);
3192 }
3193 // could be vararg.
3194 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3195 str += ", arg"; str += utostr(i);
3196 }
3197 str+= ");\n";
3198
3199 str += "\t else if (receiver == 0)\n";
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003200 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3201 str += "\t else\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003202
3203
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003204 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3205 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3206 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3207 str += ", arg"; str += utostr(i);
3208 }
3209 // could be vararg.
3210 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3211 str += ", arg"; str += utostr(i);
3212 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003213 str += ");\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003214
3215
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003216 str += "\t}\n";
3217 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3218 str += " s;\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003219 str += "};\n};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003220 SourceLocation FunLocStart;
3221 if (CurFunctionDef)
3222 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3223 else {
3224 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3225 FunLocStart = CurMethodDef->getLocStart();
3226 }
3227
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003228 InsertText(FunLocStart, str);
3229 ++stretCount;
3230
3231 // AST for __Stretn(receiver, args).s;
3232 IdentifierInfo *ID = &Context->Idents.get(name);
3233 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003234 SourceLocation(), ID, castType,
3235 nullptr, SC_Extern, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003236 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3237 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003238 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003239 castType, VK_LValue, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003240
3241 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003242 SourceLocation(),
3243 &Context->Idents.get("s"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003244 returnType, nullptr,
3245 /*BitWidth=*/nullptr,
3246 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003247 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3248 FieldD->getType(), VK_LValue,
3249 OK_Ordinary);
3250
3251 return ME;
3252}
3253
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003254Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3255 SourceLocation StartLoc,
3256 SourceLocation EndLoc) {
3257 if (!SelGetUidFunctionDecl)
3258 SynthSelGetUidFunctionDecl();
3259 if (!MsgSendFunctionDecl)
3260 SynthMsgSendFunctionDecl();
3261 if (!MsgSendSuperFunctionDecl)
3262 SynthMsgSendSuperFunctionDecl();
3263 if (!MsgSendStretFunctionDecl)
3264 SynthMsgSendStretFunctionDecl();
3265 if (!MsgSendSuperStretFunctionDecl)
3266 SynthMsgSendSuperStretFunctionDecl();
3267 if (!MsgSendFpretFunctionDecl)
3268 SynthMsgSendFpretFunctionDecl();
3269 if (!GetClassFunctionDecl)
3270 SynthGetClassFunctionDecl();
3271 if (!GetSuperClassFunctionDecl)
3272 SynthGetSuperClassFunctionDecl();
3273 if (!GetMetaClassFunctionDecl)
3274 SynthGetMetaClassFunctionDecl();
3275
3276 // default to objc_msgSend().
3277 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3278 // May need to use objc_msgSend_stret() as well.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003279 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003280 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003281 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003282 if (resultType->isRecordType())
3283 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3284 else if (resultType->isRealFloatingType())
3285 MsgSendFlavor = MsgSendFpretFunctionDecl;
3286 }
3287
3288 // Synthesize a call to objc_msgSend().
3289 SmallVector<Expr*, 8> MsgExprs;
3290 switch (Exp->getReceiverKind()) {
3291 case ObjCMessageExpr::SuperClass: {
3292 MsgSendFlavor = MsgSendSuperFunctionDecl;
3293 if (MsgSendStretFlavor)
3294 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3295 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3296
3297 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3298
3299 SmallVector<Expr*, 4> InitExprs;
3300
3301 // set the receiver to self, the first argument to all methods.
3302 InitExprs.push_back(
3303 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3304 CK_BitCast,
3305 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003306 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003307 Context->getObjCIdType(),
3308 VK_RValue,
3309 SourceLocation()))
3310 ); // set the 'receiver'.
3311
3312 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3313 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07003314 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003315 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003316 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3317 &ClsExprs[0],
3318 ClsExprs.size(),
3319 StartLoc,
3320 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003321 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003322 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003323 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3324 &ClsExprs[0], ClsExprs.size(),
3325 StartLoc, EndLoc);
3326
3327 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3328 // To turn off a warning, type-cast to 'id'
3329 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3330 NoTypeInfoCStyleCastExpr(Context,
3331 Context->getObjCIdType(),
3332 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003333 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003334 QualType superType = getSuperStructType();
3335 Expr *SuperRep;
3336
3337 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003338 SynthSuperConstructorFunctionDecl();
3339 // Simulate a constructor call...
3340 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003341 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003342 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003343 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003344 superType, VK_LValue,
3345 SourceLocation());
3346 // The code for super is a little tricky to prevent collision with
3347 // the structure definition in the header. The rewriter has it's own
3348 // internal definition (__rw_objc_super) that is uses. This is why
3349 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003350 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003351 //
3352 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3353 Context->getPointerType(SuperRep->getType()),
3354 VK_RValue, OK_Ordinary,
3355 SourceLocation());
3356 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3357 Context->getPointerType(superType),
3358 CK_BitCast, SuperRep);
3359 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003360 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003361 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003362 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003363 SourceLocation());
3364 TypeSourceInfo *superTInfo
3365 = Context->getTrivialTypeSourceInfo(superType);
3366 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3367 superType, VK_LValue,
3368 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003369 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003370 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3371 Context->getPointerType(SuperRep->getType()),
3372 VK_RValue, OK_Ordinary,
3373 SourceLocation());
3374 }
3375 MsgExprs.push_back(SuperRep);
3376 break;
3377 }
3378
3379 case ObjCMessageExpr::Class: {
3380 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003381 ObjCInterfaceDecl *Class
3382 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3383 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07003384 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003385 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3386 &ClsExprs[0],
3387 ClsExprs.size(),
3388 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003389 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3390 Context->getObjCIdType(),
3391 CK_BitCast, Cls);
3392 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003393 break;
3394 }
3395
3396 case ObjCMessageExpr::SuperInstance:{
3397 MsgSendFlavor = MsgSendSuperFunctionDecl;
3398 if (MsgSendStretFlavor)
3399 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3400 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3401 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3402 SmallVector<Expr*, 4> InitExprs;
3403
3404 InitExprs.push_back(
3405 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3406 CK_BitCast,
3407 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003408 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003409 Context->getObjCIdType(),
3410 VK_RValue, SourceLocation()))
3411 ); // set the 'receiver'.
3412
3413 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3414 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07003415 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003416 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003417 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3418 &ClsExprs[0],
3419 ClsExprs.size(),
3420 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003421 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003422 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003423 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3424 &ClsExprs[0], ClsExprs.size(),
3425 StartLoc, EndLoc);
3426
3427 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3428 // To turn off a warning, type-cast to 'id'
3429 InitExprs.push_back(
3430 // set 'super class', using class_getSuperclass().
3431 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3432 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003433 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003434 QualType superType = getSuperStructType();
3435 Expr *SuperRep;
3436
3437 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003438 SynthSuperConstructorFunctionDecl();
3439 // Simulate a constructor call...
3440 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003441 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003442 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003443 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003444 superType, VK_LValue, SourceLocation());
3445 // The code for super is a little tricky to prevent collision with
3446 // the structure definition in the header. The rewriter has it's own
3447 // internal definition (__rw_objc_super) that is uses. This is why
3448 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003449 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003450 //
3451 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3452 Context->getPointerType(SuperRep->getType()),
3453 VK_RValue, OK_Ordinary,
3454 SourceLocation());
3455 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3456 Context->getPointerType(superType),
3457 CK_BitCast, SuperRep);
3458 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003459 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003460 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003461 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003462 SourceLocation());
3463 TypeSourceInfo *superTInfo
3464 = Context->getTrivialTypeSourceInfo(superType);
3465 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3466 superType, VK_RValue, ILE,
3467 false);
3468 }
3469 MsgExprs.push_back(SuperRep);
3470 break;
3471 }
3472
3473 case ObjCMessageExpr::Instance: {
3474 // Remove all type-casts because it may contain objc-style types; e.g.
3475 // Foo<Proto> *.
3476 Expr *recExpr = Exp->getInstanceReceiver();
3477 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3478 recExpr = CE->getSubExpr();
3479 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3480 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3481 ? CK_BlockPointerToObjCPointerCast
3482 : CK_CPointerToObjCPointerCast;
3483
3484 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3485 CK, recExpr);
3486 MsgExprs.push_back(recExpr);
3487 break;
3488 }
3489 }
3490
3491 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3492 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07003493 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003494 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3495 &SelExprs[0], SelExprs.size(),
3496 StartLoc,
3497 EndLoc);
3498 MsgExprs.push_back(SelExp);
3499
3500 // Now push any user supplied arguments.
3501 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3502 Expr *userExpr = Exp->getArg(i);
3503 // Make all implicit casts explicit...ICE comes in handy:-)
3504 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3505 // Reuse the ICE type, it is exactly what the doctor ordered.
3506 QualType type = ICE->getType();
3507 if (needToScanForQualifiers(type))
3508 type = Context->getObjCIdType();
3509 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3510 (void)convertBlockPointerToFunctionPointer(type);
3511 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3512 CastKind CK;
3513 if (SubExpr->getType()->isIntegralType(*Context) &&
3514 type->isBooleanType()) {
3515 CK = CK_IntegralToBoolean;
3516 } else if (type->isObjCObjectPointerType()) {
3517 if (SubExpr->getType()->isBlockPointerType()) {
3518 CK = CK_BlockPointerToObjCPointerCast;
3519 } else if (SubExpr->getType()->isPointerType()) {
3520 CK = CK_CPointerToObjCPointerCast;
3521 } else {
3522 CK = CK_BitCast;
3523 }
3524 } else {
3525 CK = CK_BitCast;
3526 }
3527
3528 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3529 }
3530 // Make id<P...> cast into an 'id' cast.
3531 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3532 if (CE->getType()->isObjCQualifiedIdType()) {
3533 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3534 userExpr = CE->getSubExpr();
3535 CastKind CK;
3536 if (userExpr->getType()->isIntegralType(*Context)) {
3537 CK = CK_IntegralToPointer;
3538 } else if (userExpr->getType()->isBlockPointerType()) {
3539 CK = CK_BlockPointerToObjCPointerCast;
3540 } else if (userExpr->getType()->isPointerType()) {
3541 CK = CK_CPointerToObjCPointerCast;
3542 } else {
3543 CK = CK_BitCast;
3544 }
3545 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3546 CK, userExpr);
3547 }
3548 }
3549 MsgExprs.push_back(userExpr);
3550 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3551 // out the argument in the original expression (since we aren't deleting
3552 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3553 //Exp->setArg(i, 0);
3554 }
3555 // Generate the funky cast.
3556 CastExpr *cast;
3557 SmallVector<QualType, 8> ArgTypes;
3558 QualType returnType;
3559
3560 // Push 'id' and 'SEL', the 2 implicit arguments.
3561 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3562 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3563 else
3564 ArgTypes.push_back(Context->getObjCIdType());
3565 ArgTypes.push_back(Context->getObjCSelType());
3566 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3567 // Push any user argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -07003568 for (const auto *PI : OMD->params()) {
3569 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003570 ? Context->getObjCIdType()
Stephen Hines651f13c2014-04-23 16:59:28 -07003571 : PI->getType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003572 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3573 (void)convertBlockPointerToFunctionPointer(t);
3574 ArgTypes.push_back(t);
3575 }
3576 returnType = Exp->getType();
3577 convertToUnqualifiedObjCType(returnType);
3578 (void)convertBlockPointerToFunctionPointer(returnType);
3579 } else {
3580 returnType = Context->getObjCIdType();
3581 }
3582 // Get the type, we will need to reference it in a couple spots.
3583 QualType msgSendType = MsgSendFlavor->getType();
3584
3585 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003586 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003587 VK_LValue, SourceLocation());
3588
3589 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3590 // If we don't do this cast, we get the following bizarre warning/note:
3591 // xx.m:13: warning: function called through a non-compatible type
3592 // xx.m:13: note: if this code is reached, the program will abort
3593 cast = NoTypeInfoCStyleCastExpr(Context,
3594 Context->getPointerType(Context->VoidTy),
3595 CK_BitCast, DRE);
3596
3597 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003598 // If we don't have a method decl, force a variadic cast.
3599 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003600 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003601 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003602 castType = Context->getPointerType(castType);
3603 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3604 cast);
3605
3606 // Don't forget the parens to enforce the proper binding.
3607 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3608
3609 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07003610 CallExpr *CE = new (Context)
3611 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003612 Stmt *ReplacingStmt = CE;
3613 if (MsgSendStretFlavor) {
3614 // We have the method which returns a struct/union. Must also generate
3615 // call to objc_msgSend_stret and hang both varieties on a conditional
3616 // expression which dictate which one to envoke depending on size of
3617 // method's return type.
3618
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003619 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3620 returnType,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003621 ArgTypes, MsgExprs,
3622 Exp->getMethodDecl());
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003623 ReplacingStmt = STCE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003624 }
3625 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3626 return ReplacingStmt;
3627}
3628
3629Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3630 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3631 Exp->getLocEnd());
3632
3633 // Now do the actual rewrite.
3634 ReplaceStmt(Exp, ReplacingStmt);
3635
3636 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3637 return ReplacingStmt;
3638}
3639
3640// typedef struct objc_object Protocol;
3641QualType RewriteModernObjC::getProtocolType() {
3642 if (!ProtocolTypeDecl) {
3643 TypeSourceInfo *TInfo
3644 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3645 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3646 SourceLocation(), SourceLocation(),
3647 &Context->Idents.get("Protocol"),
3648 TInfo);
3649 }
3650 return Context->getTypeDeclType(ProtocolTypeDecl);
3651}
3652
3653/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3654/// a synthesized/forward data reference (to the protocol's metadata).
3655/// The forward references (and metadata) are generated in
3656/// RewriteModernObjC::HandleTranslationUnit().
3657Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003658 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3659 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003660 IdentifierInfo *ID = &Context->Idents.get(Name);
3661 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003662 SourceLocation(), ID, getProtocolType(),
3663 nullptr, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003664 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3665 VK_LValue, SourceLocation());
Stephen Hines651f13c2014-04-23 16:59:28 -07003666 CastExpr *castExpr =
3667 NoTypeInfoCStyleCastExpr(
3668 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003669 ReplaceStmt(Exp, castExpr);
3670 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3671 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3672 return castExpr;
3673
3674}
3675
3676bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3677 const char *endBuf) {
3678 while (startBuf < endBuf) {
3679 if (*startBuf == '#') {
3680 // Skip whitespace.
3681 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3682 ;
3683 if (!strncmp(startBuf, "if", strlen("if")) ||
3684 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3685 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3686 !strncmp(startBuf, "define", strlen("define")) ||
3687 !strncmp(startBuf, "undef", strlen("undef")) ||
3688 !strncmp(startBuf, "else", strlen("else")) ||
3689 !strncmp(startBuf, "elif", strlen("elif")) ||
3690 !strncmp(startBuf, "endif", strlen("endif")) ||
3691 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3692 !strncmp(startBuf, "include", strlen("include")) ||
3693 !strncmp(startBuf, "import", strlen("import")) ||
3694 !strncmp(startBuf, "include_next", strlen("include_next")))
3695 return true;
3696 }
3697 startBuf++;
3698 }
3699 return false;
3700}
3701
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003702/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3703/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003704bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003705 TagDecl *Tag,
3706 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003707 if (!IDecl)
3708 return false;
3709 SourceLocation TagLocation;
3710 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3711 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003712 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003713 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003714 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003715 TagLocation = RD->getLocation();
3716 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003717 IDecl->getLocation(), TagLocation);
3718 }
3719 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3720 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3721 return false;
3722 IsNamedDefinition = true;
3723 TagLocation = ED->getLocation();
3724 return Context->getSourceManager().isBeforeInTranslationUnit(
3725 IDecl->getLocation(), TagLocation);
3726
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003727 }
3728 return false;
3729}
3730
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003731/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003732/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003733bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3734 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003735 if (isa<TypedefType>(Type)) {
3736 Result += "\t";
3737 return false;
3738 }
3739
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003740 if (Type->isArrayType()) {
3741 QualType ElemTy = Context->getBaseElementType(Type);
3742 return RewriteObjCFieldDeclType(ElemTy, Result);
3743 }
3744 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003745 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3746 if (RD->isCompleteDefinition()) {
3747 if (RD->isStruct())
3748 Result += "\n\tstruct ";
3749 else if (RD->isUnion())
3750 Result += "\n\tunion ";
3751 else
3752 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003753
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003754 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003755 if (GlobalDefinedTags.count(RD)) {
3756 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003757 Result += " ";
3758 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003759 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003760 Result += " {\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07003761 for (auto *FD : RD->fields())
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003762 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003763 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003764 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003765 }
3766 }
3767 else if (Type->isEnumeralType()) {
3768 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3769 if (ED->isCompleteDefinition()) {
3770 Result += "\n\tenum ";
3771 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003772 if (GlobalDefinedTags.count(ED)) {
3773 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003774 Result += " ";
3775 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003776 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003777
3778 Result += " {\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07003779 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003780 Result += "\t"; Result += EC->getName(); Result += " = ";
3781 llvm::APSInt Val = EC->getInitVal();
3782 Result += Val.toString(10);
3783 Result += ",\n";
3784 }
3785 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003786 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003787 }
3788 }
3789
3790 Result += "\t";
3791 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003792 return false;
3793}
3794
3795
3796/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3797/// It handles elaborated types, as well as enum types in the process.
3798void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3799 std::string &Result) {
3800 QualType Type = fieldDecl->getType();
3801 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003802
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003803 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3804 if (!EleboratedType)
3805 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003806 Result += Name;
3807 if (fieldDecl->isBitField()) {
3808 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3809 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003810 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003811 const ArrayType *AT = Context->getAsArrayType(Type);
3812 do {
3813 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003814 Result += "[";
3815 llvm::APInt Dim = CAT->getSize();
3816 Result += utostr(Dim.getZExtValue());
3817 Result += "]";
3818 }
Eli Friedman6febf122012-12-13 01:43:21 +00003819 AT = Context->getAsArrayType(AT->getElementType());
3820 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003821 }
3822
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003823 Result += ";\n";
3824}
3825
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003826/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3827/// named aggregate types into the input buffer.
3828void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3829 std::string &Result) {
3830 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003831 if (isa<TypedefType>(Type))
3832 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003833 if (Type->isArrayType())
3834 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003835 ObjCContainerDecl *IDecl =
3836 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003837
3838 TagDecl *TD = nullptr;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003839 if (Type->isRecordType()) {
3840 TD = Type->getAs<RecordType>()->getDecl();
3841 }
3842 else if (Type->isEnumeralType()) {
3843 TD = Type->getAs<EnumType>()->getDecl();
3844 }
3845
3846 if (TD) {
3847 if (GlobalDefinedTags.count(TD))
3848 return;
3849
3850 bool IsNamedDefinition = false;
3851 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3852 RewriteObjCFieldDeclType(Type, Result);
3853 Result += ";";
3854 }
3855 if (IsNamedDefinition)
3856 GlobalDefinedTags.insert(TD);
3857 }
3858
3859}
3860
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003861unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3862 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3863 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3864 return IvarGroupNumber[IV];
3865 }
3866 unsigned GroupNo = 0;
3867 SmallVector<const ObjCIvarDecl *, 8> IVars;
3868 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3869 IVD; IVD = IVD->getNextIvar())
3870 IVars.push_back(IVD);
3871
3872 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3873 if (IVars[i]->isBitField()) {
3874 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3875 while (i < e && IVars[i]->isBitField())
3876 IvarGroupNumber[IVars[i++]] = GroupNo;
3877 if (i < e)
3878 --i;
3879 }
3880
3881 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3882 return IvarGroupNumber[IV];
3883}
3884
3885QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3886 ObjCIvarDecl *IV,
3887 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3888 std::string StructTagName;
3889 ObjCIvarBitfieldGroupType(IV, StructTagName);
3890 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3891 Context->getTranslationUnitDecl(),
3892 SourceLocation(), SourceLocation(),
3893 &Context->Idents.get(StructTagName));
3894 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3895 ObjCIvarDecl *Ivar = IVars[i];
3896 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3897 &Context->Idents.get(Ivar->getName()),
3898 Ivar->getType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003899 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3900 false, ICIS_NoInit));
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003901 }
3902 RD->completeDefinition();
3903 return Context->getTagDeclType(RD);
3904}
3905
3906QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3907 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3908 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3909 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3910 if (GroupRecordType.count(tuple))
3911 return GroupRecordType[tuple];
3912
3913 SmallVector<ObjCIvarDecl *, 8> IVars;
3914 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3915 IVD; IVD = IVD->getNextIvar()) {
3916 if (IVD->isBitField())
3917 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3918 else {
3919 if (!IVars.empty()) {
3920 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3921 // Generate the struct type for this group of bitfield ivars.
3922 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3923 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3924 IVars.clear();
3925 }
3926 }
3927 }
3928 if (!IVars.empty()) {
3929 // Do the last one.
3930 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3931 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3932 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3933 }
3934 QualType RetQT = GroupRecordType[tuple];
3935 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3936
3937 return RetQT;
3938}
3939
3940/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3941/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3942void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3943 std::string &Result) {
3944 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3945 Result += CDecl->getName();
3946 Result += "__GRBF_";
3947 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3948 Result += utostr(GroupNo);
3949 return;
3950}
3951
3952/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3953/// Name of the struct would be: classname__T_n where n is the group number for
3954/// this ivar.
3955void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3956 std::string &Result) {
3957 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3958 Result += CDecl->getName();
3959 Result += "__T_";
3960 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3961 Result += utostr(GroupNo);
3962 return;
3963}
3964
3965/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3966/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3967/// this ivar.
3968void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3969 std::string &Result) {
3970 Result += "OBJC_IVAR_$_";
3971 ObjCIvarBitfieldGroupDecl(IV, Result);
3972}
3973
3974#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3975 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3976 ++IX; \
3977 if (IX < ENDIX) \
3978 --IX; \
3979}
3980
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003981/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3982/// an objective-c class with ivars.
3983void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3984 std::string &Result) {
3985 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3986 assert(CDecl->getName() != "" &&
3987 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003988 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003989 SmallVector<ObjCIvarDecl *, 8> IVars;
3990 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003991 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003992 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003993
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003994 SourceLocation LocStart = CDecl->getLocStart();
3995 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003997 const char *startBuf = SM->getCharacterData(LocStart);
3998 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004000 // If no ivars and no root or if its root, directly or indirectly,
4001 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004002 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004003 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4004 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4005 ReplaceText(LocStart, endBuf-startBuf, Result);
4006 return;
4007 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004008
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004009 // Insert named struct/union definitions inside class to
4010 // outer scope. This follows semantics of locally defined
4011 // struct/unions in objective-c classes.
4012 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4013 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004014
4015 // Insert named structs which are syntheized to group ivar bitfields
4016 // to outer scope as well.
4017 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4018 if (IVars[i]->isBitField()) {
4019 ObjCIvarDecl *IV = IVars[i];
4020 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4021 RewriteObjCFieldDeclType(QT, Result);
4022 Result += ";";
4023 // skip over ivar bitfields in this group.
4024 SKIP_BITFIELDS(i , e, IVars);
4025 }
4026
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004027 Result += "\nstruct ";
4028 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004029 Result += "_IMPL {\n";
4030
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004031 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004032 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4033 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4034 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004035 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004036
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004037 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4038 if (IVars[i]->isBitField()) {
4039 ObjCIvarDecl *IV = IVars[i];
4040 Result += "\tstruct ";
4041 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4042 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4043 // skip over ivar bitfields in this group.
4044 SKIP_BITFIELDS(i , e, IVars);
4045 }
4046 else
4047 RewriteObjCFieldDecl(IVars[i], Result);
4048 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004049
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004050 Result += "};\n";
4051 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4052 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004053 // Mark this struct as having been generated.
4054 if (!ObjCSynthesizedStructs.insert(CDecl))
4055 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004056}
4057
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004058/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4059/// have been referenced in an ivar access expression.
4060void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4061 std::string &Result) {
4062 // write out ivar offset symbols which have been referenced in an ivar
4063 // access expression.
4064 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4065 if (Ivars.empty())
4066 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004067
4068 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004069 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4070 e = Ivars.end(); i != e; i++) {
4071 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004072 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4073 unsigned GroupNo = 0;
4074 if (IvarDecl->isBitField()) {
4075 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4076 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4077 continue;
4078 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004079 Result += "\n";
4080 if (LangOpts.MicrosoftExt)
4081 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004082 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004083 if (LangOpts.MicrosoftExt &&
4084 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004085 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4086 Result += "__declspec(dllimport) ";
4087
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004088 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004089 if (IvarDecl->isBitField()) {
4090 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4091 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4092 }
4093 else
4094 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004095 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004096 }
4097}
4098
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004099//===----------------------------------------------------------------------===//
4100// Meta Data Emission
4101//===----------------------------------------------------------------------===//
4102
4103
4104/// RewriteImplementations - This routine rewrites all method implementations
4105/// and emits meta-data.
4106
4107void RewriteModernObjC::RewriteImplementations() {
4108 int ClsDefCount = ClassImplementation.size();
4109 int CatDefCount = CategoryImplementation.size();
4110
4111 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004112 for (int i = 0; i < ClsDefCount; i++) {
4113 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4114 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4115 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004116 assert(false &&
4117 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004118 RewriteImplementationDecl(OIMP);
4119 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004120
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004121 for (int i = 0; i < CatDefCount; i++) {
4122 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4123 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4124 if (CDecl->isImplicitInterfaceDecl())
4125 assert(false &&
4126 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004127 RewriteImplementationDecl(CIMP);
4128 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004129}
4130
4131void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4132 const std::string &Name,
4133 ValueDecl *VD, bool def) {
4134 assert(BlockByRefDeclNo.count(VD) &&
4135 "RewriteByRefString: ByRef decl missing");
4136 if (def)
4137 ResultStr += "struct ";
4138 ResultStr += "__Block_byref_" + Name +
4139 "_" + utostr(BlockByRefDeclNo[VD]) ;
4140}
4141
4142static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4143 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4144 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4145 return false;
4146}
4147
4148std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4149 StringRef funcName,
4150 std::string Tag) {
4151 const FunctionType *AFT = CE->getFunctionType();
Stephen Hines651f13c2014-04-23 16:59:28 -07004152 QualType RT = AFT->getReturnType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004153 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004154 SourceLocation BlockLoc = CE->getExprLoc();
4155 std::string S;
4156 ConvertSourceLocationToLineDirective(BlockLoc, S);
4157
4158 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4159 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004160
4161 BlockDecl *BD = CE->getBlockDecl();
4162
4163 if (isa<FunctionNoProtoType>(AFT)) {
4164 // No user-supplied arguments. Still need to pass in a pointer to the
4165 // block (to reference imported block decl refs).
4166 S += "(" + StructRef + " *__cself)";
4167 } else if (BD->param_empty()) {
4168 S += "(" + StructRef + " *__cself)";
4169 } else {
4170 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4171 assert(FT && "SynthesizeBlockFunc: No function proto");
4172 S += '(';
4173 // first add the implicit argument.
4174 S += StructRef + " *__cself, ";
4175 std::string ParamStr;
4176 for (BlockDecl::param_iterator AI = BD->param_begin(),
4177 E = BD->param_end(); AI != E; ++AI) {
4178 if (AI != BD->param_begin()) S += ", ";
4179 ParamStr = (*AI)->getNameAsString();
4180 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004181 (void)convertBlockPointerToFunctionPointer(QT);
4182 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004183 S += ParamStr;
4184 }
4185 if (FT->isVariadic()) {
4186 if (!BD->param_empty()) S += ", ";
4187 S += "...";
4188 }
4189 S += ')';
4190 }
4191 S += " {\n";
4192
4193 // Create local declarations to avoid rewriting all closure decl ref exprs.
4194 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00004195 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004196 E = BlockByRefDecls.end(); I != E; ++I) {
4197 S += " ";
4198 std::string Name = (*I)->getNameAsString();
4199 std::string TypeString;
4200 RewriteByRefString(TypeString, Name, (*I));
4201 TypeString += " *";
4202 Name = TypeString + Name;
4203 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4204 }
4205 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004206 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004207 E = BlockByCopyDecls.end(); I != E; ++I) {
4208 S += " ";
4209 // Handle nested closure invocation. For example:
4210 //
4211 // void (^myImportedClosure)(void);
4212 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4213 //
4214 // void (^anotherClosure)(void);
4215 // anotherClosure = ^(void) {
4216 // myImportedClosure(); // import and invoke the closure
4217 // };
4218 //
4219 if (isTopLevelBlockPointerType((*I)->getType())) {
4220 RewriteBlockPointerTypeVariable(S, (*I));
4221 S += " = (";
4222 RewriteBlockPointerType(S, (*I)->getType());
4223 S += ")";
4224 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4225 }
4226 else {
4227 std::string Name = (*I)->getNameAsString();
4228 QualType QT = (*I)->getType();
4229 if (HasLocalVariableExternalStorage(*I))
4230 QT = Context->getPointerType(QT);
4231 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4232 S += Name + " = __cself->" +
4233 (*I)->getNameAsString() + "; // bound by copy\n";
4234 }
4235 }
4236 std::string RewrittenStr = RewrittenBlockExprs[CE];
4237 const char *cstr = RewrittenStr.c_str();
4238 while (*cstr++ != '{') ;
4239 S += cstr;
4240 S += "\n";
4241 return S;
4242}
4243
4244std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4245 StringRef funcName,
4246 std::string Tag) {
4247 std::string StructRef = "struct " + Tag;
4248 std::string S = "static void __";
4249
4250 S += funcName;
4251 S += "_block_copy_" + utostr(i);
4252 S += "(" + StructRef;
4253 S += "*dst, " + StructRef;
4254 S += "*src) {";
4255 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4256 E = ImportedBlockDecls.end(); I != E; ++I) {
4257 ValueDecl *VD = (*I);
4258 S += "_Block_object_assign((void*)&dst->";
4259 S += (*I)->getNameAsString();
4260 S += ", (void*)src->";
4261 S += (*I)->getNameAsString();
4262 if (BlockByRefDeclsPtrSet.count((*I)))
4263 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4264 else if (VD->getType()->isBlockPointerType())
4265 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4266 else
4267 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4268 }
4269 S += "}\n";
4270
4271 S += "\nstatic void __";
4272 S += funcName;
4273 S += "_block_dispose_" + utostr(i);
4274 S += "(" + StructRef;
4275 S += "*src) {";
4276 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4277 E = ImportedBlockDecls.end(); I != E; ++I) {
4278 ValueDecl *VD = (*I);
4279 S += "_Block_object_dispose((void*)src->";
4280 S += (*I)->getNameAsString();
4281 if (BlockByRefDeclsPtrSet.count((*I)))
4282 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4283 else if (VD->getType()->isBlockPointerType())
4284 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4285 else
4286 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4287 }
4288 S += "}\n";
4289 return S;
4290}
4291
4292std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4293 std::string Desc) {
4294 std::string S = "\nstruct " + Tag;
4295 std::string Constructor = " " + Tag;
4296
4297 S += " {\n struct __block_impl impl;\n";
4298 S += " struct " + Desc;
4299 S += "* Desc;\n";
4300
4301 Constructor += "(void *fp, "; // Invoke function pointer.
4302 Constructor += "struct " + Desc; // Descriptor pointer.
4303 Constructor += " *desc";
4304
4305 if (BlockDeclRefs.size()) {
4306 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004307 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004308 E = BlockByCopyDecls.end(); I != E; ++I) {
4309 S += " ";
4310 std::string FieldName = (*I)->getNameAsString();
4311 std::string ArgName = "_" + FieldName;
4312 // Handle nested closure invocation. For example:
4313 //
4314 // void (^myImportedBlock)(void);
4315 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4316 //
4317 // void (^anotherBlock)(void);
4318 // anotherBlock = ^(void) {
4319 // myImportedBlock(); // import and invoke the closure
4320 // };
4321 //
4322 if (isTopLevelBlockPointerType((*I)->getType())) {
4323 S += "struct __block_impl *";
4324 Constructor += ", void *" + ArgName;
4325 } else {
4326 QualType QT = (*I)->getType();
4327 if (HasLocalVariableExternalStorage(*I))
4328 QT = Context->getPointerType(QT);
4329 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4330 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4331 Constructor += ", " + ArgName;
4332 }
4333 S += FieldName + ";\n";
4334 }
4335 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004336 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004337 E = BlockByRefDecls.end(); I != E; ++I) {
4338 S += " ";
4339 std::string FieldName = (*I)->getNameAsString();
4340 std::string ArgName = "_" + FieldName;
4341 {
4342 std::string TypeString;
4343 RewriteByRefString(TypeString, FieldName, (*I));
4344 TypeString += " *";
4345 FieldName = TypeString + FieldName;
4346 ArgName = TypeString + ArgName;
4347 Constructor += ", " + ArgName;
4348 }
4349 S += FieldName + "; // by ref\n";
4350 }
4351 // Finish writing the constructor.
4352 Constructor += ", int flags=0)";
4353 // Initialize all "by copy" arguments.
4354 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00004355 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004356 E = BlockByCopyDecls.end(); I != E; ++I) {
4357 std::string Name = (*I)->getNameAsString();
4358 if (firsTime) {
4359 Constructor += " : ";
4360 firsTime = false;
4361 }
4362 else
4363 Constructor += ", ";
4364 if (isTopLevelBlockPointerType((*I)->getType()))
4365 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4366 else
4367 Constructor += Name + "(_" + Name + ")";
4368 }
4369 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00004370 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004371 E = BlockByRefDecls.end(); I != E; ++I) {
4372 std::string Name = (*I)->getNameAsString();
4373 if (firsTime) {
4374 Constructor += " : ";
4375 firsTime = false;
4376 }
4377 else
4378 Constructor += ", ";
4379 Constructor += Name + "(_" + Name + "->__forwarding)";
4380 }
4381
4382 Constructor += " {\n";
4383 if (GlobalVarDecl)
4384 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4385 else
4386 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4387 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4388
4389 Constructor += " Desc = desc;\n";
4390 } else {
4391 // Finish writing the constructor.
4392 Constructor += ", int flags=0) {\n";
4393 if (GlobalVarDecl)
4394 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4395 else
4396 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4397 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4398 Constructor += " Desc = desc;\n";
4399 }
4400 Constructor += " ";
4401 Constructor += "}\n";
4402 S += Constructor;
4403 S += "};\n";
4404 return S;
4405}
4406
4407std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4408 std::string ImplTag, int i,
4409 StringRef FunName,
4410 unsigned hasCopy) {
4411 std::string S = "\nstatic struct " + DescTag;
4412
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004413 S += " {\n size_t reserved;\n";
4414 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004415 if (hasCopy) {
4416 S += " void (*copy)(struct ";
4417 S += ImplTag; S += "*, struct ";
4418 S += ImplTag; S += "*);\n";
4419
4420 S += " void (*dispose)(struct ";
4421 S += ImplTag; S += "*);\n";
4422 }
4423 S += "} ";
4424
4425 S += DescTag + "_DATA = { 0, sizeof(struct ";
4426 S += ImplTag + ")";
4427 if (hasCopy) {
4428 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4429 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4430 }
4431 S += "};\n";
4432 return S;
4433}
4434
4435void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4436 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004437 bool RewriteSC = (GlobalVarDecl &&
4438 !Blocks.empty() &&
4439 GlobalVarDecl->getStorageClass() == SC_Static &&
4440 GlobalVarDecl->getType().getCVRQualifiers());
4441 if (RewriteSC) {
4442 std::string SC(" void __");
4443 SC += GlobalVarDecl->getNameAsString();
4444 SC += "() {}";
4445 InsertText(FunLocStart, SC);
4446 }
4447
4448 // Insert closures that were part of the function.
4449 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4450 CollectBlockDeclRefInfo(Blocks[i]);
4451 // Need to copy-in the inner copied-in variables not actually used in this
4452 // block.
4453 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004454 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004455 ValueDecl *VD = Exp->getDecl();
4456 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004457 if (!VD->hasAttr<BlocksAttr>()) {
4458 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4459 BlockByCopyDeclsPtrSet.insert(VD);
4460 BlockByCopyDecls.push_back(VD);
4461 }
4462 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004463 }
John McCallf4b88a42012-03-10 09:33:50 +00004464
4465 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004466 BlockByRefDeclsPtrSet.insert(VD);
4467 BlockByRefDecls.push_back(VD);
4468 }
John McCallf4b88a42012-03-10 09:33:50 +00004469
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004470 // imported objects in the inner blocks not used in the outer
4471 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004472 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004473 VD->getType()->isBlockPointerType())
4474 ImportedBlockDecls.insert(VD);
4475 }
4476
4477 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4478 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4479
4480 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4481
4482 InsertText(FunLocStart, CI);
4483
4484 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4485
4486 InsertText(FunLocStart, CF);
4487
4488 if (ImportedBlockDecls.size()) {
4489 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4490 InsertText(FunLocStart, HF);
4491 }
4492 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4493 ImportedBlockDecls.size() > 0);
4494 InsertText(FunLocStart, BD);
4495
4496 BlockDeclRefs.clear();
4497 BlockByRefDecls.clear();
4498 BlockByRefDeclsPtrSet.clear();
4499 BlockByCopyDecls.clear();
4500 BlockByCopyDeclsPtrSet.clear();
4501 ImportedBlockDecls.clear();
4502 }
4503 if (RewriteSC) {
4504 // Must insert any 'const/volatile/static here. Since it has been
4505 // removed as result of rewriting of block literals.
4506 std::string SC;
4507 if (GlobalVarDecl->getStorageClass() == SC_Static)
4508 SC = "static ";
4509 if (GlobalVarDecl->getType().isConstQualified())
4510 SC += "const ";
4511 if (GlobalVarDecl->getType().isVolatileQualified())
4512 SC += "volatile ";
4513 if (GlobalVarDecl->getType().isRestrictQualified())
4514 SC += "restrict ";
4515 InsertText(FunLocStart, SC);
4516 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004517 if (GlobalConstructionExp) {
4518 // extra fancy dance for global literal expression.
4519
4520 // Always the latest block expression on the block stack.
4521 std::string Tag = "__";
4522 Tag += FunName;
4523 Tag += "_block_impl_";
4524 Tag += utostr(Blocks.size()-1);
4525 std::string globalBuf = "static ";
4526 globalBuf += Tag; globalBuf += " ";
4527 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004528
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004529 llvm::raw_string_ostream constructorExprBuf(SStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004530 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4531 PrintingPolicy(LangOpts));
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004532 globalBuf += constructorExprBuf.str();
4533 globalBuf += ";\n";
4534 InsertText(FunLocStart, globalBuf);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004535 GlobalConstructionExp = nullptr;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004536 }
4537
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004538 Blocks.clear();
4539 InnerDeclRefsCount.clear();
4540 InnerDeclRefs.clear();
4541 RewrittenBlockExprs.clear();
4542}
4543
4544void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004545 SourceLocation FunLocStart =
4546 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4547 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004548 StringRef FuncName = FD->getName();
4549
4550 SynthesizeBlockLiterals(FunLocStart, FuncName);
4551}
4552
4553static void BuildUniqueMethodName(std::string &Name,
4554 ObjCMethodDecl *MD) {
4555 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4556 Name = IFace->getName();
4557 Name += "__" + MD->getSelector().getAsString();
4558 // Convert colons to underscores.
4559 std::string::size_type loc = 0;
4560 while ((loc = Name.find(":", loc)) != std::string::npos)
4561 Name.replace(loc, 1, "_");
4562}
4563
4564void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4565 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4566 //SourceLocation FunLocStart = MD->getLocStart();
4567 SourceLocation FunLocStart = MD->getLocStart();
4568 std::string FuncName;
4569 BuildUniqueMethodName(FuncName, MD);
4570 SynthesizeBlockLiterals(FunLocStart, FuncName);
4571}
4572
4573void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4574 for (Stmt::child_range CI = S->children(); CI; ++CI)
4575 if (*CI) {
4576 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4577 GetBlockDeclRefExprs(CBE->getBody());
4578 else
4579 GetBlockDeclRefExprs(*CI);
4580 }
4581 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004582 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4583 if (DRE->refersToEnclosingLocal()) {
4584 // FIXME: Handle enums.
4585 if (!isa<FunctionDecl>(DRE->getDecl()))
4586 BlockDeclRefs.push_back(DRE);
4587 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4588 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004589 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004590 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004591
4592 return;
4593}
4594
Craig Topper6b9240e2013-07-05 19:34:19 +00004595void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4596 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004597 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4598 for (Stmt::child_range CI = S->children(); CI; ++CI)
4599 if (*CI) {
4600 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4601 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4602 GetInnerBlockDeclRefExprs(CBE->getBody(),
4603 InnerBlockDeclRefs,
4604 InnerContexts);
4605 }
4606 else
4607 GetInnerBlockDeclRefExprs(*CI,
4608 InnerBlockDeclRefs,
4609 InnerContexts);
4610
4611 }
4612 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004613 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4614 if (DRE->refersToEnclosingLocal()) {
4615 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4616 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4617 InnerBlockDeclRefs.push_back(DRE);
4618 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4619 if (Var->isFunctionOrMethodVarDecl())
4620 ImportedLocalExternalDecls.insert(Var);
4621 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004622 }
4623
4624 return;
4625}
4626
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004627/// convertObjCTypeToCStyleType - This routine converts such objc types
4628/// as qualified objects, and blocks to their closest c/c++ types that
4629/// it can. It returns true if input type was modified.
4630bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4631 QualType oldT = T;
4632 convertBlockPointerToFunctionPointer(T);
4633 if (T->isFunctionPointerType()) {
4634 QualType PointeeTy;
4635 if (const PointerType* PT = T->getAs<PointerType>()) {
4636 PointeeTy = PT->getPointeeType();
4637 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4638 T = convertFunctionTypeOfBlocks(FT);
4639 T = Context->getPointerType(T);
4640 }
4641 }
4642 }
4643
4644 convertToUnqualifiedObjCType(T);
4645 return T != oldT;
4646}
4647
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004648/// convertFunctionTypeOfBlocks - This routine converts a function type
4649/// whose result type may be a block pointer or whose argument type(s)
4650/// might be block pointers to an equivalent function type replacing
4651/// all block pointers to function pointers.
4652QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4653 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4654 // FTP will be null for closures that don't take arguments.
4655 // Generate a funky cast.
4656 SmallVector<QualType, 8> ArgTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07004657 QualType Res = FT->getReturnType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004658 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004659
4660 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004661 for (auto &I : FTP->param_types()) {
4662 QualType t = I;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004664 if (convertObjCTypeToCStyleType(t))
4665 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004666 ArgTypes.push_back(t);
4667 }
4668 }
4669 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004670 if (modified)
Jordan Rosebea522f2013-03-08 21:51:21 +00004671 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004672 else FuncType = QualType(FT, 0);
4673 return FuncType;
4674}
4675
4676Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4677 // Navigate to relevant type information.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004678 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004679
4680 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4681 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004682 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4683 CPT = MExpr->getType()->getAs<BlockPointerType>();
4684 }
4685 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4686 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4687 }
4688 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4689 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4690 else if (const ConditionalOperator *CEXPR =
4691 dyn_cast<ConditionalOperator>(BlockExp)) {
4692 Expr *LHSExp = CEXPR->getLHS();
4693 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4694 Expr *RHSExp = CEXPR->getRHS();
4695 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4696 Expr *CONDExp = CEXPR->getCond();
4697 ConditionalOperator *CondExpr =
4698 new (Context) ConditionalOperator(CONDExp,
4699 SourceLocation(), cast<Expr>(LHSStmt),
4700 SourceLocation(), cast<Expr>(RHSStmt),
4701 Exp->getType(), VK_RValue, OK_Ordinary);
4702 return CondExpr;
4703 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4704 CPT = IRE->getType()->getAs<BlockPointerType>();
4705 } else if (const PseudoObjectExpr *POE
4706 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4707 CPT = POE->getType()->castAs<BlockPointerType>();
4708 } else {
4709 assert(1 && "RewriteBlockClass: Bad type");
4710 }
4711 assert(CPT && "RewriteBlockClass: Bad type");
4712 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4713 assert(FT && "RewriteBlockClass: Bad type");
4714 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4715 // FTP will be null for closures that don't take arguments.
4716
4717 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4718 SourceLocation(), SourceLocation(),
4719 &Context->Idents.get("__block_impl"));
4720 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4721
4722 // Generate a funky cast.
4723 SmallVector<QualType, 8> ArgTypes;
4724
4725 // Push the block argument type.
4726 ArgTypes.push_back(PtrBlock);
4727 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004728 for (auto &I : FTP->param_types()) {
4729 QualType t = I;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004730 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4731 if (!convertBlockPointerToFunctionPointer(t))
4732 convertToUnqualifiedObjCType(t);
4733 ArgTypes.push_back(t);
4734 }
4735 }
4736 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00004737 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004738
4739 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4740
4741 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4742 CK_BitCast,
4743 const_cast<Expr*>(BlockExp));
4744 // Don't forget the parens to enforce the proper binding.
4745 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4746 BlkCast);
4747 //PE->dump();
4748
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004749 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004750 SourceLocation(),
4751 &Context->Idents.get("FuncPtr"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004752 Context->VoidPtrTy, nullptr,
4753 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004754 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004755 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4756 FD->getType(), VK_LValue,
4757 OK_Ordinary);
4758
4759
4760 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4761 CK_BitCast, ME);
4762 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4763
4764 SmallVector<Expr*, 8> BlkExprs;
4765 // Add the implicit argument.
4766 BlkExprs.push_back(BlkCast);
4767 // Add the user arguments.
4768 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4769 E = Exp->arg_end(); I != E; ++I) {
4770 BlkExprs.push_back(*I);
4771 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004772 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004773 Exp->getType(), VK_RValue,
4774 SourceLocation());
4775 return CE;
4776}
4777
4778// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004779// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004780// For example:
4781//
4782// int main() {
4783// __block Foo *f;
4784// __block int i;
4785//
4786// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004787// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004788// i = 77;
4789// };
4790//}
John McCallf4b88a42012-03-10 09:33:50 +00004791Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004792 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4793 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004794 ValueDecl *VD = DeclRefExp->getDecl();
4795 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004796
4797 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004798 SourceLocation(),
4799 &Context->Idents.get("__forwarding"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004800 Context->VoidPtrTy, nullptr,
4801 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004802 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004803 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4804 FD, SourceLocation(),
4805 FD->getType(), VK_LValue,
4806 OK_Ordinary);
4807
4808 StringRef Name = VD->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004809 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004810 &Context->Idents.get(Name),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004811 Context->VoidPtrTy, nullptr,
4812 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004813 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004814 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4815 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4816
4817
4818
4819 // Need parens to enforce precedence.
4820 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4821 DeclRefExp->getExprLoc(),
4822 ME);
4823 ReplaceStmt(DeclRefExp, PE);
4824 return PE;
4825}
4826
4827// Rewrites the imported local variable V with external storage
4828// (static, extern, etc.) as *V
4829//
4830Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4831 ValueDecl *VD = DRE->getDecl();
4832 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4833 if (!ImportedLocalExternalDecls.count(Var))
4834 return DRE;
4835 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4836 VK_LValue, OK_Ordinary,
4837 DRE->getLocation());
4838 // Need parens to enforce precedence.
4839 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4840 Exp);
4841 ReplaceStmt(DRE, PE);
4842 return PE;
4843}
4844
4845void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4846 SourceLocation LocStart = CE->getLParenLoc();
4847 SourceLocation LocEnd = CE->getRParenLoc();
4848
4849 // Need to avoid trying to rewrite synthesized casts.
4850 if (LocStart.isInvalid())
4851 return;
4852 // Need to avoid trying to rewrite casts contained in macros.
4853 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4854 return;
4855
4856 const char *startBuf = SM->getCharacterData(LocStart);
4857 const char *endBuf = SM->getCharacterData(LocEnd);
4858 QualType QT = CE->getType();
4859 const Type* TypePtr = QT->getAs<Type>();
4860 if (isa<TypeOfExprType>(TypePtr)) {
4861 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4862 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4863 std::string TypeAsString = "(";
4864 RewriteBlockPointerType(TypeAsString, QT);
4865 TypeAsString += ")";
4866 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4867 return;
4868 }
4869 // advance the location to startArgList.
4870 const char *argPtr = startBuf;
4871
4872 while (*argPtr++ && (argPtr < endBuf)) {
4873 switch (*argPtr) {
4874 case '^':
4875 // Replace the '^' with '*'.
4876 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4877 ReplaceText(LocStart, 1, "*");
4878 break;
4879 }
4880 }
4881 return;
4882}
4883
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004884void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4885 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004886 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4887 CastKind != CK_AnyPointerToBlockPointerCast)
4888 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004889
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004890 QualType QT = IC->getType();
4891 (void)convertBlockPointerToFunctionPointer(QT);
4892 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4893 std::string Str = "(";
4894 Str += TypeString;
4895 Str += ")";
4896 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4897
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004898 return;
4899}
4900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004901void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4902 SourceLocation DeclLoc = FD->getLocation();
4903 unsigned parenCount = 0;
4904
4905 // We have 1 or more arguments that have closure pointers.
4906 const char *startBuf = SM->getCharacterData(DeclLoc);
4907 const char *startArgList = strchr(startBuf, '(');
4908
4909 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4910
4911 parenCount++;
4912 // advance the location to startArgList.
4913 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4914 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4915
4916 const char *argPtr = startArgList;
4917
4918 while (*argPtr++ && parenCount) {
4919 switch (*argPtr) {
4920 case '^':
4921 // Replace the '^' with '*'.
4922 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4923 ReplaceText(DeclLoc, 1, "*");
4924 break;
4925 case '(':
4926 parenCount++;
4927 break;
4928 case ')':
4929 parenCount--;
4930 break;
4931 }
4932 }
4933 return;
4934}
4935
4936bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4937 const FunctionProtoType *FTP;
4938 const PointerType *PT = QT->getAs<PointerType>();
4939 if (PT) {
4940 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4941 } else {
4942 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4943 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4944 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4945 }
4946 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004947 for (const auto &I : FTP->param_types())
4948 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004949 return true;
4950 }
4951 return false;
4952}
4953
4954bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4955 const FunctionProtoType *FTP;
4956 const PointerType *PT = QT->getAs<PointerType>();
4957 if (PT) {
4958 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4959 } else {
4960 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4961 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4962 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4963 }
4964 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004965 for (const auto &I : FTP->param_types()) {
4966 if (I->isObjCQualifiedIdType())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004967 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004968 if (I->isObjCObjectPointerType() &&
4969 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004970 return true;
4971 }
4972
4973 }
4974 return false;
4975}
4976
4977void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4978 const char *&RParen) {
4979 const char *argPtr = strchr(Name, '(');
4980 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4981
4982 LParen = argPtr; // output the start.
4983 argPtr++; // skip past the left paren.
4984 unsigned parenCount = 1;
4985
4986 while (*argPtr && parenCount) {
4987 switch (*argPtr) {
4988 case '(': parenCount++; break;
4989 case ')': parenCount--; break;
4990 default: break;
4991 }
4992 if (parenCount) argPtr++;
4993 }
4994 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4995 RParen = argPtr; // output the end
4996}
4997
4998void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4999 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5000 RewriteBlockPointerFunctionArgs(FD);
5001 return;
5002 }
5003 // Handle Variables and Typedefs.
5004 SourceLocation DeclLoc = ND->getLocation();
5005 QualType DeclT;
5006 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5007 DeclT = VD->getType();
5008 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5009 DeclT = TDD->getUnderlyingType();
5010 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5011 DeclT = FD->getType();
5012 else
5013 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5014
5015 const char *startBuf = SM->getCharacterData(DeclLoc);
5016 const char *endBuf = startBuf;
5017 // scan backward (from the decl location) for the end of the previous decl.
5018 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5019 startBuf--;
5020 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5021 std::string buf;
5022 unsigned OrigLength=0;
5023 // *startBuf != '^' if we are dealing with a pointer to function that
5024 // may take block argument types (which will be handled below).
5025 if (*startBuf == '^') {
5026 // Replace the '^' with '*', computing a negative offset.
5027 buf = '*';
5028 startBuf++;
5029 OrigLength++;
5030 }
5031 while (*startBuf != ')') {
5032 buf += *startBuf;
5033 startBuf++;
5034 OrigLength++;
5035 }
5036 buf += ')';
5037 OrigLength++;
5038
5039 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5040 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5041 // Replace the '^' with '*' for arguments.
5042 // Replace id<P> with id/*<>*/
5043 DeclLoc = ND->getLocation();
5044 startBuf = SM->getCharacterData(DeclLoc);
5045 const char *argListBegin, *argListEnd;
5046 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5047 while (argListBegin < argListEnd) {
5048 if (*argListBegin == '^')
5049 buf += '*';
5050 else if (*argListBegin == '<') {
5051 buf += "/*";
5052 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005053 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005054 while (*argListBegin != '>') {
5055 buf += *argListBegin++;
5056 OrigLength++;
5057 }
5058 buf += *argListBegin;
5059 buf += "*/";
5060 }
5061 else
5062 buf += *argListBegin;
5063 argListBegin++;
5064 OrigLength++;
5065 }
5066 buf += ')';
5067 OrigLength++;
5068 }
5069 ReplaceText(Start, OrigLength, buf);
5070
5071 return;
5072}
5073
5074
5075/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5076/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5077/// struct Block_byref_id_object *src) {
5078/// _Block_object_assign (&_dest->object, _src->object,
5079/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5080/// [|BLOCK_FIELD_IS_WEAK]) // object
5081/// _Block_object_assign(&_dest->object, _src->object,
5082/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5083/// [|BLOCK_FIELD_IS_WEAK]) // block
5084/// }
5085/// And:
5086/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5087/// _Block_object_dispose(_src->object,
5088/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5089/// [|BLOCK_FIELD_IS_WEAK]) // object
5090/// _Block_object_dispose(_src->object,
5091/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5092/// [|BLOCK_FIELD_IS_WEAK]) // block
5093/// }
5094
5095std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5096 int flag) {
5097 std::string S;
5098 if (CopyDestroyCache.count(flag))
5099 return S;
5100 CopyDestroyCache.insert(flag);
5101 S = "static void __Block_byref_id_object_copy_";
5102 S += utostr(flag);
5103 S += "(void *dst, void *src) {\n";
5104
5105 // offset into the object pointer is computed as:
5106 // void * + void* + int + int + void* + void *
5107 unsigned IntSize =
5108 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5109 unsigned VoidPtrSize =
5110 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5111
5112 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5113 S += " _Block_object_assign((char*)dst + ";
5114 S += utostr(offset);
5115 S += ", *(void * *) ((char*)src + ";
5116 S += utostr(offset);
5117 S += "), ";
5118 S += utostr(flag);
5119 S += ");\n}\n";
5120
5121 S += "static void __Block_byref_id_object_dispose_";
5122 S += utostr(flag);
5123 S += "(void *src) {\n";
5124 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5125 S += utostr(offset);
5126 S += "), ";
5127 S += utostr(flag);
5128 S += ");\n}\n";
5129 return S;
5130}
5131
5132/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5133/// the declaration into:
5134/// struct __Block_byref_ND {
5135/// void *__isa; // NULL for everything except __weak pointers
5136/// struct __Block_byref_ND *__forwarding;
5137/// int32_t __flags;
5138/// int32_t __size;
5139/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5140/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5141/// typex ND;
5142/// };
5143///
5144/// It then replaces declaration of ND variable with:
5145/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5146/// __size=sizeof(struct __Block_byref_ND),
5147/// ND=initializer-if-any};
5148///
5149///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005150void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5151 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005152 int flag = 0;
5153 int isa = 0;
5154 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5155 if (DeclLoc.isInvalid())
5156 // If type location is missing, it is because of missing type (a warning).
5157 // Use variable's location which is good for this case.
5158 DeclLoc = ND->getLocation();
5159 const char *startBuf = SM->getCharacterData(DeclLoc);
5160 SourceLocation X = ND->getLocEnd();
5161 X = SM->getExpansionLoc(X);
5162 const char *endBuf = SM->getCharacterData(X);
5163 std::string Name(ND->getNameAsString());
5164 std::string ByrefType;
5165 RewriteByRefString(ByrefType, Name, ND, true);
5166 ByrefType += " {\n";
5167 ByrefType += " void *__isa;\n";
5168 RewriteByRefString(ByrefType, Name, ND);
5169 ByrefType += " *__forwarding;\n";
5170 ByrefType += " int __flags;\n";
5171 ByrefType += " int __size;\n";
5172 // Add void *__Block_byref_id_object_copy;
5173 // void *__Block_byref_id_object_dispose; if needed.
5174 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005175 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005176 if (HasCopyAndDispose) {
5177 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5178 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5179 }
5180
5181 QualType T = Ty;
5182 (void)convertBlockPointerToFunctionPointer(T);
5183 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5184
5185 ByrefType += " " + Name + ";\n";
5186 ByrefType += "};\n";
5187 // Insert this type in global scope. It is needed by helper function.
5188 SourceLocation FunLocStart;
5189 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005190 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005191 else {
5192 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5193 FunLocStart = CurMethodDef->getLocStart();
5194 }
5195 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005196
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005197 if (Ty.isObjCGCWeak()) {
5198 flag |= BLOCK_FIELD_IS_WEAK;
5199 isa = 1;
5200 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005201 if (HasCopyAndDispose) {
5202 flag = BLOCK_BYREF_CALLER;
5203 QualType Ty = ND->getType();
5204 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5205 if (Ty->isBlockPointerType())
5206 flag |= BLOCK_FIELD_IS_BLOCK;
5207 else
5208 flag |= BLOCK_FIELD_IS_OBJECT;
5209 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5210 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005211 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005212 }
5213
5214 // struct __Block_byref_ND ND =
5215 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5216 // initializer-if-any};
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005217 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005218 // FIXME. rewriter does not support __block c++ objects which
5219 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005220 if (hasInit)
5221 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5222 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5223 if (CXXDecl && CXXDecl->isDefaultConstructor())
5224 hasInit = false;
5225 }
5226
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005227 unsigned flags = 0;
5228 if (HasCopyAndDispose)
5229 flags |= BLOCK_HAS_COPY_DISPOSE;
5230 Name = ND->getNameAsString();
5231 ByrefType.clear();
5232 RewriteByRefString(ByrefType, Name, ND);
5233 std::string ForwardingCastType("(");
5234 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005235 ByrefType += " " + Name + " = {(void*)";
5236 ByrefType += utostr(isa);
5237 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5238 ByrefType += utostr(flags);
5239 ByrefType += ", ";
5240 ByrefType += "sizeof(";
5241 RewriteByRefString(ByrefType, Name, ND);
5242 ByrefType += ")";
5243 if (HasCopyAndDispose) {
5244 ByrefType += ", __Block_byref_id_object_copy_";
5245 ByrefType += utostr(flag);
5246 ByrefType += ", __Block_byref_id_object_dispose_";
5247 ByrefType += utostr(flag);
5248 }
5249
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005250 if (!firstDecl) {
5251 // In multiple __block declarations, and for all but 1st declaration,
5252 // find location of the separating comma. This would be start location
5253 // where new text is to be inserted.
5254 DeclLoc = ND->getLocation();
5255 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5256 const char *commaBuf = startDeclBuf;
5257 while (*commaBuf != ',')
5258 commaBuf--;
5259 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5260 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5261 startBuf = commaBuf;
5262 }
5263
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005264 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005265 ByrefType += "};\n";
5266 unsigned nameSize = Name.size();
5267 // for block or function pointer declaration. Name is aleady
5268 // part of the declaration.
5269 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5270 nameSize = 1;
5271 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5272 }
5273 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005274 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005275 SourceLocation startLoc;
5276 Expr *E = ND->getInit();
5277 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5278 startLoc = ECE->getLParenLoc();
5279 else
5280 startLoc = E->getLocStart();
5281 startLoc = SM->getExpansionLoc(startLoc);
5282 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005283 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005284
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005285 const char separator = lastDecl ? ';' : ',';
5286 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5287 const char *separatorBuf = strchr(startInitializerBuf, separator);
5288 assert((*separatorBuf == separator) &&
5289 "RewriteByRefVar: can't find ';' or ','");
5290 SourceLocation separatorLoc =
5291 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5292
5293 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005294 }
5295 return;
5296}
5297
5298void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5299 // Add initializers for any closure decl refs.
5300 GetBlockDeclRefExprs(Exp->getBody());
5301 if (BlockDeclRefs.size()) {
5302 // Unique all "by copy" declarations.
5303 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005304 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005305 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5306 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5307 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5308 }
5309 }
5310 // Unique all "by ref" declarations.
5311 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005312 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005313 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5314 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5315 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5316 }
5317 }
5318 // Find any imported blocks...they will need special attention.
5319 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005320 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005321 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5322 BlockDeclRefs[i]->getType()->isBlockPointerType())
5323 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5324 }
5325}
5326
5327FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5328 IdentifierInfo *ID = &Context->Idents.get(name);
5329 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5330 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005331 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005332 false, false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005333}
5334
5335Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00005336 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005337
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005338 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005339
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005340 Blocks.push_back(Exp);
5341
5342 CollectBlockDeclRefInfo(Exp);
5343
5344 // Add inner imported variables now used in current block.
5345 int countOfInnerDecls = 0;
5346 if (!InnerBlockDeclRefs.empty()) {
5347 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005348 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005349 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005350 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005351 // We need to save the copied-in variables in nested
5352 // blocks because it is needed at the end for some of the API generations.
5353 // See SynthesizeBlockLiterals routine.
5354 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5355 BlockDeclRefs.push_back(Exp);
5356 BlockByCopyDeclsPtrSet.insert(VD);
5357 BlockByCopyDecls.push_back(VD);
5358 }
John McCallf4b88a42012-03-10 09:33:50 +00005359 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005360 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5361 BlockDeclRefs.push_back(Exp);
5362 BlockByRefDeclsPtrSet.insert(VD);
5363 BlockByRefDecls.push_back(VD);
5364 }
5365 }
5366 // Find any imported blocks...they will need special attention.
5367 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005368 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005369 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5370 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5371 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5372 }
5373 InnerDeclRefsCount.push_back(countOfInnerDecls);
5374
5375 std::string FuncName;
5376
5377 if (CurFunctionDef)
5378 FuncName = CurFunctionDef->getNameAsString();
5379 else if (CurMethodDef)
5380 BuildUniqueMethodName(FuncName, CurMethodDef);
5381 else if (GlobalVarDecl)
5382 FuncName = std::string(GlobalVarDecl->getNameAsString());
5383
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005384 bool GlobalBlockExpr =
5385 block->getDeclContext()->getRedeclContext()->isFileContext();
5386
5387 if (GlobalBlockExpr && !GlobalVarDecl) {
5388 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5389 GlobalBlockExpr = false;
5390 }
5391
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005392 std::string BlockNumber = utostr(Blocks.size()-1);
5393
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005394 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5395
5396 // Get a pointer to the function type so we can cast appropriately.
5397 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5398 QualType FType = Context->getPointerType(BFT);
5399
5400 FunctionDecl *FD;
5401 Expr *NewRep;
5402
Benjamin Kramere5753592013-09-09 14:48:42 +00005403 // Simulate a constructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005404 std::string Tag;
5405
5406 if (GlobalBlockExpr)
5407 Tag = "__global_";
5408 else
5409 Tag = "__";
5410 Tag += FuncName + "_block_impl_" + BlockNumber;
5411
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005412 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005413 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005414 SourceLocation());
5415
5416 SmallVector<Expr*, 4> InitExprs;
5417
5418 // Initialize the block function.
5419 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005420 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5421 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005422 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5423 CK_BitCast, Arg);
5424 InitExprs.push_back(castExpr);
5425
5426 // Initialize the block descriptor.
5427 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5428
5429 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5430 SourceLocation(), SourceLocation(),
5431 &Context->Idents.get(DescData.c_str()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005432 Context->VoidPtrTy, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005433 SC_Static);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005434 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005435 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005436 Context->VoidPtrTy,
5437 VK_LValue,
5438 SourceLocation()),
5439 UO_AddrOf,
5440 Context->getPointerType(Context->VoidPtrTy),
5441 VK_RValue, OK_Ordinary,
5442 SourceLocation());
5443 InitExprs.push_back(DescRefExpr);
5444
5445 // Add initializers for any closure decl refs.
5446 if (BlockDeclRefs.size()) {
5447 Expr *Exp;
5448 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005449 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005450 E = BlockByCopyDecls.end(); I != E; ++I) {
5451 if (isObjCType((*I)->getType())) {
5452 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5453 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005454 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5455 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005456 if (HasLocalVariableExternalStorage(*I)) {
5457 QualType QT = (*I)->getType();
5458 QT = Context->getPointerType(QT);
5459 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5460 OK_Ordinary, SourceLocation());
5461 }
5462 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5463 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005464 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5465 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005466 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5467 CK_BitCast, Arg);
5468 } else {
5469 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005470 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5471 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005472 if (HasLocalVariableExternalStorage(*I)) {
5473 QualType QT = (*I)->getType();
5474 QT = Context->getPointerType(QT);
5475 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5476 OK_Ordinary, SourceLocation());
5477 }
5478
5479 }
5480 InitExprs.push_back(Exp);
5481 }
5482 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005483 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005484 E = BlockByRefDecls.end(); I != E; ++I) {
5485 ValueDecl *ND = (*I);
5486 std::string Name(ND->getNameAsString());
5487 std::string RecName;
5488 RewriteByRefString(RecName, Name, ND, true);
5489 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5490 + sizeof("struct"));
5491 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5492 SourceLocation(), SourceLocation(),
5493 II);
5494 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5495 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5496
5497 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005498 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005499 SourceLocation());
5500 bool isNestedCapturedVar = false;
5501 if (block)
Stephen Hines651f13c2014-04-23 16:59:28 -07005502 for (const auto &CI : block->captures()) {
5503 const VarDecl *variable = CI.getVariable();
5504 if (variable == ND && CI.isNested()) {
5505 assert (CI.isByRef() &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005506 "SynthBlockInitExpr - captured block variable is not byref");
5507 isNestedCapturedVar = true;
5508 break;
5509 }
5510 }
5511 // captured nested byref variable has its address passed. Do not take
5512 // its address again.
5513 if (!isNestedCapturedVar)
5514 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5515 Context->getPointerType(Exp->getType()),
5516 VK_RValue, OK_Ordinary, SourceLocation());
5517 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5518 InitExprs.push_back(Exp);
5519 }
5520 }
5521 if (ImportedBlockDecls.size()) {
5522 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5523 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5524 unsigned IntSize =
5525 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5526 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5527 Context->IntTy, SourceLocation());
5528 InitExprs.push_back(FlagExp);
5529 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005530 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005531 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005532
5533 if (GlobalBlockExpr) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005534 assert (!GlobalConstructionExp &&
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005535 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5536 GlobalConstructionExp = NewRep;
5537 NewRep = DRE;
5538 }
5539
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005540 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5541 Context->getPointerType(NewRep->getType()),
5542 VK_RValue, OK_Ordinary, SourceLocation());
5543 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5544 NewRep);
5545 BlockDeclRefs.clear();
5546 BlockByRefDecls.clear();
5547 BlockByRefDeclsPtrSet.clear();
5548 BlockByCopyDecls.clear();
5549 BlockByCopyDeclsPtrSet.clear();
5550 ImportedBlockDecls.clear();
5551 return NewRep;
5552}
5553
5554bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5555 if (const ObjCForCollectionStmt * CS =
5556 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5557 return CS->getElement() == DS;
5558 return false;
5559}
5560
5561//===----------------------------------------------------------------------===//
5562// Function Body / Expression rewriting
5563//===----------------------------------------------------------------------===//
5564
5565Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5566 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5567 isa<DoStmt>(S) || isa<ForStmt>(S))
5568 Stmts.push_back(S);
5569 else if (isa<ObjCForCollectionStmt>(S)) {
5570 Stmts.push_back(S);
5571 ObjCBcLabelNo.push_back(++BcLabelCount);
5572 }
5573
5574 // Pseudo-object operations and ivar references need special
5575 // treatment because we're going to recursively rewrite them.
5576 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5577 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5578 return RewritePropertyOrImplicitSetter(PseudoOp);
5579 } else {
5580 return RewritePropertyOrImplicitGetter(PseudoOp);
5581 }
5582 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5583 return RewriteObjCIvarRefExpr(IvarRefExpr);
5584 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005585 else if (isa<OpaqueValueExpr>(S))
5586 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005587
5588 SourceRange OrigStmtRange = S->getSourceRange();
5589
5590 // Perform a bottom up rewrite of all children.
5591 for (Stmt::child_range CI = S->children(); CI; ++CI)
5592 if (*CI) {
5593 Stmt *childStmt = (*CI);
5594 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5595 if (newStmt) {
5596 *CI = newStmt;
5597 }
5598 }
5599
5600 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005601 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005602 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5603 InnerContexts.insert(BE->getBlockDecl());
5604 ImportedLocalExternalDecls.clear();
5605 GetInnerBlockDeclRefExprs(BE->getBody(),
5606 InnerBlockDeclRefs, InnerContexts);
5607 // Rewrite the block body in place.
5608 Stmt *SaveCurrentBody = CurrentBody;
5609 CurrentBody = BE->getBody();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005610 PropParentMap = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005611 // block literal on rhs of a property-dot-sytax assignment
5612 // must be replaced by its synthesize ast so getRewrittenText
5613 // works as expected. In this case, what actually ends up on RHS
5614 // is the blockTranscribed which is the helper function for the
5615 // block literal; as in: self.c = ^() {[ace ARR];};
5616 bool saveDisableReplaceStmt = DisableReplaceStmt;
5617 DisableReplaceStmt = false;
5618 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5619 DisableReplaceStmt = saveDisableReplaceStmt;
5620 CurrentBody = SaveCurrentBody;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005621 PropParentMap = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005622 ImportedLocalExternalDecls.clear();
5623 // Now we snarf the rewritten text and stash it away for later use.
5624 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5625 RewrittenBlockExprs[BE] = Str;
5626
5627 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5628
5629 //blockTranscribed->dump();
5630 ReplaceStmt(S, blockTranscribed);
5631 return blockTranscribed;
5632 }
5633 // Handle specific things.
5634 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5635 return RewriteAtEncode(AtEncode);
5636
5637 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5638 return RewriteAtSelector(AtSelector);
5639
5640 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5641 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005642
5643 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5644 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005645
Patrick Beardeb382ec2012-04-19 00:25:12 +00005646 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5647 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005648
5649 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5650 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005651
5652 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5653 dyn_cast<ObjCDictionaryLiteral>(S))
5654 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005655
5656 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5657#if 0
5658 // Before we rewrite it, put the original message expression in a comment.
5659 SourceLocation startLoc = MessExpr->getLocStart();
5660 SourceLocation endLoc = MessExpr->getLocEnd();
5661
5662 const char *startBuf = SM->getCharacterData(startLoc);
5663 const char *endBuf = SM->getCharacterData(endLoc);
5664
5665 std::string messString;
5666 messString += "// ";
5667 messString.append(startBuf, endBuf-startBuf+1);
5668 messString += "\n";
5669
5670 // FIXME: Missing definition of
5671 // InsertText(clang::SourceLocation, char const*, unsigned int).
5672 // InsertText(startLoc, messString.c_str(), messString.size());
5673 // Tried this, but it didn't work either...
5674 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5675#endif
5676 return RewriteMessageExpr(MessExpr);
5677 }
5678
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005679 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5680 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5681 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5682 }
5683
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005684 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5685 return RewriteObjCTryStmt(StmtTry);
5686
5687 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5688 return RewriteObjCSynchronizedStmt(StmtTry);
5689
5690 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5691 return RewriteObjCThrowStmt(StmtThrow);
5692
5693 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5694 return RewriteObjCProtocolExpr(ProtocolExp);
5695
5696 if (ObjCForCollectionStmt *StmtForCollection =
5697 dyn_cast<ObjCForCollectionStmt>(S))
5698 return RewriteObjCForCollectionStmt(StmtForCollection,
5699 OrigStmtRange.getEnd());
5700 if (BreakStmt *StmtBreakStmt =
5701 dyn_cast<BreakStmt>(S))
5702 return RewriteBreakStmt(StmtBreakStmt);
5703 if (ContinueStmt *StmtContinueStmt =
5704 dyn_cast<ContinueStmt>(S))
5705 return RewriteContinueStmt(StmtContinueStmt);
5706
5707 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5708 // and cast exprs.
5709 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5710 // FIXME: What we're doing here is modifying the type-specifier that
5711 // precedes the first Decl. In the future the DeclGroup should have
5712 // a separate type-specifier that we can rewrite.
5713 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5714 // the context of an ObjCForCollectionStmt. For example:
5715 // NSArray *someArray;
5716 // for (id <FooProtocol> index in someArray) ;
5717 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5718 // and it depends on the original text locations/positions.
5719 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5720 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5721
5722 // Blocks rewrite rules.
5723 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5724 DI != DE; ++DI) {
5725 Decl *SD = *DI;
5726 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5727 if (isTopLevelBlockPointerType(ND->getType()))
5728 RewriteBlockPointerDecl(ND);
5729 else if (ND->getType()->isFunctionPointerType())
5730 CheckFunctionPointerDecl(ND->getType(), ND);
5731 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5732 if (VD->hasAttr<BlocksAttr>()) {
5733 static unsigned uniqueByrefDeclCount = 0;
5734 assert(!BlockByRefDeclNo.count(ND) &&
5735 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5736 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005737 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005738 }
5739 else
5740 RewriteTypeOfDecl(VD);
5741 }
5742 }
5743 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5744 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5745 RewriteBlockPointerDecl(TD);
5746 else if (TD->getUnderlyingType()->isFunctionPointerType())
5747 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5748 }
5749 }
5750 }
5751
5752 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5753 RewriteObjCQualifiedInterfaceTypes(CE);
5754
5755 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5756 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5757 assert(!Stmts.empty() && "Statement stack is empty");
5758 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5759 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5760 && "Statement stack mismatch");
5761 Stmts.pop_back();
5762 }
5763 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005764 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5765 ValueDecl *VD = DRE->getDecl();
5766 if (VD->hasAttr<BlocksAttr>())
5767 return RewriteBlockDeclRefExpr(DRE);
5768 if (HasLocalVariableExternalStorage(VD))
5769 return RewriteLocalVariableExternalStorage(DRE);
5770 }
5771
5772 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5773 if (CE->getCallee()->getType()->isBlockPointerType()) {
5774 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5775 ReplaceStmt(S, BlockCall);
5776 return BlockCall;
5777 }
5778 }
5779 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5780 RewriteCastExpr(CE);
5781 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005782 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5783 RewriteImplicitCastObjCExpr(ICE);
5784 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005785#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005786
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005787 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5788 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5789 ICE->getSubExpr(),
5790 SourceLocation());
5791 // Get the new text.
5792 std::string SStr;
5793 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005794 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005795 const std::string &Str = Buf.str();
5796
5797 printf("CAST = %s\n", &Str[0]);
5798 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5799 delete S;
5800 return Replacement;
5801 }
5802#endif
5803 // Return this stmt unmodified.
5804 return S;
5805}
5806
5807void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005808 for (auto *FD : RD->fields()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005809 if (isTopLevelBlockPointerType(FD->getType()))
5810 RewriteBlockPointerDecl(FD);
5811 if (FD->getType()->isObjCQualifiedIdType() ||
5812 FD->getType()->isObjCQualifiedInterfaceType())
5813 RewriteObjCQualifiedInterfaceTypes(FD);
5814 }
5815}
5816
5817/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5818/// main file of the input.
5819void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5820 switch (D->getKind()) {
5821 case Decl::Function: {
5822 FunctionDecl *FD = cast<FunctionDecl>(D);
5823 if (FD->isOverloadedOperator())
5824 return;
5825
5826 // Since function prototypes don't have ParmDecl's, we check the function
5827 // prototype. This enables us to rewrite function declarations and
5828 // definitions using the same code.
5829 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5830
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005831 if (!FD->isThisDeclarationADefinition())
5832 break;
5833
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005834 // FIXME: If this should support Obj-C++, support CXXTryStmt
5835 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5836 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005837 CurrentBody = Body;
5838 Body =
5839 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5840 FD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005841 CurrentBody = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842 if (PropParentMap) {
5843 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005844 PropParentMap = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005845 }
5846 // This synthesizes and inserts the block "impl" struct, invoke function,
5847 // and any copy/dispose helper functions.
5848 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005849 RewriteLineDirective(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005850 CurFunctionDef = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005851 }
5852 break;
5853 }
5854 case Decl::ObjCMethod: {
5855 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5856 if (CompoundStmt *Body = MD->getCompoundBody()) {
5857 CurMethodDef = MD;
5858 CurrentBody = Body;
5859 Body =
5860 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5861 MD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005862 CurrentBody = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005863 if (PropParentMap) {
5864 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005865 PropParentMap = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005866 }
5867 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005868 RewriteLineDirective(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005869 CurMethodDef = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005870 }
5871 break;
5872 }
5873 case Decl::ObjCImplementation: {
5874 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5875 ClassImplementation.push_back(CI);
5876 break;
5877 }
5878 case Decl::ObjCCategoryImpl: {
5879 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5880 CategoryImplementation.push_back(CI);
5881 break;
5882 }
5883 case Decl::Var: {
5884 VarDecl *VD = cast<VarDecl>(D);
5885 RewriteObjCQualifiedInterfaceTypes(VD);
5886 if (isTopLevelBlockPointerType(VD->getType()))
5887 RewriteBlockPointerDecl(VD);
5888 else if (VD->getType()->isFunctionPointerType()) {
5889 CheckFunctionPointerDecl(VD->getType(), VD);
5890 if (VD->getInit()) {
5891 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5892 RewriteCastExpr(CE);
5893 }
5894 }
5895 } else if (VD->getType()->isRecordType()) {
5896 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5897 if (RD->isCompleteDefinition())
5898 RewriteRecordBody(RD);
5899 }
5900 if (VD->getInit()) {
5901 GlobalVarDecl = VD;
5902 CurrentBody = VD->getInit();
5903 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005904 CurrentBody = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005905 if (PropParentMap) {
5906 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005907 PropParentMap = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005908 }
5909 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005910 GlobalVarDecl = nullptr;
5911
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005912 // This is needed for blocks.
5913 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5914 RewriteCastExpr(CE);
5915 }
5916 }
5917 break;
5918 }
5919 case Decl::TypeAlias:
5920 case Decl::Typedef: {
5921 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5922 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5923 RewriteBlockPointerDecl(TD);
5924 else if (TD->getUnderlyingType()->isFunctionPointerType())
5925 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00005926 else
5927 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005928 }
5929 break;
5930 }
5931 case Decl::CXXRecord:
5932 case Decl::Record: {
5933 RecordDecl *RD = cast<RecordDecl>(D);
5934 if (RD->isCompleteDefinition())
5935 RewriteRecordBody(RD);
5936 break;
5937 }
5938 default:
5939 break;
5940 }
5941 // Nothing yet.
5942}
5943
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005944/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5945/// protocol reference symbols in the for of:
5946/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5947static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5948 ObjCProtocolDecl *PDecl,
5949 std::string &Result) {
5950 // Also output .objc_protorefs$B section and its meta-data.
5951 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005952 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005953 Result += "struct _protocol_t *";
5954 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5955 Result += PDecl->getNameAsString();
5956 Result += " = &";
5957 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5958 Result += ";\n";
5959}
5960
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005961void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5962 if (Diags.hasErrorOccurred())
5963 return;
5964
5965 RewriteInclude();
5966
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005967 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005968 // translation of function bodies were postponed until all class and
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005969 // their extensions and implementations are seen. This is because, we
Stephen Hines651f13c2014-04-23 16:59:28 -07005970 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005971 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5972 HandleTopLevelSingleDecl(FDecl);
5973 }
5974
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005975 // Here's a great place to add any extra declarations that may be needed.
5976 // Write out meta data for each @protocol(<expr>).
5977 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005978 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005979 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005980 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5981 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005982
5983 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005984
5985 if (ClassImplementation.size() || CategoryImplementation.size())
5986 RewriteImplementations();
5987
Fariborz Jahanian57317782012-02-21 23:58:41 +00005988 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5989 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5990 // Write struct declaration for the class matching its ivar declarations.
5991 // Note that for modern abi, this is postponed until the end of TU
5992 // because class extensions and the implementation might declare their own
5993 // private ivars.
5994 RewriteInterfaceDecl(CDecl);
5995 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005997 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5998 // we are done.
5999 if (const RewriteBuffer *RewriteBuf =
6000 Rewrite.getRewriteBufferFor(MainFileID)) {
6001 //printf("Changed:\n");
6002 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6003 } else {
6004 llvm::errs() << "No changes\n";
6005 }
6006
6007 if (ClassImplementation.size() || CategoryImplementation.size() ||
6008 ProtocolExprDecls.size()) {
6009 // Rewrite Objective-c meta data*
6010 std::string ResultStr;
6011 RewriteMetaDataIntoBuffer(ResultStr);
6012 // Emit metadata.
6013 *OutFile << ResultStr;
6014 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006015 // Emit ImageInfo;
6016 {
6017 std::string ResultStr;
6018 WriteImageInfo(ResultStr);
6019 *OutFile << ResultStr;
6020 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006021 OutFile->flush();
6022}
6023
6024void RewriteModernObjC::Initialize(ASTContext &context) {
6025 InitializeCommon(context);
6026
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006027 Preamble += "#ifndef __OBJC2__\n";
6028 Preamble += "#define __OBJC2__\n";
6029 Preamble += "#endif\n";
6030
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006031 // declaring objc_selector outside the parameter list removes a silly
6032 // scope related warning...
6033 if (IsHeader)
6034 Preamble = "#pragma once\n";
6035 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006036 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6037 Preamble += "\n\tstruct objc_object *superClass; ";
6038 // Add a constructor for creating temporary objects.
6039 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6040 Preamble += ": object(o), superClass(s) {} ";
6041 Preamble += "\n};\n";
6042
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006043 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006044 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006045 // These are currently generated.
6046 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006047 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006048 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006049 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6050 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006051 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006052 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006053 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6054 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006055 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006056
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006057 // These need be generated for performance. Currently they are not,
6058 // using API calls instead.
6059 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6060 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6061 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6062
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006063 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006064 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6065 Preamble += "typedef struct objc_object Protocol;\n";
6066 Preamble += "#define _REWRITER_typedef_Protocol\n";
6067 Preamble += "#endif\n";
6068 if (LangOpts.MicrosoftExt) {
6069 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6070 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006071 }
6072 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006073 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006074
6075 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6076 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6077 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6078 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6079 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6080
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006081 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006082 Preamble += "(const char *);\n";
6083 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6084 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006086 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006087 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006088 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006089 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6090 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006091 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00006092 Preamble += "#ifdef _WIN64\n";
6093 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6094 Preamble += "#else\n";
6095 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6096 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006097 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6098 Preamble += "struct __objcFastEnumerationState {\n\t";
6099 Preamble += "unsigned long state;\n\t";
6100 Preamble += "void **itemsPtr;\n\t";
6101 Preamble += "unsigned long *mutationsPtr;\n\t";
6102 Preamble += "unsigned long extra[5];\n};\n";
6103 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6104 Preamble += "#define __FASTENUMERATIONSTATE\n";
6105 Preamble += "#endif\n";
6106 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6107 Preamble += "struct __NSConstantStringImpl {\n";
6108 Preamble += " int *isa;\n";
6109 Preamble += " int flags;\n";
6110 Preamble += " char *str;\n";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006111 Preamble += "#if _WIN64\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07006112 Preamble += " long long length;\n";
6113 Preamble += "#else\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006114 Preamble += " long length;\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07006115 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006116 Preamble += "};\n";
6117 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6118 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6119 Preamble += "#else\n";
6120 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6121 Preamble += "#endif\n";
6122 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6123 Preamble += "#endif\n";
6124 // Blocks preamble.
6125 Preamble += "#ifndef BLOCK_IMPL\n";
6126 Preamble += "#define BLOCK_IMPL\n";
6127 Preamble += "struct __block_impl {\n";
6128 Preamble += " void *isa;\n";
6129 Preamble += " int Flags;\n";
6130 Preamble += " int Reserved;\n";
6131 Preamble += " void *FuncPtr;\n";
6132 Preamble += "};\n";
6133 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6134 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6135 Preamble += "extern \"C\" __declspec(dllexport) "
6136 "void _Block_object_assign(void *, const void *, const int);\n";
6137 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6138 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6139 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6140 Preamble += "#else\n";
6141 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6142 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6143 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6144 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6145 Preamble += "#endif\n";
6146 Preamble += "#endif\n";
6147 if (LangOpts.MicrosoftExt) {
6148 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6149 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6150 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6151 Preamble += "#define __attribute__(X)\n";
6152 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006153 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006154 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006155 Preamble += "#endif\n";
6156 Preamble += "#ifndef __block\n";
6157 Preamble += "#define __block\n";
6158 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006159 }
6160 else {
6161 Preamble += "#define __block\n";
6162 Preamble += "#define __weak\n";
6163 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006164
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006165 // Declarations required for modern objective-c array and dictionary literals.
6166 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006167 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006168 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006169 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006170 Preamble += "\tva_list marker;\n";
6171 Preamble += "\tva_start(marker, count);\n";
6172 Preamble += "\tarr = new void *[count];\n";
6173 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6174 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6175 Preamble += "\tva_end( marker );\n";
6176 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006177 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006178 Preamble += "\tdelete[] arr;\n";
6179 Preamble += " }\n";
6180 Preamble += "};\n";
6181
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006182 // Declaration required for implementation of @autoreleasepool statement.
6183 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6184 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6185 Preamble += "struct __AtAutoreleasePool {\n";
6186 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6187 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6188 Preamble += " void * atautoreleasepoolobj;\n";
6189 Preamble += "};\n";
6190
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006191 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6192 // as this avoids warning in any 64bit/32bit compilation model.
6193 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6194}
6195
6196/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6197/// ivar offset.
6198void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6199 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006200 Result += "__OFFSETOFIVAR__(struct ";
6201 Result += ivar->getContainingInterface()->getNameAsString();
6202 if (LangOpts.MicrosoftExt)
6203 Result += "_IMPL";
6204 Result += ", ";
6205 if (ivar->isBitField())
6206 ObjCIvarBitfieldGroupDecl(ivar, Result);
6207 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006208 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006209 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006210}
6211
6212/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6213/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006214/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006215/// char *attributes;
6216/// }
6217
6218/// struct _prop_list_t {
6219/// uint32_t entsize; // sizeof(struct _prop_t)
6220/// uint32_t count_of_properties;
6221/// struct _prop_t prop_list[count_of_properties];
6222/// }
6223
6224/// struct _protocol_t;
6225
6226/// struct _protocol_list_t {
6227/// long protocol_count; // Note, this is 32/64 bit
6228/// struct _protocol_t * protocol_list[protocol_count];
6229/// }
6230
6231/// struct _objc_method {
6232/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006233/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006234/// char *_imp;
6235/// }
6236
6237/// struct _method_list_t {
6238/// uint32_t entsize; // sizeof(struct _objc_method)
6239/// uint32_t method_count;
6240/// struct _objc_method method_list[method_count];
6241/// }
6242
6243/// struct _protocol_t {
6244/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006245/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006246/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006247/// const struct method_list_t *instance_methods;
6248/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006249/// const struct method_list_t *optionalInstanceMethods;
6250/// const struct method_list_t *optionalClassMethods;
6251/// const struct _prop_list_t * properties;
6252/// const uint32_t size; // sizeof(struct _protocol_t)
6253/// const uint32_t flags; // = 0
6254/// const char ** extendedMethodTypes;
6255/// }
6256
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006257/// struct _ivar_t {
6258/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006259/// const char *name;
6260/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006261/// uint32_t alignment;
6262/// uint32_t size;
6263/// }
6264
6265/// struct _ivar_list_t {
6266/// uint32 entsize; // sizeof(struct _ivar_t)
6267/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006268/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006269/// }
6270
6271/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006272/// uint32_t flags;
6273/// uint32_t instanceStart;
6274/// uint32_t instanceSize;
6275/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006276/// const uint8_t *ivarLayout;
6277/// const char *name;
6278/// const struct _method_list_t *baseMethods;
6279/// const struct _protocol_list_t *baseProtocols;
6280/// const struct _ivar_list_t *ivars;
6281/// const uint8_t *weakIvarLayout;
6282/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006283/// }
6284
6285/// struct _class_t {
6286/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006287/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006288/// void *cache;
6289/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006290/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006291/// }
6292
6293/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006294/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006295/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006296/// const struct _method_list_t *instance_methods;
6297/// const struct _method_list_t *class_methods;
6298/// const struct _protocol_list_t *protocols;
6299/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006300/// }
6301
6302/// MessageRefTy - LLVM for:
6303/// struct _message_ref_t {
6304/// IMP messenger;
6305/// SEL name;
6306/// };
6307
6308/// SuperMessageRefTy - LLVM for:
6309/// struct _super_message_ref_t {
6310/// SUPER_IMP messenger;
6311/// SEL name;
6312/// };
6313
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006314static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006315 static bool meta_data_declared = false;
6316 if (meta_data_declared)
6317 return;
6318
6319 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006320 Result += "\tconst char *name;\n";
6321 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006322 Result += "};\n";
6323
6324 Result += "\nstruct _protocol_t;\n";
6325
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006326 Result += "\nstruct _objc_method {\n";
6327 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006328 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006329 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006330 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006331
6332 Result += "\nstruct _protocol_t {\n";
6333 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006334 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006335 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006336 Result += "\tconst struct method_list_t *instance_methods;\n";
6337 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006338 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6339 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6340 Result += "\tconst struct _prop_list_t * properties;\n";
6341 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6342 Result += "\tconst unsigned int flags; // = 0\n";
6343 Result += "\tconst char ** extendedMethodTypes;\n";
6344 Result += "};\n";
6345
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006346 Result += "\nstruct _ivar_t {\n";
6347 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006348 Result += "\tconst char *name;\n";
6349 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006350 Result += "\tunsigned int alignment;\n";
6351 Result += "\tunsigned int size;\n";
6352 Result += "};\n";
6353
6354 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006355 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006356 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006357 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006358 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6359 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006360 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006361 Result += "\tconst unsigned char *ivarLayout;\n";
6362 Result += "\tconst char *name;\n";
6363 Result += "\tconst struct _method_list_t *baseMethods;\n";
6364 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6365 Result += "\tconst struct _ivar_list_t *ivars;\n";
6366 Result += "\tconst unsigned char *weakIvarLayout;\n";
6367 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006368 Result += "};\n";
6369
6370 Result += "\nstruct _class_t {\n";
6371 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006372 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006373 Result += "\tvoid *cache;\n";
6374 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006375 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006376 Result += "};\n";
6377
6378 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006379 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006380 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006381 Result += "\tconst struct _method_list_t *instance_methods;\n";
6382 Result += "\tconst struct _method_list_t *class_methods;\n";
6383 Result += "\tconst struct _protocol_list_t *protocols;\n";
6384 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006385 Result += "};\n";
6386
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006387 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006388 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006389 meta_data_declared = true;
6390}
6391
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006392static void Write_protocol_list_t_TypeDecl(std::string &Result,
6393 long super_protocol_count) {
6394 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6395 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6396 Result += "\tstruct _protocol_t *super_protocols[";
6397 Result += utostr(super_protocol_count); Result += "];\n";
6398 Result += "}";
6399}
6400
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006401static void Write_method_list_t_TypeDecl(std::string &Result,
6402 unsigned int method_count) {
6403 Result += "struct /*_method_list_t*/"; Result += " {\n";
6404 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6405 Result += "\tunsigned int method_count;\n";
6406 Result += "\tstruct _objc_method method_list[";
6407 Result += utostr(method_count); Result += "];\n";
6408 Result += "}";
6409}
6410
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006411static void Write__prop_list_t_TypeDecl(std::string &Result,
6412 unsigned int property_count) {
6413 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6414 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6415 Result += "\tunsigned int count_of_properties;\n";
6416 Result += "\tstruct _prop_t prop_list[";
6417 Result += utostr(property_count); Result += "];\n";
6418 Result += "}";
6419}
6420
Fariborz Jahanianae932952012-02-10 20:47:10 +00006421static void Write__ivar_list_t_TypeDecl(std::string &Result,
6422 unsigned int ivar_count) {
6423 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6424 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6425 Result += "\tunsigned int count;\n";
6426 Result += "\tstruct _ivar_t ivar_list[";
6427 Result += utostr(ivar_count); Result += "];\n";
6428 Result += "}";
6429}
6430
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006431static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6432 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6433 StringRef VarName,
6434 StringRef ProtocolName) {
6435 if (SuperProtocols.size() > 0) {
6436 Result += "\nstatic ";
6437 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6438 Result += " "; Result += VarName;
6439 Result += ProtocolName;
6440 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6441 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6442 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6443 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6444 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6445 Result += SuperPD->getNameAsString();
6446 if (i == e-1)
6447 Result += "\n};\n";
6448 else
6449 Result += ",\n";
6450 }
6451 }
6452}
6453
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006454static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6455 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006456 ArrayRef<ObjCMethodDecl *> Methods,
6457 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006458 StringRef TopLevelDeclName,
6459 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006460 if (Methods.size() > 0) {
6461 Result += "\nstatic ";
6462 Write_method_list_t_TypeDecl(Result, Methods.size());
6463 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006464 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006465 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6466 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6467 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6468 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6469 ObjCMethodDecl *MD = Methods[i];
6470 if (i == 0)
6471 Result += "\t{{(struct objc_selector *)\"";
6472 else
6473 Result += "\t{(struct objc_selector *)\"";
6474 Result += (MD)->getSelector().getAsString(); Result += "\"";
6475 Result += ", ";
6476 std::string MethodTypeString;
6477 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6478 Result += "\""; Result += MethodTypeString; Result += "\"";
6479 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006480 if (!MethodImpl)
6481 Result += "0";
6482 else {
6483 Result += "(void *)";
6484 Result += RewriteObj.MethodInternalNames[MD];
6485 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006486 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006487 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006488 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006489 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006490 }
6491 Result += "};\n";
6492 }
6493}
6494
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006495static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006496 ASTContext *Context, std::string &Result,
6497 ArrayRef<ObjCPropertyDecl *> Properties,
6498 const Decl *Container,
6499 StringRef VarName,
6500 StringRef ProtocolName) {
6501 if (Properties.size() > 0) {
6502 Result += "\nstatic ";
6503 Write__prop_list_t_TypeDecl(Result, Properties.size());
6504 Result += " "; Result += VarName;
6505 Result += ProtocolName;
6506 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6507 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6508 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6509 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6510 ObjCPropertyDecl *PropDecl = Properties[i];
6511 if (i == 0)
6512 Result += "\t{{\"";
6513 else
6514 Result += "\t{\"";
6515 Result += PropDecl->getName(); Result += "\",";
6516 std::string PropertyTypeString, QuotePropertyTypeString;
6517 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6518 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6519 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6520 if (i == e-1)
6521 Result += "}}\n";
6522 else
6523 Result += "},\n";
6524 }
6525 Result += "};\n";
6526 }
6527}
6528
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006529// Metadata flags
6530enum MetaDataDlags {
6531 CLS = 0x0,
6532 CLS_META = 0x1,
6533 CLS_ROOT = 0x2,
6534 OBJC2_CLS_HIDDEN = 0x10,
6535 CLS_EXCEPTION = 0x20,
6536
6537 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6538 CLS_HAS_IVAR_RELEASER = 0x40,
6539 /// class was compiled with -fobjc-arr
6540 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6541};
6542
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006543static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6544 unsigned int flags,
6545 const std::string &InstanceStart,
6546 const std::string &InstanceSize,
6547 ArrayRef<ObjCMethodDecl *>baseMethods,
6548 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6549 ArrayRef<ObjCIvarDecl *>ivars,
6550 ArrayRef<ObjCPropertyDecl *>Properties,
6551 StringRef VarName,
6552 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006553 Result += "\nstatic struct _class_ro_t ";
6554 Result += VarName; Result += ClassName;
6555 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6556 Result += "\t";
6557 Result += llvm::utostr(flags); Result += ", ";
6558 Result += InstanceStart; Result += ", ";
6559 Result += InstanceSize; Result += ", \n";
6560 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006561 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6562 if (Triple.getArch() == llvm::Triple::x86_64)
6563 // uint32_t const reserved; // only when building for 64bit targets
6564 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006565 // const uint8_t * const ivarLayout;
6566 Result += "0, \n\t";
6567 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006568 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006569 if (baseMethods.size() > 0) {
6570 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006571 if (metaclass)
6572 Result += "_OBJC_$_CLASS_METHODS_";
6573 else
6574 Result += "_OBJC_$_INSTANCE_METHODS_";
6575 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006576 Result += ",\n\t";
6577 }
6578 else
6579 Result += "0, \n\t";
6580
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006581 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006582 Result += "(const struct _objc_protocol_list *)&";
6583 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6584 Result += ",\n\t";
6585 }
6586 else
6587 Result += "0, \n\t";
6588
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006589 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006590 Result += "(const struct _ivar_list_t *)&";
6591 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6592 Result += ",\n\t";
6593 }
6594 else
6595 Result += "0, \n\t";
6596
6597 // weakIvarLayout
6598 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006599 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006600 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006601 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006602 Result += ",\n";
6603 }
6604 else
6605 Result += "0, \n";
6606
6607 Result += "};\n";
6608}
6609
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006610static void Write_class_t(ASTContext *Context, std::string &Result,
6611 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006612 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6613 bool rootClass = (!CDecl->getSuperClass());
6614 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006615
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006616 if (!rootClass) {
6617 // Find the Root class
6618 RootClass = CDecl->getSuperClass();
6619 while (RootClass->getSuperClass()) {
6620 RootClass = RootClass->getSuperClass();
6621 }
6622 }
6623
6624 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006625 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006626 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006627 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006628 if (CDecl->getImplementation())
6629 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006630 else
6631 Result += "__declspec(dllimport) ";
6632
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006633 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006634 Result += CDecl->getNameAsString();
6635 Result += ";\n";
6636 }
6637 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006638 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006639 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006640 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006641 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006642 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006643 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006644 else
6645 Result += "__declspec(dllimport) ";
6646
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006647 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006648 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006649 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006650 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006651
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006652 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006653 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006654 if (RootClass->getImplementation())
6655 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006656 else
6657 Result += "__declspec(dllimport) ";
6658
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006659 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006660 Result += VarName;
6661 Result += RootClass->getNameAsString();
6662 Result += ";\n";
6663 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006664 }
6665
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006666 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6667 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006668 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6669 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006670 if (metaclass) {
6671 if (!rootClass) {
6672 Result += "0, // &"; Result += VarName;
6673 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006674 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006675 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006676 Result += CDecl->getSuperClass()->getNameAsString();
6677 Result += ",\n\t";
6678 }
6679 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006680 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006681 Result += CDecl->getNameAsString();
6682 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006683 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006684 Result += ",\n\t";
6685 }
6686 }
6687 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006688 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006689 Result += CDecl->getNameAsString();
6690 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006691 if (!rootClass) {
6692 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006693 Result += CDecl->getSuperClass()->getNameAsString();
6694 Result += ",\n\t";
6695 }
6696 else
6697 Result += "0,\n\t";
6698 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006699 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6700 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6701 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006702 Result += "&_OBJC_METACLASS_RO_$_";
6703 else
6704 Result += "&_OBJC_CLASS_RO_$_";
6705 Result += CDecl->getNameAsString();
6706 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006707
6708 // Add static function to initialize some of the meta-data fields.
6709 // avoid doing it twice.
6710 if (metaclass)
6711 return;
6712
6713 const ObjCInterfaceDecl *SuperClass =
6714 rootClass ? CDecl : CDecl->getSuperClass();
6715
6716 Result += "static void OBJC_CLASS_SETUP_$_";
6717 Result += CDecl->getNameAsString();
6718 Result += "(void ) {\n";
6719 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6720 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006721 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006722
6723 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006724 Result += ".superclass = ";
6725 if (rootClass)
6726 Result += "&OBJC_CLASS_$_";
6727 else
6728 Result += "&OBJC_METACLASS_$_";
6729
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006730 Result += SuperClass->getNameAsString(); Result += ";\n";
6731
6732 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6733 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6734
6735 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6736 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6737 Result += CDecl->getNameAsString(); Result += ";\n";
6738
6739 if (!rootClass) {
6740 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6741 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6742 Result += SuperClass->getNameAsString(); Result += ";\n";
6743 }
6744
6745 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6746 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6747 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006748}
6749
Fariborz Jahanian61186122012-02-17 18:40:41 +00006750static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6751 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006752 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006753 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006754 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6755 ArrayRef<ObjCMethodDecl *> ClassMethods,
6756 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6757 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006758 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006759 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006760 // must declare an extern class object in case this class is not implemented
6761 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006762 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006763 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006764 if (ClassDecl->getImplementation())
6765 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006766 else
6767 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006768
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006769 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006770 Result += "OBJC_CLASS_$_"; Result += ClassName;
6771 Result += ";\n";
6772
Fariborz Jahanian61186122012-02-17 18:40:41 +00006773 Result += "\nstatic struct _category_t ";
6774 Result += "_OBJC_$_CATEGORY_";
6775 Result += ClassName; Result += "_$_"; Result += CatName;
6776 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6777 Result += "{\n";
6778 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006779 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006780 Result += ",\n";
6781 if (InstanceMethods.size() > 0) {
6782 Result += "\t(const struct _method_list_t *)&";
6783 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6784 Result += ClassName; Result += "_$_"; Result += CatName;
6785 Result += ",\n";
6786 }
6787 else
6788 Result += "\t0,\n";
6789
6790 if (ClassMethods.size() > 0) {
6791 Result += "\t(const struct _method_list_t *)&";
6792 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6793 Result += ClassName; Result += "_$_"; Result += CatName;
6794 Result += ",\n";
6795 }
6796 else
6797 Result += "\t0,\n";
6798
6799 if (RefedProtocols.size() > 0) {
6800 Result += "\t(const struct _protocol_list_t *)&";
6801 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6802 Result += ClassName; Result += "_$_"; Result += CatName;
6803 Result += ",\n";
6804 }
6805 else
6806 Result += "\t0,\n";
6807
6808 if (ClassProperties.size() > 0) {
6809 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6810 Result += ClassName; Result += "_$_"; Result += CatName;
6811 Result += ",\n";
6812 }
6813 else
6814 Result += "\t0,\n";
6815
6816 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006817
6818 // Add static function to initialize the class pointer in the category structure.
6819 Result += "static void OBJC_CATEGORY_SETUP_$_";
6820 Result += ClassDecl->getNameAsString();
6821 Result += "_$_";
6822 Result += CatName;
6823 Result += "(void ) {\n";
6824 Result += "\t_OBJC_$_CATEGORY_";
6825 Result += ClassDecl->getNameAsString();
6826 Result += "_$_";
6827 Result += CatName;
6828 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6829 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006830}
6831
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006832static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6833 ASTContext *Context, std::string &Result,
6834 ArrayRef<ObjCMethodDecl *> Methods,
6835 StringRef VarName,
6836 StringRef ProtocolName) {
6837 if (Methods.size() == 0)
6838 return;
6839
6840 Result += "\nstatic const char *";
6841 Result += VarName; Result += ProtocolName;
6842 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6843 Result += "{\n";
6844 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6845 ObjCMethodDecl *MD = Methods[i];
6846 std::string MethodTypeString, QuoteMethodTypeString;
6847 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6848 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6849 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6850 if (i == e-1)
6851 Result += "\n};\n";
6852 else {
6853 Result += ",\n";
6854 }
6855 }
6856}
6857
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006858static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6859 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006860 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006861 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006862 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006863 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6864 // this is what happens:
6865 /**
6866 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6867 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6868 Class->getVisibility() == HiddenVisibility)
6869 Visibility shoud be: HiddenVisibility;
6870 else
6871 Visibility shoud be: DefaultVisibility;
6872 */
6873
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006874 Result += "\n";
6875 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6876 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006877 if (Context->getLangOpts().MicrosoftExt)
6878 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6879
6880 if (!Context->getLangOpts().MicrosoftExt ||
6881 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006882 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006883 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006884 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006885 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006886 if (Ivars[i]->isBitField())
6887 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6888 else
6889 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006890 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6891 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006892 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6893 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006894 if (Ivars[i]->isBitField()) {
6895 // skip over rest of the ivar bitfields.
6896 SKIP_BITFIELDS(i , e, Ivars);
6897 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006898 }
6899}
6900
Fariborz Jahanianae932952012-02-10 20:47:10 +00006901static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6902 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006903 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006904 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006905 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006906 if (OriginalIvars.size() > 0) {
6907 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6908 SmallVector<ObjCIvarDecl *, 8> Ivars;
6909 // strip off all but the first ivar bitfield from each group of ivars.
6910 // Such ivars in the ivar list table will be replaced by their grouping struct
6911 // 'ivar'.
6912 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6913 if (OriginalIvars[i]->isBitField()) {
6914 Ivars.push_back(OriginalIvars[i]);
6915 // skip over rest of the ivar bitfields.
6916 SKIP_BITFIELDS(i , e, OriginalIvars);
6917 }
6918 else
6919 Ivars.push_back(OriginalIvars[i]);
6920 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006921
Fariborz Jahanianae932952012-02-10 20:47:10 +00006922 Result += "\nstatic ";
6923 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6924 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006925 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006926 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6927 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6928 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6929 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6930 ObjCIvarDecl *IvarDecl = Ivars[i];
6931 if (i == 0)
6932 Result += "\t{{";
6933 else
6934 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006935 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006936 if (Ivars[i]->isBitField())
6937 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6938 else
6939 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006940 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006941
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006942 Result += "\"";
6943 if (Ivars[i]->isBitField())
6944 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6945 else
6946 Result += IvarDecl->getName();
6947 Result += "\", ";
6948
6949 QualType IVQT = IvarDecl->getType();
6950 if (IvarDecl->isBitField())
6951 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6952
Fariborz Jahanianae932952012-02-10 20:47:10 +00006953 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006954 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006955 IvarDecl);
6956 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6957 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6958
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006959 // FIXME. this alignment represents the host alignment and need be changed to
6960 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006961 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006962 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006963 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006964 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006965 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006966 if (i == e-1)
6967 Result += "}}\n";
6968 else
6969 Result += "},\n";
6970 }
6971 Result += "};\n";
6972 }
6973}
6974
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006975/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006976void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6977 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006978
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006979 // Do not synthesize the protocol more than once.
6980 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6981 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006982 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006983
6984 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6985 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006986 // Must write out all protocol definitions in current qualifier list,
6987 // and in their nested qualifiers before writing out current definition.
Stephen Hines651f13c2014-04-23 16:59:28 -07006988 for (auto *I : PDecl->protocols())
6989 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006990
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006991 // Construct method lists.
6992 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6993 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Stephen Hines651f13c2014-04-23 16:59:28 -07006994 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006995 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6996 OptInstanceMethods.push_back(MD);
6997 } else {
6998 InstanceMethods.push_back(MD);
6999 }
7000 }
7001
Stephen Hines651f13c2014-04-23 16:59:28 -07007002 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007003 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7004 OptClassMethods.push_back(MD);
7005 } else {
7006 ClassMethods.push_back(MD);
7007 }
7008 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007009 std::vector<ObjCMethodDecl *> AllMethods;
7010 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7011 AllMethods.push_back(InstanceMethods[i]);
7012 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7013 AllMethods.push_back(ClassMethods[i]);
7014 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7015 AllMethods.push_back(OptInstanceMethods[i]);
7016 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7017 AllMethods.push_back(OptClassMethods[i]);
7018
7019 Write__extendedMethodTypes_initializer(*this, Context, Result,
7020 AllMethods,
7021 "_OBJC_PROTOCOL_METHOD_TYPES_",
7022 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007023 // Protocol's super protocol list
Stephen Hines651f13c2014-04-23 16:59:28 -07007024 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007025 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7026 "_OBJC_PROTOCOL_REFS_",
7027 PDecl->getNameAsString());
7028
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007029 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007030 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007031 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007032
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007033 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007034 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007035 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007036
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007037 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007038 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007039 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007040
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007041 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007042 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007043 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007044
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007045 // Protocol's property metadata.
Stephen Hines651f13c2014-04-23 16:59:28 -07007046 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007047 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007048 /* Container */nullptr,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007049 "_OBJC_PROTOCOL_PROPERTIES_",
7050 PDecl->getNameAsString());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007051
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007052 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007053 Result += "\n";
7054 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007055 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007056 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007057 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007058 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7059 Result += "\t0,\n"; // id is; is null
7060 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007061 if (SuperProtocols.size() > 0) {
7062 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7063 Result += PDecl->getNameAsString(); Result += ",\n";
7064 }
7065 else
7066 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007067 if (InstanceMethods.size() > 0) {
7068 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7069 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007070 }
7071 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007072 Result += "\t0,\n";
7073
7074 if (ClassMethods.size() > 0) {
7075 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7076 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007077 }
7078 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007079 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007080
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007081 if (OptInstanceMethods.size() > 0) {
7082 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7083 Result += PDecl->getNameAsString(); Result += ",\n";
7084 }
7085 else
7086 Result += "\t0,\n";
7087
7088 if (OptClassMethods.size() > 0) {
7089 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7090 Result += PDecl->getNameAsString(); Result += ",\n";
7091 }
7092 else
7093 Result += "\t0,\n";
7094
7095 if (ProtocolProperties.size() > 0) {
7096 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7097 Result += PDecl->getNameAsString(); Result += ",\n";
7098 }
7099 else
7100 Result += "\t0,\n";
7101
7102 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7103 Result += "\t0,\n";
7104
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007105 if (AllMethods.size() > 0) {
7106 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7107 Result += PDecl->getNameAsString();
7108 Result += "\n};\n";
7109 }
7110 else
7111 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007112
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007113 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007114 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007115 Result += "struct _protocol_t *";
7116 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7117 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7118 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007120 // Mark this protocol as having been generated.
7121 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7122 llvm_unreachable("protocol already synthesized");
7123
7124}
7125
7126void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7127 const ObjCList<ObjCProtocolDecl> &Protocols,
7128 StringRef prefix, StringRef ClassName,
7129 std::string &Result) {
7130 if (Protocols.empty()) return;
7131
7132 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007133 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134
7135 // Output the top lovel protocol meta-data for the class.
7136 /* struct _objc_protocol_list {
7137 struct _objc_protocol_list *next;
7138 int protocol_count;
7139 struct _objc_protocol *class_protocols[];
7140 }
7141 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007142 Result += "\n";
7143 if (LangOpts.MicrosoftExt)
7144 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7145 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007146 Result += "\tstruct _objc_protocol_list *next;\n";
7147 Result += "\tint protocol_count;\n";
7148 Result += "\tstruct _objc_protocol *class_protocols[";
7149 Result += utostr(Protocols.size());
7150 Result += "];\n} _OBJC_";
7151 Result += prefix;
7152 Result += "_PROTOCOLS_";
7153 Result += ClassName;
7154 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7155 "{\n\t0, ";
7156 Result += utostr(Protocols.size());
7157 Result += "\n";
7158
7159 Result += "\t,{&_OBJC_PROTOCOL_";
7160 Result += Protocols[0]->getNameAsString();
7161 Result += " \n";
7162
7163 for (unsigned i = 1; i != Protocols.size(); i++) {
7164 Result += "\t ,&_OBJC_PROTOCOL_";
7165 Result += Protocols[i]->getNameAsString();
7166 Result += "\n";
7167 }
7168 Result += "\t }\n};\n";
7169}
7170
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007171/// hasObjCExceptionAttribute - Return true if this class or any super
7172/// class has the __objc_exception__ attribute.
7173/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7174static bool hasObjCExceptionAttribute(ASTContext &Context,
7175 const ObjCInterfaceDecl *OID) {
7176 if (OID->hasAttr<ObjCExceptionAttr>())
7177 return true;
7178 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7179 return hasObjCExceptionAttribute(Context, Super);
7180 return false;
7181}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007182
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007183void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7184 std::string &Result) {
7185 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7186
7187 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007188 if (CDecl->isImplicitInterfaceDecl())
7189 assert(false &&
7190 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007191
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007192 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007193 SmallVector<ObjCIvarDecl *, 8> IVars;
7194
7195 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7196 IVD; IVD = IVD->getNextIvar()) {
7197 // Ignore unnamed bit-fields.
7198 if (!IVD->getDeclName())
7199 continue;
7200 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007201 }
7202
Fariborz Jahanianae932952012-02-10 20:47:10 +00007203 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007204 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007205 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007206
7207 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07007208 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007209
7210 // If any of our property implementations have associated getters or
7211 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07007212 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00007213 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007214 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007215 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007216 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007217 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007218 if (!PD)
7219 continue;
7220 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007221 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007222 InstanceMethods.push_back(Getter);
7223 if (PD->isReadOnly())
7224 continue;
7225 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007226 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007227 InstanceMethods.push_back(Setter);
7228 }
7229
7230 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7231 "_OBJC_$_INSTANCE_METHODS_",
7232 IDecl->getNameAsString(), true);
7233
Stephen Hines651f13c2014-04-23 16:59:28 -07007234 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007235
7236 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7237 "_OBJC_$_CLASS_METHODS_",
7238 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007239
7240 // Protocols referenced in class declaration?
7241 // Protocol's super protocol list
7242 std::vector<ObjCProtocolDecl *> RefedProtocols;
7243 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7244 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7245 E = Protocols.end();
7246 I != E; ++I) {
7247 RefedProtocols.push_back(*I);
7248 // Must write out all protocol definitions in current qualifier list,
7249 // and in their nested qualifiers before writing out current definition.
7250 RewriteObjCProtocolMetaData(*I, Result);
7251 }
7252
7253 Write_protocol_list_initializer(Context, Result,
7254 RefedProtocols,
7255 "_OBJC_CLASS_PROTOCOLS_$_",
7256 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007257
7258 // Protocol's property metadata.
Stephen Hines651f13c2014-04-23 16:59:28 -07007259 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007260 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007261 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007262 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007263 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007264
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007265
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007266 // Data for initializing _class_ro_t metaclass meta-data
7267 uint32_t flags = CLS_META;
7268 std::string InstanceSize;
7269 std::string InstanceStart;
7270
7271
7272 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7273 if (classIsHidden)
7274 flags |= OBJC2_CLS_HIDDEN;
7275
7276 if (!CDecl->getSuperClass())
7277 // class is root
7278 flags |= CLS_ROOT;
7279 InstanceSize = "sizeof(struct _class_t)";
7280 InstanceStart = InstanceSize;
7281 Write__class_ro_t_initializer(Context, Result, flags,
7282 InstanceStart, InstanceSize,
7283 ClassMethods,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007284 nullptr,
7285 nullptr,
7286 nullptr,
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007287 "_OBJC_METACLASS_RO_$_",
7288 CDecl->getNameAsString());
7289
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007290 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007291 flags = CLS;
7292 if (classIsHidden)
7293 flags |= OBJC2_CLS_HIDDEN;
7294
7295 if (hasObjCExceptionAttribute(*Context, CDecl))
7296 flags |= CLS_EXCEPTION;
7297
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007298 if (!CDecl->getSuperClass())
7299 // class is root
7300 flags |= CLS_ROOT;
7301
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007302 InstanceSize.clear();
7303 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007304 if (!ObjCSynthesizedStructs.count(CDecl)) {
7305 InstanceSize = "0";
7306 InstanceStart = "0";
7307 }
7308 else {
7309 InstanceSize = "sizeof(struct ";
7310 InstanceSize += CDecl->getNameAsString();
7311 InstanceSize += "_IMPL)";
7312
7313 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7314 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007315 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007316 }
7317 else
7318 InstanceStart = InstanceSize;
7319 }
7320 Write__class_ro_t_initializer(Context, Result, flags,
7321 InstanceStart, InstanceSize,
7322 InstanceMethods,
7323 RefedProtocols,
7324 IVars,
7325 ClassProperties,
7326 "_OBJC_CLASS_RO_$_",
7327 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007328
7329 Write_class_t(Context, Result,
7330 "OBJC_METACLASS_$_",
7331 CDecl, /*metaclass*/true);
7332
7333 Write_class_t(Context, Result,
7334 "OBJC_CLASS_$_",
7335 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007336
7337 if (ImplementationIsNonLazy(IDecl))
7338 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007339
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007340}
7341
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007342void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7343 int ClsDefCount = ClassImplementation.size();
7344 if (!ClsDefCount)
7345 return;
7346 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7347 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7348 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7349 for (int i = 0; i < ClsDefCount; i++) {
7350 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7351 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7352 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7353 Result += CDecl->getName(); Result += ",\n";
7354 }
7355 Result += "};\n";
7356}
7357
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007358void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7359 int ClsDefCount = ClassImplementation.size();
7360 int CatDefCount = CategoryImplementation.size();
7361
7362 // For each implemented class, write out all its meta data.
7363 for (int i = 0; i < ClsDefCount; i++)
7364 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7365
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007366 RewriteClassSetupInitHook(Result);
7367
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007368 // For each implemented category, write out all its meta data.
7369 for (int i = 0; i < CatDefCount; i++)
7370 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7371
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007372 RewriteCategorySetupInitHook(Result);
7373
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007374 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007375 if (LangOpts.MicrosoftExt)
7376 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007377 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7378 Result += llvm::utostr(ClsDefCount); Result += "]";
7379 Result +=
7380 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7381 "regular,no_dead_strip\")))= {\n";
7382 for (int i = 0; i < ClsDefCount; i++) {
7383 Result += "\t&OBJC_CLASS_$_";
7384 Result += ClassImplementation[i]->getNameAsString();
7385 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007386 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007387 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007388
7389 if (!DefinedNonLazyClasses.empty()) {
7390 if (LangOpts.MicrosoftExt)
7391 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7392 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7393 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7394 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7395 Result += ",\n";
7396 }
7397 Result += "};\n";
7398 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007399 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007400
7401 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007402 if (LangOpts.MicrosoftExt)
7403 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007404 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7405 Result += llvm::utostr(CatDefCount); Result += "]";
7406 Result +=
7407 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7408 "regular,no_dead_strip\")))= {\n";
7409 for (int i = 0; i < CatDefCount; i++) {
7410 Result += "\t&_OBJC_$_CATEGORY_";
7411 Result +=
7412 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7413 Result += "_$_";
7414 Result += CategoryImplementation[i]->getNameAsString();
7415 Result += ",\n";
7416 }
7417 Result += "};\n";
7418 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007419
7420 if (!DefinedNonLazyCategories.empty()) {
7421 if (LangOpts.MicrosoftExt)
7422 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7423 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7424 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7425 Result += "\t&_OBJC_$_CATEGORY_";
7426 Result +=
7427 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7428 Result += "_$_";
7429 Result += DefinedNonLazyCategories[i]->getNameAsString();
7430 Result += ",\n";
7431 }
7432 Result += "};\n";
7433 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007434}
7435
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007436void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7437 if (LangOpts.MicrosoftExt)
7438 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7439
7440 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7441 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007442 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007443}
7444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007445/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7446/// implementation.
7447void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7448 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007449 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007450 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7451 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007452 ObjCCategoryDecl *CDecl
7453 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007454
7455 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007456 FullCategoryName += "_$_";
7457 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007458
7459 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07007460 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007461
7462 // If any of our property implementations have associated getters or
7463 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07007464 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00007465 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007466 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007467 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007468 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007469 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007470 if (!PD)
7471 continue;
7472 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7473 InstanceMethods.push_back(Getter);
7474 if (PD->isReadOnly())
7475 continue;
7476 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7477 InstanceMethods.push_back(Setter);
7478 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007479
Fariborz Jahanian61186122012-02-17 18:40:41 +00007480 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7481 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7482 FullCategoryName, true);
7483
Stephen Hines651f13c2014-04-23 16:59:28 -07007484 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanian61186122012-02-17 18:40:41 +00007485
7486 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7487 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7488 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007489
7490 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007491 // Protocol's super protocol list
Stephen Hines651f13c2014-04-23 16:59:28 -07007492 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7493 for (auto *I : CDecl->protocols())
Fariborz Jahanian61186122012-02-17 18:40:41 +00007494 // Must write out all protocol definitions in current qualifier list,
7495 // and in their nested qualifiers before writing out current definition.
Stephen Hines651f13c2014-04-23 16:59:28 -07007496 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007497
Fariborz Jahanian61186122012-02-17 18:40:41 +00007498 Write_protocol_list_initializer(Context, Result,
7499 RefedProtocols,
7500 "_OBJC_CATEGORY_PROTOCOLS_$_",
7501 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007502
Fariborz Jahanian61186122012-02-17 18:40:41 +00007503 // Protocol's property metadata.
Stephen Hines651f13c2014-04-23 16:59:28 -07007504 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanian61186122012-02-17 18:40:41 +00007505 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007506 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007507 "_OBJC_$_PROP_LIST_",
7508 FullCategoryName);
7509
7510 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007511 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007512 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007513 InstanceMethods,
7514 ClassMethods,
7515 RefedProtocols,
7516 ClassProperties);
7517
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007518 // Determine if this category is also "non-lazy".
7519 if (ImplementationIsNonLazy(IDecl))
7520 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007521
7522}
7523
7524void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7525 int CatDefCount = CategoryImplementation.size();
7526 if (!CatDefCount)
7527 return;
7528 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7529 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7530 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7531 for (int i = 0; i < CatDefCount; i++) {
7532 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7533 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7534 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7535 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7536 Result += ClassDecl->getName();
7537 Result += "_$_";
7538 Result += CatDecl->getName();
7539 Result += ",\n";
7540 }
7541 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007542}
7543
7544// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7545/// class methods.
7546template<typename MethodIterator>
7547void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7548 MethodIterator MethodEnd,
7549 bool IsInstanceMethod,
7550 StringRef prefix,
7551 StringRef ClassName,
7552 std::string &Result) {
7553 if (MethodBegin == MethodEnd) return;
7554
7555 if (!objc_impl_method) {
7556 /* struct _objc_method {
7557 SEL _cmd;
7558 char *method_types;
7559 void *_imp;
7560 }
7561 */
7562 Result += "\nstruct _objc_method {\n";
7563 Result += "\tSEL _cmd;\n";
7564 Result += "\tchar *method_types;\n";
7565 Result += "\tvoid *_imp;\n";
7566 Result += "};\n";
7567
7568 objc_impl_method = true;
7569 }
7570
7571 // Build _objc_method_list for class's methods if needed
7572
7573 /* struct {
7574 struct _objc_method_list *next_method;
7575 int method_count;
7576 struct _objc_method method_list[];
7577 }
7578 */
7579 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007580 Result += "\n";
7581 if (LangOpts.MicrosoftExt) {
7582 if (IsInstanceMethod)
7583 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7584 else
7585 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7586 }
7587 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007588 Result += "\tstruct _objc_method_list *next_method;\n";
7589 Result += "\tint method_count;\n";
7590 Result += "\tstruct _objc_method method_list[";
7591 Result += utostr(NumMethods);
7592 Result += "];\n} _OBJC_";
7593 Result += prefix;
7594 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7595 Result += "_METHODS_";
7596 Result += ClassName;
7597 Result += " __attribute__ ((used, section (\"__OBJC, __";
7598 Result += IsInstanceMethod ? "inst" : "cls";
7599 Result += "_meth\")))= ";
7600 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7601
7602 Result += "\t,{{(SEL)\"";
7603 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7604 std::string MethodTypeString;
7605 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7606 Result += "\", \"";
7607 Result += MethodTypeString;
7608 Result += "\", (void *)";
7609 Result += MethodInternalNames[*MethodBegin];
7610 Result += "}\n";
7611 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7612 Result += "\t ,{(SEL)\"";
7613 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7614 std::string MethodTypeString;
7615 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7616 Result += "\", \"";
7617 Result += MethodTypeString;
7618 Result += "\", (void *)";
7619 Result += MethodInternalNames[*MethodBegin];
7620 Result += "}\n";
7621 }
7622 Result += "\t }\n};\n";
7623}
7624
7625Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7626 SourceRange OldRange = IV->getSourceRange();
7627 Expr *BaseExpr = IV->getBase();
7628
7629 // Rewrite the base, but without actually doing replaces.
7630 {
7631 DisableReplaceStmtScope S(*this);
7632 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7633 IV->setBase(BaseExpr);
7634 }
7635
7636 ObjCIvarDecl *D = IV->getDecl();
7637
7638 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007639
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007640 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7641 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007642 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007643 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7644 // lookup which class implements the instance variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007645 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007646 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7647 clsDeclared);
7648 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7649
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007650 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007651 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007652 if (D->isBitField())
7653 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7654 else
7655 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007656
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007657 ReferencedIvars[clsDeclared].insert(D);
7658
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007659 // cast offset to "char *".
7660 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7661 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007662 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007663 BaseExpr);
7664 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7665 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007666 Context->UnsignedLongTy, nullptr,
7667 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00007668 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7669 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007670 SourceLocation());
7671 BinaryOperator *addExpr =
7672 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7673 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007674 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007675 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007676 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7677 SourceLocation(),
7678 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007679 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007680 if (D->isBitField())
7681 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007682
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007683 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007684 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007685 RD = RD->getDefinition();
7686 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007687 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007688 ObjCContainerDecl *CDecl =
7689 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7690 // ivar in class extensions requires special treatment.
7691 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7692 CDecl = CatDecl->getClassInterface();
7693 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007694 RecName += "_IMPL";
7695 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7696 SourceLocation(), SourceLocation(),
7697 &Context->Idents.get(RecName.c_str()));
7698 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7699 unsigned UnsignedIntSize =
7700 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7701 Expr *Zero = IntegerLiteral::Create(*Context,
7702 llvm::APInt(UnsignedIntSize, 0),
7703 Context->UnsignedIntTy, SourceLocation());
7704 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7705 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7706 Zero);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007707 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007708 SourceLocation(),
7709 &Context->Idents.get(D->getNameAsString()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007710 IvarT, nullptr,
7711 /*BitWidth=*/nullptr,
7712 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007713 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7714 FD->getType(), VK_LValue,
7715 OK_Ordinary);
7716 IvarT = Context->getDecltypeType(ME, ME->getType());
7717 }
7718 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007719 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007720 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007721
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007722 castExpr = NoTypeInfoCStyleCastExpr(Context,
7723 castT,
7724 CK_BitCast,
7725 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007726
7727
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007728 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007729 VK_LValue, OK_Ordinary,
7730 SourceLocation());
7731 PE = new (Context) ParenExpr(OldRange.getBegin(),
7732 OldRange.getEnd(),
7733 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007734
7735 if (D->isBitField()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007736 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007737 SourceLocation(),
7738 &Context->Idents.get(D->getNameAsString()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007739 D->getType(), nullptr,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007740 /*BitWidth=*/D->getBitWidth(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007741 /*Mutable=*/true, ICIS_NoInit);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007742 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7743 FD->getType(), VK_LValue,
7744 OK_Ordinary);
7745 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007746
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007747 }
7748 else
7749 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007750 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007751
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007752 ReplaceStmtWithRange(IV, Replacement, OldRange);
7753 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007754}