xref: /minix3/external/bsd/llvm/dist/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1*0a6a1f1dSLionel Sambuc //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2*0a6a1f1dSLionel Sambuc //
3*0a6a1f1dSLionel Sambuc //                     The LLVM Compiler Infrastructure
4*0a6a1f1dSLionel Sambuc //
5*0a6a1f1dSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6*0a6a1f1dSLionel Sambuc // License. See LICENSE.TXT for details.
7*0a6a1f1dSLionel Sambuc //
8*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
9*0a6a1f1dSLionel Sambuc //
10*0a6a1f1dSLionel Sambuc // Hacks and fun related to the code rewriter.
11*0a6a1f1dSLionel Sambuc //
12*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
13*0a6a1f1dSLionel Sambuc 
14*0a6a1f1dSLionel Sambuc #include "clang/Rewrite/Frontend/ASTConsumers.h"
15*0a6a1f1dSLionel Sambuc #include "clang/AST/AST.h"
16*0a6a1f1dSLionel Sambuc #include "clang/AST/ASTConsumer.h"
17*0a6a1f1dSLionel Sambuc #include "clang/AST/Attr.h"
18*0a6a1f1dSLionel Sambuc #include "clang/AST/ParentMap.h"
19*0a6a1f1dSLionel Sambuc #include "clang/Basic/CharInfo.h"
20*0a6a1f1dSLionel Sambuc #include "clang/Basic/Diagnostic.h"
21*0a6a1f1dSLionel Sambuc #include "clang/Basic/IdentifierTable.h"
22*0a6a1f1dSLionel Sambuc #include "clang/Basic/SourceManager.h"
23*0a6a1f1dSLionel Sambuc #include "clang/Basic/TargetInfo.h"
24*0a6a1f1dSLionel Sambuc #include "clang/Lex/Lexer.h"
25*0a6a1f1dSLionel Sambuc #include "clang/Rewrite/Core/Rewriter.h"
26*0a6a1f1dSLionel Sambuc #include "llvm/ADT/DenseSet.h"
27*0a6a1f1dSLionel Sambuc #include "llvm/ADT/SmallPtrSet.h"
28*0a6a1f1dSLionel Sambuc #include "llvm/ADT/StringExtras.h"
29*0a6a1f1dSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
30*0a6a1f1dSLionel Sambuc #include "llvm/Support/raw_ostream.h"
31*0a6a1f1dSLionel Sambuc #include <memory>
32*0a6a1f1dSLionel Sambuc 
33*0a6a1f1dSLionel Sambuc #ifdef CLANG_ENABLE_OBJC_REWRITER
34*0a6a1f1dSLionel Sambuc 
35*0a6a1f1dSLionel Sambuc using namespace clang;
36*0a6a1f1dSLionel Sambuc using llvm::utostr;
37*0a6a1f1dSLionel Sambuc 
38*0a6a1f1dSLionel Sambuc namespace {
39*0a6a1f1dSLionel Sambuc   class RewriteModernObjC : public ASTConsumer {
40*0a6a1f1dSLionel Sambuc   protected:
41*0a6a1f1dSLionel Sambuc 
42*0a6a1f1dSLionel Sambuc     enum {
43*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
44*0a6a1f1dSLionel Sambuc                                         block, ... */
45*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
46*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
47*0a6a1f1dSLionel Sambuc                                         __block variable */
48*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
49*0a6a1f1dSLionel Sambuc                                         helpers */
50*0a6a1f1dSLionel Sambuc       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
51*0a6a1f1dSLionel Sambuc                                         support routines */
52*0a6a1f1dSLionel Sambuc       BLOCK_BYREF_CURRENT_MAX = 256
53*0a6a1f1dSLionel Sambuc     };
54*0a6a1f1dSLionel Sambuc 
55*0a6a1f1dSLionel Sambuc     enum {
56*0a6a1f1dSLionel Sambuc       BLOCK_NEEDS_FREE =        (1 << 24),
57*0a6a1f1dSLionel Sambuc       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
58*0a6a1f1dSLionel Sambuc       BLOCK_HAS_CXX_OBJ =       (1 << 26),
59*0a6a1f1dSLionel Sambuc       BLOCK_IS_GC =             (1 << 27),
60*0a6a1f1dSLionel Sambuc       BLOCK_IS_GLOBAL =         (1 << 28),
61*0a6a1f1dSLionel Sambuc       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
62*0a6a1f1dSLionel Sambuc     };
63*0a6a1f1dSLionel Sambuc 
64*0a6a1f1dSLionel Sambuc     Rewriter Rewrite;
65*0a6a1f1dSLionel Sambuc     DiagnosticsEngine &Diags;
66*0a6a1f1dSLionel Sambuc     const LangOptions &LangOpts;
67*0a6a1f1dSLionel Sambuc     ASTContext *Context;
68*0a6a1f1dSLionel Sambuc     SourceManager *SM;
69*0a6a1f1dSLionel Sambuc     TranslationUnitDecl *TUDecl;
70*0a6a1f1dSLionel Sambuc     FileID MainFileID;
71*0a6a1f1dSLionel Sambuc     const char *MainFileStart, *MainFileEnd;
72*0a6a1f1dSLionel Sambuc     Stmt *CurrentBody;
73*0a6a1f1dSLionel Sambuc     ParentMap *PropParentMap; // created lazily.
74*0a6a1f1dSLionel Sambuc     std::string InFileName;
75*0a6a1f1dSLionel Sambuc     raw_ostream* OutFile;
76*0a6a1f1dSLionel Sambuc     std::string Preamble;
77*0a6a1f1dSLionel Sambuc 
78*0a6a1f1dSLionel Sambuc     TypeDecl *ProtocolTypeDecl;
79*0a6a1f1dSLionel Sambuc     VarDecl *GlobalVarDecl;
80*0a6a1f1dSLionel Sambuc     Expr *GlobalConstructionExp;
81*0a6a1f1dSLionel Sambuc     unsigned RewriteFailedDiag;
82*0a6a1f1dSLionel Sambuc     unsigned GlobalBlockRewriteFailedDiag;
83*0a6a1f1dSLionel Sambuc     // ObjC string constant support.
84*0a6a1f1dSLionel Sambuc     unsigned NumObjCStringLiterals;
85*0a6a1f1dSLionel Sambuc     VarDecl *ConstantStringClassReference;
86*0a6a1f1dSLionel Sambuc     RecordDecl *NSStringRecord;
87*0a6a1f1dSLionel Sambuc 
88*0a6a1f1dSLionel Sambuc     // ObjC foreach break/continue generation support.
89*0a6a1f1dSLionel Sambuc     int BcLabelCount;
90*0a6a1f1dSLionel Sambuc 
91*0a6a1f1dSLionel Sambuc     unsigned TryFinallyContainsReturnDiag;
92*0a6a1f1dSLionel Sambuc     // Needed for super.
93*0a6a1f1dSLionel Sambuc     ObjCMethodDecl *CurMethodDef;
94*0a6a1f1dSLionel Sambuc     RecordDecl *SuperStructDecl;
95*0a6a1f1dSLionel Sambuc     RecordDecl *ConstantStringDecl;
96*0a6a1f1dSLionel Sambuc 
97*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendFunctionDecl;
98*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendSuperFunctionDecl;
99*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendStretFunctionDecl;
100*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendSuperStretFunctionDecl;
101*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendFpretFunctionDecl;
102*0a6a1f1dSLionel Sambuc     FunctionDecl *GetClassFunctionDecl;
103*0a6a1f1dSLionel Sambuc     FunctionDecl *GetMetaClassFunctionDecl;
104*0a6a1f1dSLionel Sambuc     FunctionDecl *GetSuperClassFunctionDecl;
105*0a6a1f1dSLionel Sambuc     FunctionDecl *SelGetUidFunctionDecl;
106*0a6a1f1dSLionel Sambuc     FunctionDecl *CFStringFunctionDecl;
107*0a6a1f1dSLionel Sambuc     FunctionDecl *SuperConstructorFunctionDecl;
108*0a6a1f1dSLionel Sambuc     FunctionDecl *CurFunctionDef;
109*0a6a1f1dSLionel Sambuc 
110*0a6a1f1dSLionel Sambuc     /* Misc. containers needed for meta-data rewrite. */
111*0a6a1f1dSLionel Sambuc     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112*0a6a1f1dSLionel Sambuc     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117*0a6a1f1dSLionel Sambuc     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118*0a6a1f1dSLionel Sambuc     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119*0a6a1f1dSLionel Sambuc     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120*0a6a1f1dSLionel Sambuc 
121*0a6a1f1dSLionel Sambuc     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122*0a6a1f1dSLionel Sambuc     SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123*0a6a1f1dSLionel Sambuc 
124*0a6a1f1dSLionel Sambuc     SmallVector<Stmt *, 32> Stmts;
125*0a6a1f1dSLionel Sambuc     SmallVector<int, 8> ObjCBcLabelNo;
126*0a6a1f1dSLionel Sambuc     // Remember all the @protocol(<expr>) expressions.
127*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128*0a6a1f1dSLionel Sambuc 
129*0a6a1f1dSLionel Sambuc     llvm::DenseSet<uint64_t> CopyDestroyCache;
130*0a6a1f1dSLionel Sambuc 
131*0a6a1f1dSLionel Sambuc     // Block expressions.
132*0a6a1f1dSLionel Sambuc     SmallVector<BlockExpr *, 32> Blocks;
133*0a6a1f1dSLionel Sambuc     SmallVector<int, 32> InnerDeclRefsCount;
134*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135*0a6a1f1dSLionel Sambuc 
136*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137*0a6a1f1dSLionel Sambuc 
138*0a6a1f1dSLionel Sambuc 
139*0a6a1f1dSLionel Sambuc     // Block related declarations.
140*0a6a1f1dSLionel Sambuc     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142*0a6a1f1dSLionel Sambuc     SmallVector<ValueDecl *, 8> BlockByRefDecls;
143*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144*0a6a1f1dSLionel Sambuc     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
147*0a6a1f1dSLionel Sambuc 
148*0a6a1f1dSLionel Sambuc     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
149*0a6a1f1dSLionel Sambuc     llvm::DenseMap<ObjCInterfaceDecl *,
150*0a6a1f1dSLionel Sambuc                     llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
151*0a6a1f1dSLionel Sambuc 
152*0a6a1f1dSLionel Sambuc     // ivar bitfield grouping containers
153*0a6a1f1dSLionel Sambuc     llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154*0a6a1f1dSLionel Sambuc     llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155*0a6a1f1dSLionel Sambuc     // This container maps an <class, group number for ivar> tuple to the type
156*0a6a1f1dSLionel Sambuc     // of the struct where the bitfield belongs.
157*0a6a1f1dSLionel Sambuc     llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
158*0a6a1f1dSLionel Sambuc     SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
159*0a6a1f1dSLionel Sambuc 
160*0a6a1f1dSLionel Sambuc     // This maps an original source AST to it's rewritten form. This allows
161*0a6a1f1dSLionel Sambuc     // us to avoid rewriting the same node twice (which is very uncommon).
162*0a6a1f1dSLionel Sambuc     // This is needed to support some of the exotic property rewriting.
163*0a6a1f1dSLionel Sambuc     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
164*0a6a1f1dSLionel Sambuc 
165*0a6a1f1dSLionel Sambuc     // Needed for header files being rewritten
166*0a6a1f1dSLionel Sambuc     bool IsHeader;
167*0a6a1f1dSLionel Sambuc     bool SilenceRewriteMacroWarning;
168*0a6a1f1dSLionel Sambuc     bool GenerateLineInfo;
169*0a6a1f1dSLionel Sambuc     bool objc_impl_method;
170*0a6a1f1dSLionel Sambuc 
171*0a6a1f1dSLionel Sambuc     bool DisableReplaceStmt;
172*0a6a1f1dSLionel Sambuc     class DisableReplaceStmtScope {
173*0a6a1f1dSLionel Sambuc       RewriteModernObjC &R;
174*0a6a1f1dSLionel Sambuc       bool SavedValue;
175*0a6a1f1dSLionel Sambuc 
176*0a6a1f1dSLionel Sambuc     public:
DisableReplaceStmtScope(RewriteModernObjC & R)177*0a6a1f1dSLionel Sambuc       DisableReplaceStmtScope(RewriteModernObjC &R)
178*0a6a1f1dSLionel Sambuc         : R(R), SavedValue(R.DisableReplaceStmt) {
179*0a6a1f1dSLionel Sambuc         R.DisableReplaceStmt = true;
180*0a6a1f1dSLionel Sambuc       }
~DisableReplaceStmtScope()181*0a6a1f1dSLionel Sambuc       ~DisableReplaceStmtScope() {
182*0a6a1f1dSLionel Sambuc         R.DisableReplaceStmt = SavedValue;
183*0a6a1f1dSLionel Sambuc       }
184*0a6a1f1dSLionel Sambuc     };
185*0a6a1f1dSLionel Sambuc     void InitializeCommon(ASTContext &context);
186*0a6a1f1dSLionel Sambuc 
187*0a6a1f1dSLionel Sambuc   public:
188*0a6a1f1dSLionel Sambuc     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
189*0a6a1f1dSLionel Sambuc     // Top Level Driver code.
HandleTopLevelDecl(DeclGroupRef D)190*0a6a1f1dSLionel Sambuc     bool HandleTopLevelDecl(DeclGroupRef D) override {
191*0a6a1f1dSLionel Sambuc       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192*0a6a1f1dSLionel Sambuc         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193*0a6a1f1dSLionel Sambuc           if (!Class->isThisDeclarationADefinition()) {
194*0a6a1f1dSLionel Sambuc             RewriteForwardClassDecl(D);
195*0a6a1f1dSLionel Sambuc             break;
196*0a6a1f1dSLionel Sambuc           } else {
197*0a6a1f1dSLionel Sambuc             // Keep track of all interface declarations seen.
198*0a6a1f1dSLionel Sambuc             ObjCInterfacesSeen.push_back(Class);
199*0a6a1f1dSLionel Sambuc             break;
200*0a6a1f1dSLionel Sambuc           }
201*0a6a1f1dSLionel Sambuc         }
202*0a6a1f1dSLionel Sambuc 
203*0a6a1f1dSLionel Sambuc         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204*0a6a1f1dSLionel Sambuc           if (!Proto->isThisDeclarationADefinition()) {
205*0a6a1f1dSLionel Sambuc             RewriteForwardProtocolDecl(D);
206*0a6a1f1dSLionel Sambuc             break;
207*0a6a1f1dSLionel Sambuc           }
208*0a6a1f1dSLionel Sambuc         }
209*0a6a1f1dSLionel Sambuc 
210*0a6a1f1dSLionel Sambuc         if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211*0a6a1f1dSLionel Sambuc           // Under modern abi, we cannot translate body of the function
212*0a6a1f1dSLionel Sambuc           // yet until all class extensions and its implementation is seen.
213*0a6a1f1dSLionel Sambuc           // This is because they may introduce new bitfields which must go
214*0a6a1f1dSLionel Sambuc           // into their grouping struct.
215*0a6a1f1dSLionel Sambuc           if (FDecl->isThisDeclarationADefinition() &&
216*0a6a1f1dSLionel Sambuc               // Not c functions defined inside an objc container.
217*0a6a1f1dSLionel Sambuc               !FDecl->isTopLevelDeclInObjCContainer()) {
218*0a6a1f1dSLionel Sambuc             FunctionDefinitionsSeen.push_back(FDecl);
219*0a6a1f1dSLionel Sambuc             break;
220*0a6a1f1dSLionel Sambuc           }
221*0a6a1f1dSLionel Sambuc         }
222*0a6a1f1dSLionel Sambuc         HandleTopLevelSingleDecl(*I);
223*0a6a1f1dSLionel Sambuc       }
224*0a6a1f1dSLionel Sambuc       return true;
225*0a6a1f1dSLionel Sambuc     }
226*0a6a1f1dSLionel Sambuc 
HandleTopLevelDeclInObjCContainer(DeclGroupRef D)227*0a6a1f1dSLionel Sambuc     void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228*0a6a1f1dSLionel Sambuc       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229*0a6a1f1dSLionel Sambuc         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230*0a6a1f1dSLionel Sambuc           if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231*0a6a1f1dSLionel Sambuc             RewriteBlockPointerDecl(TD);
232*0a6a1f1dSLionel Sambuc           else if (TD->getUnderlyingType()->isFunctionPointerType())
233*0a6a1f1dSLionel Sambuc             CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234*0a6a1f1dSLionel Sambuc           else
235*0a6a1f1dSLionel Sambuc             RewriteObjCQualifiedInterfaceTypes(TD);
236*0a6a1f1dSLionel Sambuc         }
237*0a6a1f1dSLionel Sambuc       }
238*0a6a1f1dSLionel Sambuc       return;
239*0a6a1f1dSLionel Sambuc     }
240*0a6a1f1dSLionel Sambuc 
241*0a6a1f1dSLionel Sambuc     void HandleTopLevelSingleDecl(Decl *D);
242*0a6a1f1dSLionel Sambuc     void HandleDeclInMainFile(Decl *D);
243*0a6a1f1dSLionel Sambuc     RewriteModernObjC(std::string inFile, raw_ostream *OS,
244*0a6a1f1dSLionel Sambuc                 DiagnosticsEngine &D, const LangOptions &LOpts,
245*0a6a1f1dSLionel Sambuc                 bool silenceMacroWarn, bool LineInfo);
246*0a6a1f1dSLionel Sambuc 
~RewriteModernObjC()247*0a6a1f1dSLionel Sambuc     ~RewriteModernObjC() {}
248*0a6a1f1dSLionel Sambuc 
249*0a6a1f1dSLionel Sambuc     void HandleTranslationUnit(ASTContext &C) override;
250*0a6a1f1dSLionel Sambuc 
ReplaceStmt(Stmt * Old,Stmt * New)251*0a6a1f1dSLionel Sambuc     void ReplaceStmt(Stmt *Old, Stmt *New) {
252*0a6a1f1dSLionel Sambuc       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
253*0a6a1f1dSLionel Sambuc     }
254*0a6a1f1dSLionel Sambuc 
ReplaceStmtWithRange(Stmt * Old,Stmt * New,SourceRange SrcRange)255*0a6a1f1dSLionel Sambuc     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256*0a6a1f1dSLionel Sambuc       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
257*0a6a1f1dSLionel Sambuc 
258*0a6a1f1dSLionel Sambuc       Stmt *ReplacingStmt = ReplacedNodes[Old];
259*0a6a1f1dSLionel Sambuc       if (ReplacingStmt)
260*0a6a1f1dSLionel Sambuc         return; // We can't rewrite the same node twice.
261*0a6a1f1dSLionel Sambuc 
262*0a6a1f1dSLionel Sambuc       if (DisableReplaceStmt)
263*0a6a1f1dSLionel Sambuc         return;
264*0a6a1f1dSLionel Sambuc 
265*0a6a1f1dSLionel Sambuc       // Measure the old text.
266*0a6a1f1dSLionel Sambuc       int Size = Rewrite.getRangeSize(SrcRange);
267*0a6a1f1dSLionel Sambuc       if (Size == -1) {
268*0a6a1f1dSLionel Sambuc         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
269*0a6a1f1dSLionel Sambuc                      << Old->getSourceRange();
270*0a6a1f1dSLionel Sambuc         return;
271*0a6a1f1dSLionel Sambuc       }
272*0a6a1f1dSLionel Sambuc       // Get the new text.
273*0a6a1f1dSLionel Sambuc       std::string SStr;
274*0a6a1f1dSLionel Sambuc       llvm::raw_string_ostream S(SStr);
275*0a6a1f1dSLionel Sambuc       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
276*0a6a1f1dSLionel Sambuc       const std::string &Str = S.str();
277*0a6a1f1dSLionel Sambuc 
278*0a6a1f1dSLionel Sambuc       // If replacement succeeded or warning disabled return with no warning.
279*0a6a1f1dSLionel Sambuc       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280*0a6a1f1dSLionel Sambuc         ReplacedNodes[Old] = New;
281*0a6a1f1dSLionel Sambuc         return;
282*0a6a1f1dSLionel Sambuc       }
283*0a6a1f1dSLionel Sambuc       if (SilenceRewriteMacroWarning)
284*0a6a1f1dSLionel Sambuc         return;
285*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
286*0a6a1f1dSLionel Sambuc                    << Old->getSourceRange();
287*0a6a1f1dSLionel Sambuc     }
288*0a6a1f1dSLionel Sambuc 
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter=true)289*0a6a1f1dSLionel Sambuc     void InsertText(SourceLocation Loc, StringRef Str,
290*0a6a1f1dSLionel Sambuc                     bool InsertAfter = true) {
291*0a6a1f1dSLionel Sambuc       // If insertion succeeded or warning disabled return with no warning.
292*0a6a1f1dSLionel Sambuc       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293*0a6a1f1dSLionel Sambuc           SilenceRewriteMacroWarning)
294*0a6a1f1dSLionel Sambuc         return;
295*0a6a1f1dSLionel Sambuc 
296*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
297*0a6a1f1dSLionel Sambuc     }
298*0a6a1f1dSLionel Sambuc 
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef Str)299*0a6a1f1dSLionel Sambuc     void ReplaceText(SourceLocation Start, unsigned OrigLength,
300*0a6a1f1dSLionel Sambuc                      StringRef Str) {
301*0a6a1f1dSLionel Sambuc       // If removal succeeded or warning disabled return with no warning.
302*0a6a1f1dSLionel Sambuc       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303*0a6a1f1dSLionel Sambuc           SilenceRewriteMacroWarning)
304*0a6a1f1dSLionel Sambuc         return;
305*0a6a1f1dSLionel Sambuc 
306*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
307*0a6a1f1dSLionel Sambuc     }
308*0a6a1f1dSLionel Sambuc 
309*0a6a1f1dSLionel Sambuc     // Syntactic Rewriting.
310*0a6a1f1dSLionel Sambuc     void RewriteRecordBody(RecordDecl *RD);
311*0a6a1f1dSLionel Sambuc     void RewriteInclude();
312*0a6a1f1dSLionel Sambuc     void RewriteLineDirective(const Decl *D);
313*0a6a1f1dSLionel Sambuc     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314*0a6a1f1dSLionel Sambuc                                               std::string &LineString);
315*0a6a1f1dSLionel Sambuc     void RewriteForwardClassDecl(DeclGroupRef D);
316*0a6a1f1dSLionel Sambuc     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
317*0a6a1f1dSLionel Sambuc     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318*0a6a1f1dSLionel Sambuc                                      const std::string &typedefString);
319*0a6a1f1dSLionel Sambuc     void RewriteImplementations();
320*0a6a1f1dSLionel Sambuc     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321*0a6a1f1dSLionel Sambuc                                  ObjCImplementationDecl *IMD,
322*0a6a1f1dSLionel Sambuc                                  ObjCCategoryImplDecl *CID);
323*0a6a1f1dSLionel Sambuc     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324*0a6a1f1dSLionel Sambuc     void RewriteImplementationDecl(Decl *Dcl);
325*0a6a1f1dSLionel Sambuc     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326*0a6a1f1dSLionel Sambuc                                ObjCMethodDecl *MDecl, std::string &ResultStr);
327*0a6a1f1dSLionel Sambuc     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328*0a6a1f1dSLionel Sambuc                                const FunctionType *&FPRetType);
329*0a6a1f1dSLionel Sambuc     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330*0a6a1f1dSLionel Sambuc                             ValueDecl *VD, bool def=false);
331*0a6a1f1dSLionel Sambuc     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332*0a6a1f1dSLionel Sambuc     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333*0a6a1f1dSLionel Sambuc     void RewriteForwardProtocolDecl(DeclGroupRef D);
334*0a6a1f1dSLionel Sambuc     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
335*0a6a1f1dSLionel Sambuc     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336*0a6a1f1dSLionel Sambuc     void RewriteProperty(ObjCPropertyDecl *prop);
337*0a6a1f1dSLionel Sambuc     void RewriteFunctionDecl(FunctionDecl *FD);
338*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerType(std::string& Str, QualType Type);
339*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
340*0a6a1f1dSLionel Sambuc     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
341*0a6a1f1dSLionel Sambuc     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342*0a6a1f1dSLionel Sambuc     void RewriteTypeOfDecl(VarDecl *VD);
343*0a6a1f1dSLionel Sambuc     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
344*0a6a1f1dSLionel Sambuc 
345*0a6a1f1dSLionel Sambuc     std::string getIvarAccessString(ObjCIvarDecl *D);
346*0a6a1f1dSLionel Sambuc 
347*0a6a1f1dSLionel Sambuc     // Expression Rewriting.
348*0a6a1f1dSLionel Sambuc     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349*0a6a1f1dSLionel Sambuc     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350*0a6a1f1dSLionel Sambuc     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351*0a6a1f1dSLionel Sambuc     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352*0a6a1f1dSLionel Sambuc     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353*0a6a1f1dSLionel Sambuc     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
355*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
356*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
357*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
358*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
359*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
360*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
361*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
362*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365*0a6a1f1dSLionel Sambuc                                        SourceLocation OrigEnd);
366*0a6a1f1dSLionel Sambuc     Stmt *RewriteBreakStmt(BreakStmt *S);
367*0a6a1f1dSLionel Sambuc     Stmt *RewriteContinueStmt(ContinueStmt *S);
368*0a6a1f1dSLionel Sambuc     void RewriteCastExpr(CStyleCastExpr *CE);
369*0a6a1f1dSLionel Sambuc     void RewriteImplicitCastObjCExpr(CastExpr *IE);
370*0a6a1f1dSLionel Sambuc     void RewriteLinkageSpec(LinkageSpecDecl *LSD);
371*0a6a1f1dSLionel Sambuc 
372*0a6a1f1dSLionel Sambuc     // Computes ivar bitfield group no.
373*0a6a1f1dSLionel Sambuc     unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
374*0a6a1f1dSLionel Sambuc     // Names field decl. for ivar bitfield group.
375*0a6a1f1dSLionel Sambuc     void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
376*0a6a1f1dSLionel Sambuc     // Names struct type for ivar bitfield group.
377*0a6a1f1dSLionel Sambuc     void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
378*0a6a1f1dSLionel Sambuc     // Names symbol for ivar bitfield group field offset.
379*0a6a1f1dSLionel Sambuc     void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
380*0a6a1f1dSLionel Sambuc     // Given an ivar bitfield, it builds (or finds) its group record type.
381*0a6a1f1dSLionel Sambuc     QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
382*0a6a1f1dSLionel Sambuc     QualType SynthesizeBitfieldGroupStructType(
383*0a6a1f1dSLionel Sambuc                                     ObjCIvarDecl *IV,
384*0a6a1f1dSLionel Sambuc                                     SmallVectorImpl<ObjCIvarDecl *> &IVars);
385*0a6a1f1dSLionel Sambuc 
386*0a6a1f1dSLionel Sambuc     // Block rewriting.
387*0a6a1f1dSLionel Sambuc     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
388*0a6a1f1dSLionel Sambuc 
389*0a6a1f1dSLionel Sambuc     // Block specific rewrite rules.
390*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerDecl(NamedDecl *VD);
391*0a6a1f1dSLionel Sambuc     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
392*0a6a1f1dSLionel Sambuc     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
393*0a6a1f1dSLionel Sambuc     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
394*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
395*0a6a1f1dSLionel Sambuc 
396*0a6a1f1dSLionel Sambuc     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
397*0a6a1f1dSLionel Sambuc                                       std::string &Result);
398*0a6a1f1dSLionel Sambuc 
399*0a6a1f1dSLionel Sambuc     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
400*0a6a1f1dSLionel Sambuc     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
401*0a6a1f1dSLionel Sambuc                                  bool &IsNamedDefinition);
402*0a6a1f1dSLionel Sambuc     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
403*0a6a1f1dSLionel Sambuc                                               std::string &Result);
404*0a6a1f1dSLionel Sambuc 
405*0a6a1f1dSLionel Sambuc     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
406*0a6a1f1dSLionel Sambuc 
407*0a6a1f1dSLionel Sambuc     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
408*0a6a1f1dSLionel Sambuc                                   std::string &Result);
409*0a6a1f1dSLionel Sambuc 
410*0a6a1f1dSLionel Sambuc     void Initialize(ASTContext &context) override;
411*0a6a1f1dSLionel Sambuc 
412*0a6a1f1dSLionel Sambuc     // Misc. AST transformation routines. Sometimes they end up calling
413*0a6a1f1dSLionel Sambuc     // rewriting routines on the new ASTs.
414*0a6a1f1dSLionel Sambuc     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
415*0a6a1f1dSLionel Sambuc                                            Expr **args, unsigned nargs,
416*0a6a1f1dSLionel Sambuc                                            SourceLocation StartLoc=SourceLocation(),
417*0a6a1f1dSLionel Sambuc                                            SourceLocation EndLoc=SourceLocation());
418*0a6a1f1dSLionel Sambuc 
419*0a6a1f1dSLionel Sambuc     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
420*0a6a1f1dSLionel Sambuc                                         QualType returnType,
421*0a6a1f1dSLionel Sambuc                                         SmallVectorImpl<QualType> &ArgTypes,
422*0a6a1f1dSLionel Sambuc                                         SmallVectorImpl<Expr*> &MsgExprs,
423*0a6a1f1dSLionel Sambuc                                         ObjCMethodDecl *Method);
424*0a6a1f1dSLionel Sambuc 
425*0a6a1f1dSLionel Sambuc     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
426*0a6a1f1dSLionel Sambuc                            SourceLocation StartLoc=SourceLocation(),
427*0a6a1f1dSLionel Sambuc                            SourceLocation EndLoc=SourceLocation());
428*0a6a1f1dSLionel Sambuc 
429*0a6a1f1dSLionel Sambuc     void SynthCountByEnumWithState(std::string &buf);
430*0a6a1f1dSLionel Sambuc     void SynthMsgSendFunctionDecl();
431*0a6a1f1dSLionel Sambuc     void SynthMsgSendSuperFunctionDecl();
432*0a6a1f1dSLionel Sambuc     void SynthMsgSendStretFunctionDecl();
433*0a6a1f1dSLionel Sambuc     void SynthMsgSendFpretFunctionDecl();
434*0a6a1f1dSLionel Sambuc     void SynthMsgSendSuperStretFunctionDecl();
435*0a6a1f1dSLionel Sambuc     void SynthGetClassFunctionDecl();
436*0a6a1f1dSLionel Sambuc     void SynthGetMetaClassFunctionDecl();
437*0a6a1f1dSLionel Sambuc     void SynthGetSuperClassFunctionDecl();
438*0a6a1f1dSLionel Sambuc     void SynthSelGetUidFunctionDecl();
439*0a6a1f1dSLionel Sambuc     void SynthSuperConstructorFunctionDecl();
440*0a6a1f1dSLionel Sambuc 
441*0a6a1f1dSLionel Sambuc     // Rewriting metadata
442*0a6a1f1dSLionel Sambuc     template<typename MethodIterator>
443*0a6a1f1dSLionel Sambuc     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
444*0a6a1f1dSLionel Sambuc                                     MethodIterator MethodEnd,
445*0a6a1f1dSLionel Sambuc                                     bool IsInstanceMethod,
446*0a6a1f1dSLionel Sambuc                                     StringRef prefix,
447*0a6a1f1dSLionel Sambuc                                     StringRef ClassName,
448*0a6a1f1dSLionel Sambuc                                     std::string &Result);
449*0a6a1f1dSLionel Sambuc     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
450*0a6a1f1dSLionel Sambuc                                      std::string &Result);
451*0a6a1f1dSLionel Sambuc     void RewriteObjCProtocolListMetaData(
452*0a6a1f1dSLionel Sambuc                    const ObjCList<ObjCProtocolDecl> &Prots,
453*0a6a1f1dSLionel Sambuc                    StringRef prefix, StringRef ClassName, std::string &Result);
454*0a6a1f1dSLionel Sambuc     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
455*0a6a1f1dSLionel Sambuc                                           std::string &Result);
456*0a6a1f1dSLionel Sambuc     void RewriteClassSetupInitHook(std::string &Result);
457*0a6a1f1dSLionel Sambuc 
458*0a6a1f1dSLionel Sambuc     void RewriteMetaDataIntoBuffer(std::string &Result);
459*0a6a1f1dSLionel Sambuc     void WriteImageInfo(std::string &Result);
460*0a6a1f1dSLionel Sambuc     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
461*0a6a1f1dSLionel Sambuc                                              std::string &Result);
462*0a6a1f1dSLionel Sambuc     void RewriteCategorySetupInitHook(std::string &Result);
463*0a6a1f1dSLionel Sambuc 
464*0a6a1f1dSLionel Sambuc     // Rewriting ivar
465*0a6a1f1dSLionel Sambuc     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
466*0a6a1f1dSLionel Sambuc                                               std::string &Result);
467*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
468*0a6a1f1dSLionel Sambuc 
469*0a6a1f1dSLionel Sambuc 
470*0a6a1f1dSLionel Sambuc     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
471*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
472*0a6a1f1dSLionel Sambuc                                       StringRef funcName, std::string Tag);
473*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
474*0a6a1f1dSLionel Sambuc                                       StringRef funcName, std::string Tag);
475*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockImpl(BlockExpr *CE,
476*0a6a1f1dSLionel Sambuc                                     std::string Tag, std::string Desc);
477*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockDescriptor(std::string DescTag,
478*0a6a1f1dSLionel Sambuc                                           std::string ImplTag,
479*0a6a1f1dSLionel Sambuc                                           int i, StringRef funcName,
480*0a6a1f1dSLionel Sambuc                                           unsigned hasCopy);
481*0a6a1f1dSLionel Sambuc     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
482*0a6a1f1dSLionel Sambuc     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
483*0a6a1f1dSLionel Sambuc                                  StringRef FunName);
484*0a6a1f1dSLionel Sambuc     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
485*0a6a1f1dSLionel Sambuc     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
486*0a6a1f1dSLionel Sambuc                       const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
487*0a6a1f1dSLionel Sambuc 
488*0a6a1f1dSLionel Sambuc     // Misc. helper routines.
489*0a6a1f1dSLionel Sambuc     QualType getProtocolType();
490*0a6a1f1dSLionel Sambuc     void WarnAboutReturnGotoStmts(Stmt *S);
491*0a6a1f1dSLionel Sambuc     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
492*0a6a1f1dSLionel Sambuc     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
493*0a6a1f1dSLionel Sambuc     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
494*0a6a1f1dSLionel Sambuc 
495*0a6a1f1dSLionel Sambuc     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
496*0a6a1f1dSLionel Sambuc     void CollectBlockDeclRefInfo(BlockExpr *Exp);
497*0a6a1f1dSLionel Sambuc     void GetBlockDeclRefExprs(Stmt *S);
498*0a6a1f1dSLionel Sambuc     void GetInnerBlockDeclRefExprs(Stmt *S,
499*0a6a1f1dSLionel Sambuc                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
500*0a6a1f1dSLionel Sambuc                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
501*0a6a1f1dSLionel Sambuc 
502*0a6a1f1dSLionel Sambuc     // We avoid calling Type::isBlockPointerType(), since it operates on the
503*0a6a1f1dSLionel Sambuc     // canonical type. We only care if the top-level type is a closure pointer.
isTopLevelBlockPointerType(QualType T)504*0a6a1f1dSLionel Sambuc     bool isTopLevelBlockPointerType(QualType T) {
505*0a6a1f1dSLionel Sambuc       return isa<BlockPointerType>(T);
506*0a6a1f1dSLionel Sambuc     }
507*0a6a1f1dSLionel Sambuc 
508*0a6a1f1dSLionel Sambuc     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
509*0a6a1f1dSLionel Sambuc     /// to a function pointer type and upon success, returns true; false
510*0a6a1f1dSLionel Sambuc     /// otherwise.
convertBlockPointerToFunctionPointer(QualType & T)511*0a6a1f1dSLionel Sambuc     bool convertBlockPointerToFunctionPointer(QualType &T) {
512*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(T)) {
513*0a6a1f1dSLionel Sambuc         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
514*0a6a1f1dSLionel Sambuc         T = Context->getPointerType(BPT->getPointeeType());
515*0a6a1f1dSLionel Sambuc         return true;
516*0a6a1f1dSLionel Sambuc       }
517*0a6a1f1dSLionel Sambuc       return false;
518*0a6a1f1dSLionel Sambuc     }
519*0a6a1f1dSLionel Sambuc 
520*0a6a1f1dSLionel Sambuc     bool convertObjCTypeToCStyleType(QualType &T);
521*0a6a1f1dSLionel Sambuc 
522*0a6a1f1dSLionel Sambuc     bool needToScanForQualifiers(QualType T);
523*0a6a1f1dSLionel Sambuc     QualType getSuperStructType();
524*0a6a1f1dSLionel Sambuc     QualType getConstantStringStructType();
525*0a6a1f1dSLionel Sambuc     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
526*0a6a1f1dSLionel Sambuc     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
527*0a6a1f1dSLionel Sambuc 
convertToUnqualifiedObjCType(QualType & T)528*0a6a1f1dSLionel Sambuc     void convertToUnqualifiedObjCType(QualType &T) {
529*0a6a1f1dSLionel Sambuc       if (T->isObjCQualifiedIdType()) {
530*0a6a1f1dSLionel Sambuc         bool isConst = T.isConstQualified();
531*0a6a1f1dSLionel Sambuc         T = isConst ? Context->getObjCIdType().withConst()
532*0a6a1f1dSLionel Sambuc                     : Context->getObjCIdType();
533*0a6a1f1dSLionel Sambuc       }
534*0a6a1f1dSLionel Sambuc       else if (T->isObjCQualifiedClassType())
535*0a6a1f1dSLionel Sambuc         T = Context->getObjCClassType();
536*0a6a1f1dSLionel Sambuc       else if (T->isObjCObjectPointerType() &&
537*0a6a1f1dSLionel Sambuc                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
538*0a6a1f1dSLionel Sambuc         if (const ObjCObjectPointerType * OBJPT =
539*0a6a1f1dSLionel Sambuc               T->getAsObjCInterfacePointerType()) {
540*0a6a1f1dSLionel Sambuc           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
541*0a6a1f1dSLionel Sambuc           T = QualType(IFaceT, 0);
542*0a6a1f1dSLionel Sambuc           T = Context->getPointerType(T);
543*0a6a1f1dSLionel Sambuc         }
544*0a6a1f1dSLionel Sambuc      }
545*0a6a1f1dSLionel Sambuc     }
546*0a6a1f1dSLionel Sambuc 
547*0a6a1f1dSLionel Sambuc     // FIXME: This predicate seems like it would be useful to add to ASTContext.
isObjCType(QualType T)548*0a6a1f1dSLionel Sambuc     bool isObjCType(QualType T) {
549*0a6a1f1dSLionel Sambuc       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
550*0a6a1f1dSLionel Sambuc         return false;
551*0a6a1f1dSLionel Sambuc 
552*0a6a1f1dSLionel Sambuc       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
553*0a6a1f1dSLionel Sambuc 
554*0a6a1f1dSLionel Sambuc       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
555*0a6a1f1dSLionel Sambuc           OCT == Context->getCanonicalType(Context->getObjCClassType()))
556*0a6a1f1dSLionel Sambuc         return true;
557*0a6a1f1dSLionel Sambuc 
558*0a6a1f1dSLionel Sambuc       if (const PointerType *PT = OCT->getAs<PointerType>()) {
559*0a6a1f1dSLionel Sambuc         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
560*0a6a1f1dSLionel Sambuc             PT->getPointeeType()->isObjCQualifiedIdType())
561*0a6a1f1dSLionel Sambuc           return true;
562*0a6a1f1dSLionel Sambuc       }
563*0a6a1f1dSLionel Sambuc       return false;
564*0a6a1f1dSLionel Sambuc     }
565*0a6a1f1dSLionel Sambuc     bool PointerTypeTakesAnyBlockArguments(QualType QT);
566*0a6a1f1dSLionel Sambuc     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
567*0a6a1f1dSLionel Sambuc     void GetExtentOfArgList(const char *Name, const char *&LParen,
568*0a6a1f1dSLionel Sambuc                             const char *&RParen);
569*0a6a1f1dSLionel Sambuc 
QuoteDoublequotes(std::string & From,std::string & To)570*0a6a1f1dSLionel Sambuc     void QuoteDoublequotes(std::string &From, std::string &To) {
571*0a6a1f1dSLionel Sambuc       for (unsigned i = 0; i < From.length(); i++) {
572*0a6a1f1dSLionel Sambuc         if (From[i] == '"')
573*0a6a1f1dSLionel Sambuc           To += "\\\"";
574*0a6a1f1dSLionel Sambuc         else
575*0a6a1f1dSLionel Sambuc           To += From[i];
576*0a6a1f1dSLionel Sambuc       }
577*0a6a1f1dSLionel Sambuc     }
578*0a6a1f1dSLionel Sambuc 
getSimpleFunctionType(QualType result,ArrayRef<QualType> args,bool variadic=false)579*0a6a1f1dSLionel Sambuc     QualType getSimpleFunctionType(QualType result,
580*0a6a1f1dSLionel Sambuc                                    ArrayRef<QualType> args,
581*0a6a1f1dSLionel Sambuc                                    bool variadic = false) {
582*0a6a1f1dSLionel Sambuc       if (result == Context->getObjCInstanceType())
583*0a6a1f1dSLionel Sambuc         result =  Context->getObjCIdType();
584*0a6a1f1dSLionel Sambuc       FunctionProtoType::ExtProtoInfo fpi;
585*0a6a1f1dSLionel Sambuc       fpi.Variadic = variadic;
586*0a6a1f1dSLionel Sambuc       return Context->getFunctionType(result, args, fpi);
587*0a6a1f1dSLionel Sambuc     }
588*0a6a1f1dSLionel Sambuc 
589*0a6a1f1dSLionel Sambuc     // Helper function: create a CStyleCastExpr with trivial type source info.
NoTypeInfoCStyleCastExpr(ASTContext * Ctx,QualType Ty,CastKind Kind,Expr * E)590*0a6a1f1dSLionel Sambuc     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
591*0a6a1f1dSLionel Sambuc                                              CastKind Kind, Expr *E) {
592*0a6a1f1dSLionel Sambuc       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
593*0a6a1f1dSLionel Sambuc       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
594*0a6a1f1dSLionel Sambuc                                     TInfo, SourceLocation(), SourceLocation());
595*0a6a1f1dSLionel Sambuc     }
596*0a6a1f1dSLionel Sambuc 
ImplementationIsNonLazy(const ObjCImplDecl * OD) const597*0a6a1f1dSLionel Sambuc     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
598*0a6a1f1dSLionel Sambuc       IdentifierInfo* II = &Context->Idents.get("load");
599*0a6a1f1dSLionel Sambuc       Selector LoadSel = Context->Selectors.getSelector(0, &II);
600*0a6a1f1dSLionel Sambuc       return OD->getClassMethod(LoadSel) != nullptr;
601*0a6a1f1dSLionel Sambuc     }
602*0a6a1f1dSLionel Sambuc 
getStringLiteral(StringRef Str)603*0a6a1f1dSLionel Sambuc     StringLiteral *getStringLiteral(StringRef Str) {
604*0a6a1f1dSLionel Sambuc       QualType StrType = Context->getConstantArrayType(
605*0a6a1f1dSLionel Sambuc           Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
606*0a6a1f1dSLionel Sambuc           0);
607*0a6a1f1dSLionel Sambuc       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
608*0a6a1f1dSLionel Sambuc                                    /*Pascal=*/false, StrType, SourceLocation());
609*0a6a1f1dSLionel Sambuc     }
610*0a6a1f1dSLionel Sambuc   };
611*0a6a1f1dSLionel Sambuc 
612*0a6a1f1dSLionel Sambuc }
613*0a6a1f1dSLionel Sambuc 
RewriteBlocksInFunctionProtoType(QualType funcType,NamedDecl * D)614*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615*0a6a1f1dSLionel Sambuc                                                    NamedDecl *D) {
616*0a6a1f1dSLionel Sambuc   if (const FunctionProtoType *fproto
617*0a6a1f1dSLionel Sambuc       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
618*0a6a1f1dSLionel Sambuc     for (const auto &I : fproto->param_types())
619*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(I)) {
620*0a6a1f1dSLionel Sambuc         // All the args are checked/rewritten. Don't call twice!
621*0a6a1f1dSLionel Sambuc         RewriteBlockPointerDecl(D);
622*0a6a1f1dSLionel Sambuc         break;
623*0a6a1f1dSLionel Sambuc       }
624*0a6a1f1dSLionel Sambuc   }
625*0a6a1f1dSLionel Sambuc }
626*0a6a1f1dSLionel Sambuc 
CheckFunctionPointerDecl(QualType funcType,NamedDecl * ND)627*0a6a1f1dSLionel Sambuc void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
628*0a6a1f1dSLionel Sambuc   const PointerType *PT = funcType->getAs<PointerType>();
629*0a6a1f1dSLionel Sambuc   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
630*0a6a1f1dSLionel Sambuc     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
631*0a6a1f1dSLionel Sambuc }
632*0a6a1f1dSLionel Sambuc 
IsHeaderFile(const std::string & Filename)633*0a6a1f1dSLionel Sambuc static bool IsHeaderFile(const std::string &Filename) {
634*0a6a1f1dSLionel Sambuc   std::string::size_type DotPos = Filename.rfind('.');
635*0a6a1f1dSLionel Sambuc 
636*0a6a1f1dSLionel Sambuc   if (DotPos == std::string::npos) {
637*0a6a1f1dSLionel Sambuc     // no file extension
638*0a6a1f1dSLionel Sambuc     return false;
639*0a6a1f1dSLionel Sambuc   }
640*0a6a1f1dSLionel Sambuc 
641*0a6a1f1dSLionel Sambuc   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
642*0a6a1f1dSLionel Sambuc   // C header: .h
643*0a6a1f1dSLionel Sambuc   // C++ header: .hh or .H;
644*0a6a1f1dSLionel Sambuc   return Ext == "h" || Ext == "hh" || Ext == "H";
645*0a6a1f1dSLionel Sambuc }
646*0a6a1f1dSLionel Sambuc 
RewriteModernObjC(std::string inFile,raw_ostream * OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn,bool LineInfo)647*0a6a1f1dSLionel Sambuc RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
648*0a6a1f1dSLionel Sambuc                          DiagnosticsEngine &D, const LangOptions &LOpts,
649*0a6a1f1dSLionel Sambuc                          bool silenceMacroWarn,
650*0a6a1f1dSLionel Sambuc                          bool LineInfo)
651*0a6a1f1dSLionel Sambuc       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
652*0a6a1f1dSLionel Sambuc         SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
653*0a6a1f1dSLionel Sambuc   IsHeader = IsHeaderFile(inFile);
654*0a6a1f1dSLionel Sambuc   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655*0a6a1f1dSLionel Sambuc                "rewriting sub-expression within a macro (may not be correct)");
656*0a6a1f1dSLionel Sambuc   // FIXME. This should be an error. But if block is not called, it is OK. And it
657*0a6a1f1dSLionel Sambuc   // may break including some headers.
658*0a6a1f1dSLionel Sambuc   GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
659*0a6a1f1dSLionel Sambuc     "rewriting block literal declared in global scope is not implemented");
660*0a6a1f1dSLionel Sambuc 
661*0a6a1f1dSLionel Sambuc   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
662*0a6a1f1dSLionel Sambuc                DiagnosticsEngine::Warning,
663*0a6a1f1dSLionel Sambuc                "rewriter doesn't support user-specified control flow semantics "
664*0a6a1f1dSLionel Sambuc                "for @try/@finally (code may not execute properly)");
665*0a6a1f1dSLionel Sambuc }
666*0a6a1f1dSLionel Sambuc 
CreateModernObjCRewriter(const std::string & InFile,raw_ostream * OS,DiagnosticsEngine & Diags,const LangOptions & LOpts,bool SilenceRewriteMacroWarning,bool LineInfo)667*0a6a1f1dSLionel Sambuc std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
668*0a6a1f1dSLionel Sambuc     const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
669*0a6a1f1dSLionel Sambuc     const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
670*0a6a1f1dSLionel Sambuc   return llvm::make_unique<RewriteModernObjC>(
671*0a6a1f1dSLionel Sambuc       InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
672*0a6a1f1dSLionel Sambuc }
673*0a6a1f1dSLionel Sambuc 
InitializeCommon(ASTContext & context)674*0a6a1f1dSLionel Sambuc void RewriteModernObjC::InitializeCommon(ASTContext &context) {
675*0a6a1f1dSLionel Sambuc   Context = &context;
676*0a6a1f1dSLionel Sambuc   SM = &Context->getSourceManager();
677*0a6a1f1dSLionel Sambuc   TUDecl = Context->getTranslationUnitDecl();
678*0a6a1f1dSLionel Sambuc   MsgSendFunctionDecl = nullptr;
679*0a6a1f1dSLionel Sambuc   MsgSendSuperFunctionDecl = nullptr;
680*0a6a1f1dSLionel Sambuc   MsgSendStretFunctionDecl = nullptr;
681*0a6a1f1dSLionel Sambuc   MsgSendSuperStretFunctionDecl = nullptr;
682*0a6a1f1dSLionel Sambuc   MsgSendFpretFunctionDecl = nullptr;
683*0a6a1f1dSLionel Sambuc   GetClassFunctionDecl = nullptr;
684*0a6a1f1dSLionel Sambuc   GetMetaClassFunctionDecl = nullptr;
685*0a6a1f1dSLionel Sambuc   GetSuperClassFunctionDecl = nullptr;
686*0a6a1f1dSLionel Sambuc   SelGetUidFunctionDecl = nullptr;
687*0a6a1f1dSLionel Sambuc   CFStringFunctionDecl = nullptr;
688*0a6a1f1dSLionel Sambuc   ConstantStringClassReference = nullptr;
689*0a6a1f1dSLionel Sambuc   NSStringRecord = nullptr;
690*0a6a1f1dSLionel Sambuc   CurMethodDef = nullptr;
691*0a6a1f1dSLionel Sambuc   CurFunctionDef = nullptr;
692*0a6a1f1dSLionel Sambuc   GlobalVarDecl = nullptr;
693*0a6a1f1dSLionel Sambuc   GlobalConstructionExp = nullptr;
694*0a6a1f1dSLionel Sambuc   SuperStructDecl = nullptr;
695*0a6a1f1dSLionel Sambuc   ProtocolTypeDecl = nullptr;
696*0a6a1f1dSLionel Sambuc   ConstantStringDecl = nullptr;
697*0a6a1f1dSLionel Sambuc   BcLabelCount = 0;
698*0a6a1f1dSLionel Sambuc   SuperConstructorFunctionDecl = nullptr;
699*0a6a1f1dSLionel Sambuc   NumObjCStringLiterals = 0;
700*0a6a1f1dSLionel Sambuc   PropParentMap = nullptr;
701*0a6a1f1dSLionel Sambuc   CurrentBody = nullptr;
702*0a6a1f1dSLionel Sambuc   DisableReplaceStmt = false;
703*0a6a1f1dSLionel Sambuc   objc_impl_method = false;
704*0a6a1f1dSLionel Sambuc 
705*0a6a1f1dSLionel Sambuc   // Get the ID and start/end of the main file.
706*0a6a1f1dSLionel Sambuc   MainFileID = SM->getMainFileID();
707*0a6a1f1dSLionel Sambuc   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
708*0a6a1f1dSLionel Sambuc   MainFileStart = MainBuf->getBufferStart();
709*0a6a1f1dSLionel Sambuc   MainFileEnd = MainBuf->getBufferEnd();
710*0a6a1f1dSLionel Sambuc 
711*0a6a1f1dSLionel Sambuc   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
712*0a6a1f1dSLionel Sambuc }
713*0a6a1f1dSLionel Sambuc 
714*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
715*0a6a1f1dSLionel Sambuc // Top Level Driver Code
716*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
717*0a6a1f1dSLionel Sambuc 
HandleTopLevelSingleDecl(Decl * D)718*0a6a1f1dSLionel Sambuc void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
719*0a6a1f1dSLionel Sambuc   if (Diags.hasErrorOccurred())
720*0a6a1f1dSLionel Sambuc     return;
721*0a6a1f1dSLionel Sambuc 
722*0a6a1f1dSLionel Sambuc   // Two cases: either the decl could be in the main file, or it could be in a
723*0a6a1f1dSLionel Sambuc   // #included file.  If the former, rewrite it now.  If the later, check to see
724*0a6a1f1dSLionel Sambuc   // if we rewrote the #include/#import.
725*0a6a1f1dSLionel Sambuc   SourceLocation Loc = D->getLocation();
726*0a6a1f1dSLionel Sambuc   Loc = SM->getExpansionLoc(Loc);
727*0a6a1f1dSLionel Sambuc 
728*0a6a1f1dSLionel Sambuc   // If this is for a builtin, ignore it.
729*0a6a1f1dSLionel Sambuc   if (Loc.isInvalid()) return;
730*0a6a1f1dSLionel Sambuc 
731*0a6a1f1dSLionel Sambuc   // Look for built-in declarations that we need to refer during the rewrite.
732*0a6a1f1dSLionel Sambuc   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
733*0a6a1f1dSLionel Sambuc     RewriteFunctionDecl(FD);
734*0a6a1f1dSLionel Sambuc   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
735*0a6a1f1dSLionel Sambuc     // declared in <Foundation/NSString.h>
736*0a6a1f1dSLionel Sambuc     if (FVD->getName() == "_NSConstantStringClassReference") {
737*0a6a1f1dSLionel Sambuc       ConstantStringClassReference = FVD;
738*0a6a1f1dSLionel Sambuc       return;
739*0a6a1f1dSLionel Sambuc     }
740*0a6a1f1dSLionel Sambuc   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
741*0a6a1f1dSLionel Sambuc     RewriteCategoryDecl(CD);
742*0a6a1f1dSLionel Sambuc   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
743*0a6a1f1dSLionel Sambuc     if (PD->isThisDeclarationADefinition())
744*0a6a1f1dSLionel Sambuc       RewriteProtocolDecl(PD);
745*0a6a1f1dSLionel Sambuc   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
746*0a6a1f1dSLionel Sambuc     // FIXME. This will not work in all situations and leaving it out
747*0a6a1f1dSLionel Sambuc     // is harmless.
748*0a6a1f1dSLionel Sambuc     // RewriteLinkageSpec(LSD);
749*0a6a1f1dSLionel Sambuc 
750*0a6a1f1dSLionel Sambuc     // Recurse into linkage specifications
751*0a6a1f1dSLionel Sambuc     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
752*0a6a1f1dSLionel Sambuc                                  DIEnd = LSD->decls_end();
753*0a6a1f1dSLionel Sambuc          DI != DIEnd; ) {
754*0a6a1f1dSLionel Sambuc       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
755*0a6a1f1dSLionel Sambuc         if (!IFace->isThisDeclarationADefinition()) {
756*0a6a1f1dSLionel Sambuc           SmallVector<Decl *, 8> DG;
757*0a6a1f1dSLionel Sambuc           SourceLocation StartLoc = IFace->getLocStart();
758*0a6a1f1dSLionel Sambuc           do {
759*0a6a1f1dSLionel Sambuc             if (isa<ObjCInterfaceDecl>(*DI) &&
760*0a6a1f1dSLionel Sambuc                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
761*0a6a1f1dSLionel Sambuc                 StartLoc == (*DI)->getLocStart())
762*0a6a1f1dSLionel Sambuc               DG.push_back(*DI);
763*0a6a1f1dSLionel Sambuc             else
764*0a6a1f1dSLionel Sambuc               break;
765*0a6a1f1dSLionel Sambuc 
766*0a6a1f1dSLionel Sambuc             ++DI;
767*0a6a1f1dSLionel Sambuc           } while (DI != DIEnd);
768*0a6a1f1dSLionel Sambuc           RewriteForwardClassDecl(DG);
769*0a6a1f1dSLionel Sambuc           continue;
770*0a6a1f1dSLionel Sambuc         }
771*0a6a1f1dSLionel Sambuc         else {
772*0a6a1f1dSLionel Sambuc           // Keep track of all interface declarations seen.
773*0a6a1f1dSLionel Sambuc           ObjCInterfacesSeen.push_back(IFace);
774*0a6a1f1dSLionel Sambuc           ++DI;
775*0a6a1f1dSLionel Sambuc           continue;
776*0a6a1f1dSLionel Sambuc         }
777*0a6a1f1dSLionel Sambuc       }
778*0a6a1f1dSLionel Sambuc 
779*0a6a1f1dSLionel Sambuc       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
780*0a6a1f1dSLionel Sambuc         if (!Proto->isThisDeclarationADefinition()) {
781*0a6a1f1dSLionel Sambuc           SmallVector<Decl *, 8> DG;
782*0a6a1f1dSLionel Sambuc           SourceLocation StartLoc = Proto->getLocStart();
783*0a6a1f1dSLionel Sambuc           do {
784*0a6a1f1dSLionel Sambuc             if (isa<ObjCProtocolDecl>(*DI) &&
785*0a6a1f1dSLionel Sambuc                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
786*0a6a1f1dSLionel Sambuc                 StartLoc == (*DI)->getLocStart())
787*0a6a1f1dSLionel Sambuc               DG.push_back(*DI);
788*0a6a1f1dSLionel Sambuc             else
789*0a6a1f1dSLionel Sambuc               break;
790*0a6a1f1dSLionel Sambuc 
791*0a6a1f1dSLionel Sambuc             ++DI;
792*0a6a1f1dSLionel Sambuc           } while (DI != DIEnd);
793*0a6a1f1dSLionel Sambuc           RewriteForwardProtocolDecl(DG);
794*0a6a1f1dSLionel Sambuc           continue;
795*0a6a1f1dSLionel Sambuc         }
796*0a6a1f1dSLionel Sambuc       }
797*0a6a1f1dSLionel Sambuc 
798*0a6a1f1dSLionel Sambuc       HandleTopLevelSingleDecl(*DI);
799*0a6a1f1dSLionel Sambuc       ++DI;
800*0a6a1f1dSLionel Sambuc     }
801*0a6a1f1dSLionel Sambuc   }
802*0a6a1f1dSLionel Sambuc   // If we have a decl in the main file, see if we should rewrite it.
803*0a6a1f1dSLionel Sambuc   if (SM->isWrittenInMainFile(Loc))
804*0a6a1f1dSLionel Sambuc     return HandleDeclInMainFile(D);
805*0a6a1f1dSLionel Sambuc }
806*0a6a1f1dSLionel Sambuc 
807*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
808*0a6a1f1dSLionel Sambuc // Syntactic (non-AST) Rewriting Code
809*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
810*0a6a1f1dSLionel Sambuc 
RewriteInclude()811*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteInclude() {
812*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
813*0a6a1f1dSLionel Sambuc   StringRef MainBuf = SM->getBufferData(MainFileID);
814*0a6a1f1dSLionel Sambuc   const char *MainBufStart = MainBuf.begin();
815*0a6a1f1dSLionel Sambuc   const char *MainBufEnd = MainBuf.end();
816*0a6a1f1dSLionel Sambuc   size_t ImportLen = strlen("import");
817*0a6a1f1dSLionel Sambuc 
818*0a6a1f1dSLionel Sambuc   // Loop over the whole file, looking for includes.
819*0a6a1f1dSLionel Sambuc   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
820*0a6a1f1dSLionel Sambuc     if (*BufPtr == '#') {
821*0a6a1f1dSLionel Sambuc       if (++BufPtr == MainBufEnd)
822*0a6a1f1dSLionel Sambuc         return;
823*0a6a1f1dSLionel Sambuc       while (*BufPtr == ' ' || *BufPtr == '\t')
824*0a6a1f1dSLionel Sambuc         if (++BufPtr == MainBufEnd)
825*0a6a1f1dSLionel Sambuc           return;
826*0a6a1f1dSLionel Sambuc       if (!strncmp(BufPtr, "import", ImportLen)) {
827*0a6a1f1dSLionel Sambuc         // replace import with include
828*0a6a1f1dSLionel Sambuc         SourceLocation ImportLoc =
829*0a6a1f1dSLionel Sambuc           LocStart.getLocWithOffset(BufPtr-MainBufStart);
830*0a6a1f1dSLionel Sambuc         ReplaceText(ImportLoc, ImportLen, "include");
831*0a6a1f1dSLionel Sambuc         BufPtr += ImportLen;
832*0a6a1f1dSLionel Sambuc       }
833*0a6a1f1dSLionel Sambuc     }
834*0a6a1f1dSLionel Sambuc   }
835*0a6a1f1dSLionel Sambuc }
836*0a6a1f1dSLionel Sambuc 
WriteInternalIvarName(const ObjCInterfaceDecl * IDecl,ObjCIvarDecl * IvarDecl,std::string & Result)837*0a6a1f1dSLionel Sambuc static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
838*0a6a1f1dSLionel Sambuc                                   ObjCIvarDecl *IvarDecl, std::string &Result) {
839*0a6a1f1dSLionel Sambuc   Result += "OBJC_IVAR_$_";
840*0a6a1f1dSLionel Sambuc   Result += IDecl->getName();
841*0a6a1f1dSLionel Sambuc   Result += "$";
842*0a6a1f1dSLionel Sambuc   Result += IvarDecl->getName();
843*0a6a1f1dSLionel Sambuc }
844*0a6a1f1dSLionel Sambuc 
845*0a6a1f1dSLionel Sambuc std::string
getIvarAccessString(ObjCIvarDecl * D)846*0a6a1f1dSLionel Sambuc RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
847*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
848*0a6a1f1dSLionel Sambuc 
849*0a6a1f1dSLionel Sambuc   // Build name of symbol holding ivar offset.
850*0a6a1f1dSLionel Sambuc   std::string IvarOffsetName;
851*0a6a1f1dSLionel Sambuc   if (D->isBitField())
852*0a6a1f1dSLionel Sambuc     ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
853*0a6a1f1dSLionel Sambuc   else
854*0a6a1f1dSLionel Sambuc     WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
855*0a6a1f1dSLionel Sambuc 
856*0a6a1f1dSLionel Sambuc 
857*0a6a1f1dSLionel Sambuc   std::string S = "(*(";
858*0a6a1f1dSLionel Sambuc   QualType IvarT = D->getType();
859*0a6a1f1dSLionel Sambuc   if (D->isBitField())
860*0a6a1f1dSLionel Sambuc     IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
861*0a6a1f1dSLionel Sambuc 
862*0a6a1f1dSLionel Sambuc   if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
863*0a6a1f1dSLionel Sambuc     RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
864*0a6a1f1dSLionel Sambuc     RD = RD->getDefinition();
865*0a6a1f1dSLionel Sambuc     if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
866*0a6a1f1dSLionel Sambuc       // decltype(((Foo_IMPL*)0)->bar) *
867*0a6a1f1dSLionel Sambuc       ObjCContainerDecl *CDecl =
868*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCContainerDecl>(D->getDeclContext());
869*0a6a1f1dSLionel Sambuc       // ivar in class extensions requires special treatment.
870*0a6a1f1dSLionel Sambuc       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
871*0a6a1f1dSLionel Sambuc         CDecl = CatDecl->getClassInterface();
872*0a6a1f1dSLionel Sambuc       std::string RecName = CDecl->getName();
873*0a6a1f1dSLionel Sambuc       RecName += "_IMPL";
874*0a6a1f1dSLionel Sambuc       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
875*0a6a1f1dSLionel Sambuc                                           SourceLocation(), SourceLocation(),
876*0a6a1f1dSLionel Sambuc                                           &Context->Idents.get(RecName.c_str()));
877*0a6a1f1dSLionel Sambuc       QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
878*0a6a1f1dSLionel Sambuc       unsigned UnsignedIntSize =
879*0a6a1f1dSLionel Sambuc       static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
880*0a6a1f1dSLionel Sambuc       Expr *Zero = IntegerLiteral::Create(*Context,
881*0a6a1f1dSLionel Sambuc                                           llvm::APInt(UnsignedIntSize, 0),
882*0a6a1f1dSLionel Sambuc                                           Context->UnsignedIntTy, SourceLocation());
883*0a6a1f1dSLionel Sambuc       Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
884*0a6a1f1dSLionel Sambuc       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
885*0a6a1f1dSLionel Sambuc                                               Zero);
886*0a6a1f1dSLionel Sambuc       FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
887*0a6a1f1dSLionel Sambuc                                         SourceLocation(),
888*0a6a1f1dSLionel Sambuc                                         &Context->Idents.get(D->getNameAsString()),
889*0a6a1f1dSLionel Sambuc                                         IvarT, nullptr,
890*0a6a1f1dSLionel Sambuc                                         /*BitWidth=*/nullptr, /*Mutable=*/true,
891*0a6a1f1dSLionel Sambuc                                         ICIS_NoInit);
892*0a6a1f1dSLionel Sambuc       MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
893*0a6a1f1dSLionel Sambuc                                                 FD->getType(), VK_LValue,
894*0a6a1f1dSLionel Sambuc                                                 OK_Ordinary);
895*0a6a1f1dSLionel Sambuc       IvarT = Context->getDecltypeType(ME, ME->getType());
896*0a6a1f1dSLionel Sambuc     }
897*0a6a1f1dSLionel Sambuc   }
898*0a6a1f1dSLionel Sambuc   convertObjCTypeToCStyleType(IvarT);
899*0a6a1f1dSLionel Sambuc   QualType castT = Context->getPointerType(IvarT);
900*0a6a1f1dSLionel Sambuc   std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
901*0a6a1f1dSLionel Sambuc   S += TypeString;
902*0a6a1f1dSLionel Sambuc   S += ")";
903*0a6a1f1dSLionel Sambuc 
904*0a6a1f1dSLionel Sambuc   // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
905*0a6a1f1dSLionel Sambuc   S += "((char *)self + ";
906*0a6a1f1dSLionel Sambuc   S += IvarOffsetName;
907*0a6a1f1dSLionel Sambuc   S += "))";
908*0a6a1f1dSLionel Sambuc   if (D->isBitField()) {
909*0a6a1f1dSLionel Sambuc     S += ".";
910*0a6a1f1dSLionel Sambuc     S += D->getNameAsString();
911*0a6a1f1dSLionel Sambuc   }
912*0a6a1f1dSLionel Sambuc   ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
913*0a6a1f1dSLionel Sambuc   return S;
914*0a6a1f1dSLionel Sambuc }
915*0a6a1f1dSLionel Sambuc 
916*0a6a1f1dSLionel Sambuc /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
917*0a6a1f1dSLionel Sambuc /// been found in the class implementation. In this case, it must be synthesized.
mustSynthesizeSetterGetterMethod(ObjCImplementationDecl * IMP,ObjCPropertyDecl * PD,bool getter)918*0a6a1f1dSLionel Sambuc static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
919*0a6a1f1dSLionel Sambuc                                              ObjCPropertyDecl *PD,
920*0a6a1f1dSLionel Sambuc                                              bool getter) {
921*0a6a1f1dSLionel Sambuc   return getter ? !IMP->getInstanceMethod(PD->getGetterName())
922*0a6a1f1dSLionel Sambuc                 : !IMP->getInstanceMethod(PD->getSetterName());
923*0a6a1f1dSLionel Sambuc 
924*0a6a1f1dSLionel Sambuc }
925*0a6a1f1dSLionel Sambuc 
RewritePropertyImplDecl(ObjCPropertyImplDecl * PID,ObjCImplementationDecl * IMD,ObjCCategoryImplDecl * CID)926*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
927*0a6a1f1dSLionel Sambuc                                           ObjCImplementationDecl *IMD,
928*0a6a1f1dSLionel Sambuc                                           ObjCCategoryImplDecl *CID) {
929*0a6a1f1dSLionel Sambuc   static bool objcGetPropertyDefined = false;
930*0a6a1f1dSLionel Sambuc   static bool objcSetPropertyDefined = false;
931*0a6a1f1dSLionel Sambuc   SourceLocation startGetterSetterLoc;
932*0a6a1f1dSLionel Sambuc 
933*0a6a1f1dSLionel Sambuc   if (PID->getLocStart().isValid()) {
934*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = PID->getLocStart();
935*0a6a1f1dSLionel Sambuc     InsertText(startLoc, "// ");
936*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
937*0a6a1f1dSLionel Sambuc     assert((*startBuf == '@') && "bogus @synthesize location");
938*0a6a1f1dSLionel Sambuc     const char *semiBuf = strchr(startBuf, ';');
939*0a6a1f1dSLionel Sambuc     assert((*semiBuf == ';') && "@synthesize: can't find ';'");
940*0a6a1f1dSLionel Sambuc     startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
941*0a6a1f1dSLionel Sambuc   }
942*0a6a1f1dSLionel Sambuc   else
943*0a6a1f1dSLionel Sambuc     startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
944*0a6a1f1dSLionel Sambuc 
945*0a6a1f1dSLionel Sambuc   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
946*0a6a1f1dSLionel Sambuc     return; // FIXME: is this correct?
947*0a6a1f1dSLionel Sambuc 
948*0a6a1f1dSLionel Sambuc   // Generate the 'getter' function.
949*0a6a1f1dSLionel Sambuc   ObjCPropertyDecl *PD = PID->getPropertyDecl();
950*0a6a1f1dSLionel Sambuc   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
951*0a6a1f1dSLionel Sambuc   assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
952*0a6a1f1dSLionel Sambuc 
953*0a6a1f1dSLionel Sambuc   unsigned Attributes = PD->getPropertyAttributes();
954*0a6a1f1dSLionel Sambuc   if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
955*0a6a1f1dSLionel Sambuc     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
956*0a6a1f1dSLionel Sambuc                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
957*0a6a1f1dSLionel Sambuc                                          ObjCPropertyDecl::OBJC_PR_copy));
958*0a6a1f1dSLionel Sambuc     std::string Getr;
959*0a6a1f1dSLionel Sambuc     if (GenGetProperty && !objcGetPropertyDefined) {
960*0a6a1f1dSLionel Sambuc       objcGetPropertyDefined = true;
961*0a6a1f1dSLionel Sambuc       // FIXME. Is this attribute correct in all cases?
962*0a6a1f1dSLionel Sambuc       Getr = "\nextern \"C\" __declspec(dllimport) "
963*0a6a1f1dSLionel Sambuc             "id objc_getProperty(id, SEL, long, bool);\n";
964*0a6a1f1dSLionel Sambuc     }
965*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OID->getContainingInterface(),
966*0a6a1f1dSLionel Sambuc                           PD->getGetterMethodDecl(), Getr);
967*0a6a1f1dSLionel Sambuc     Getr += "{ ";
968*0a6a1f1dSLionel Sambuc     // Synthesize an explicit cast to gain access to the ivar.
969*0a6a1f1dSLionel Sambuc     // See objc-act.c:objc_synthesize_new_getter() for details.
970*0a6a1f1dSLionel Sambuc     if (GenGetProperty) {
971*0a6a1f1dSLionel Sambuc       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
972*0a6a1f1dSLionel Sambuc       Getr += "typedef ";
973*0a6a1f1dSLionel Sambuc       const FunctionType *FPRetType = nullptr;
974*0a6a1f1dSLionel Sambuc       RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
975*0a6a1f1dSLionel Sambuc                             FPRetType);
976*0a6a1f1dSLionel Sambuc       Getr += " _TYPE";
977*0a6a1f1dSLionel Sambuc       if (FPRetType) {
978*0a6a1f1dSLionel Sambuc         Getr += ")"; // close the precedence "scope" for "*".
979*0a6a1f1dSLionel Sambuc 
980*0a6a1f1dSLionel Sambuc         // Now, emit the argument types (if any).
981*0a6a1f1dSLionel Sambuc         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
982*0a6a1f1dSLionel Sambuc           Getr += "(";
983*0a6a1f1dSLionel Sambuc           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
984*0a6a1f1dSLionel Sambuc             if (i) Getr += ", ";
985*0a6a1f1dSLionel Sambuc             std::string ParamStr =
986*0a6a1f1dSLionel Sambuc                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
987*0a6a1f1dSLionel Sambuc             Getr += ParamStr;
988*0a6a1f1dSLionel Sambuc           }
989*0a6a1f1dSLionel Sambuc           if (FT->isVariadic()) {
990*0a6a1f1dSLionel Sambuc             if (FT->getNumParams())
991*0a6a1f1dSLionel Sambuc               Getr += ", ";
992*0a6a1f1dSLionel Sambuc             Getr += "...";
993*0a6a1f1dSLionel Sambuc           }
994*0a6a1f1dSLionel Sambuc           Getr += ")";
995*0a6a1f1dSLionel Sambuc         } else
996*0a6a1f1dSLionel Sambuc           Getr += "()";
997*0a6a1f1dSLionel Sambuc       }
998*0a6a1f1dSLionel Sambuc       Getr += ";\n";
999*0a6a1f1dSLionel Sambuc       Getr += "return (_TYPE)";
1000*0a6a1f1dSLionel Sambuc       Getr += "objc_getProperty(self, _cmd, ";
1001*0a6a1f1dSLionel Sambuc       RewriteIvarOffsetComputation(OID, Getr);
1002*0a6a1f1dSLionel Sambuc       Getr += ", 1)";
1003*0a6a1f1dSLionel Sambuc     }
1004*0a6a1f1dSLionel Sambuc     else
1005*0a6a1f1dSLionel Sambuc       Getr += "return " + getIvarAccessString(OID);
1006*0a6a1f1dSLionel Sambuc     Getr += "; }";
1007*0a6a1f1dSLionel Sambuc     InsertText(startGetterSetterLoc, Getr);
1008*0a6a1f1dSLionel Sambuc   }
1009*0a6a1f1dSLionel Sambuc 
1010*0a6a1f1dSLionel Sambuc   if (PD->isReadOnly() ||
1011*0a6a1f1dSLionel Sambuc       !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1012*0a6a1f1dSLionel Sambuc     return;
1013*0a6a1f1dSLionel Sambuc 
1014*0a6a1f1dSLionel Sambuc   // Generate the 'setter' function.
1015*0a6a1f1dSLionel Sambuc   std::string Setr;
1016*0a6a1f1dSLionel Sambuc   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1017*0a6a1f1dSLionel Sambuc                                       ObjCPropertyDecl::OBJC_PR_copy);
1018*0a6a1f1dSLionel Sambuc   if (GenSetProperty && !objcSetPropertyDefined) {
1019*0a6a1f1dSLionel Sambuc     objcSetPropertyDefined = true;
1020*0a6a1f1dSLionel Sambuc     // FIXME. Is this attribute correct in all cases?
1021*0a6a1f1dSLionel Sambuc     Setr = "\nextern \"C\" __declspec(dllimport) "
1022*0a6a1f1dSLionel Sambuc     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1023*0a6a1f1dSLionel Sambuc   }
1024*0a6a1f1dSLionel Sambuc 
1025*0a6a1f1dSLionel Sambuc   RewriteObjCMethodDecl(OID->getContainingInterface(),
1026*0a6a1f1dSLionel Sambuc                         PD->getSetterMethodDecl(), Setr);
1027*0a6a1f1dSLionel Sambuc   Setr += "{ ";
1028*0a6a1f1dSLionel Sambuc   // Synthesize an explicit cast to initialize the ivar.
1029*0a6a1f1dSLionel Sambuc   // See objc-act.c:objc_synthesize_new_setter() for details.
1030*0a6a1f1dSLionel Sambuc   if (GenSetProperty) {
1031*0a6a1f1dSLionel Sambuc     Setr += "objc_setProperty (self, _cmd, ";
1032*0a6a1f1dSLionel Sambuc     RewriteIvarOffsetComputation(OID, Setr);
1033*0a6a1f1dSLionel Sambuc     Setr += ", (id)";
1034*0a6a1f1dSLionel Sambuc     Setr += PD->getName();
1035*0a6a1f1dSLionel Sambuc     Setr += ", ";
1036*0a6a1f1dSLionel Sambuc     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1037*0a6a1f1dSLionel Sambuc       Setr += "0, ";
1038*0a6a1f1dSLionel Sambuc     else
1039*0a6a1f1dSLionel Sambuc       Setr += "1, ";
1040*0a6a1f1dSLionel Sambuc     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1041*0a6a1f1dSLionel Sambuc       Setr += "1)";
1042*0a6a1f1dSLionel Sambuc     else
1043*0a6a1f1dSLionel Sambuc       Setr += "0)";
1044*0a6a1f1dSLionel Sambuc   }
1045*0a6a1f1dSLionel Sambuc   else {
1046*0a6a1f1dSLionel Sambuc     Setr += getIvarAccessString(OID) + " = ";
1047*0a6a1f1dSLionel Sambuc     Setr += PD->getName();
1048*0a6a1f1dSLionel Sambuc   }
1049*0a6a1f1dSLionel Sambuc   Setr += "; }\n";
1050*0a6a1f1dSLionel Sambuc   InsertText(startGetterSetterLoc, Setr);
1051*0a6a1f1dSLionel Sambuc }
1052*0a6a1f1dSLionel Sambuc 
RewriteOneForwardClassDecl(ObjCInterfaceDecl * ForwardDecl,std::string & typedefString)1053*0a6a1f1dSLionel Sambuc static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1054*0a6a1f1dSLionel Sambuc                                        std::string &typedefString) {
1055*0a6a1f1dSLionel Sambuc   typedefString += "\n#ifndef _REWRITER_typedef_";
1056*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
1057*0a6a1f1dSLionel Sambuc   typedefString += "\n";
1058*0a6a1f1dSLionel Sambuc   typedefString += "#define _REWRITER_typedef_";
1059*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
1060*0a6a1f1dSLionel Sambuc   typedefString += "\n";
1061*0a6a1f1dSLionel Sambuc   typedefString += "typedef struct objc_object ";
1062*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
1063*0a6a1f1dSLionel Sambuc   // typedef struct { } _objc_exc_Classname;
1064*0a6a1f1dSLionel Sambuc   typedefString += ";\ntypedef struct {} _objc_exc_";
1065*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
1066*0a6a1f1dSLionel Sambuc   typedefString += ";\n#endif\n";
1067*0a6a1f1dSLionel Sambuc }
1068*0a6a1f1dSLionel Sambuc 
RewriteForwardClassEpilogue(ObjCInterfaceDecl * ClassDecl,const std::string & typedefString)1069*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1070*0a6a1f1dSLionel Sambuc                                               const std::string &typedefString) {
1071*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = ClassDecl->getLocStart();
1072*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
1073*0a6a1f1dSLionel Sambuc     const char *semiPtr = strchr(startBuf, ';');
1074*0a6a1f1dSLionel Sambuc     // Replace the @class with typedefs corresponding to the classes.
1075*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1076*0a6a1f1dSLionel Sambuc }
1077*0a6a1f1dSLionel Sambuc 
RewriteForwardClassDecl(DeclGroupRef D)1078*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1079*0a6a1f1dSLionel Sambuc   std::string typedefString;
1080*0a6a1f1dSLionel Sambuc   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1081*0a6a1f1dSLionel Sambuc     if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1082*0a6a1f1dSLionel Sambuc       if (I == D.begin()) {
1083*0a6a1f1dSLionel Sambuc         // Translate to typedef's that forward reference structs with the same name
1084*0a6a1f1dSLionel Sambuc         // as the class. As a convenience, we include the original declaration
1085*0a6a1f1dSLionel Sambuc         // as a comment.
1086*0a6a1f1dSLionel Sambuc         typedefString += "// @class ";
1087*0a6a1f1dSLionel Sambuc         typedefString += ForwardDecl->getNameAsString();
1088*0a6a1f1dSLionel Sambuc         typedefString += ";";
1089*0a6a1f1dSLionel Sambuc       }
1090*0a6a1f1dSLionel Sambuc       RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1091*0a6a1f1dSLionel Sambuc     }
1092*0a6a1f1dSLionel Sambuc     else
1093*0a6a1f1dSLionel Sambuc       HandleTopLevelSingleDecl(*I);
1094*0a6a1f1dSLionel Sambuc   }
1095*0a6a1f1dSLionel Sambuc   DeclGroupRef::iterator I = D.begin();
1096*0a6a1f1dSLionel Sambuc   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1097*0a6a1f1dSLionel Sambuc }
1098*0a6a1f1dSLionel Sambuc 
RewriteForwardClassDecl(const SmallVectorImpl<Decl * > & D)1099*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteForwardClassDecl(
1100*0a6a1f1dSLionel Sambuc                                 const SmallVectorImpl<Decl *> &D) {
1101*0a6a1f1dSLionel Sambuc   std::string typedefString;
1102*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < D.size(); i++) {
1103*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1104*0a6a1f1dSLionel Sambuc     if (i == 0) {
1105*0a6a1f1dSLionel Sambuc       typedefString += "// @class ";
1106*0a6a1f1dSLionel Sambuc       typedefString += ForwardDecl->getNameAsString();
1107*0a6a1f1dSLionel Sambuc       typedefString += ";";
1108*0a6a1f1dSLionel Sambuc     }
1109*0a6a1f1dSLionel Sambuc     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1110*0a6a1f1dSLionel Sambuc   }
1111*0a6a1f1dSLionel Sambuc   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1112*0a6a1f1dSLionel Sambuc }
1113*0a6a1f1dSLionel Sambuc 
RewriteMethodDeclaration(ObjCMethodDecl * Method)1114*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1115*0a6a1f1dSLionel Sambuc   // When method is a synthesized one, such as a getter/setter there is
1116*0a6a1f1dSLionel Sambuc   // nothing to rewrite.
1117*0a6a1f1dSLionel Sambuc   if (Method->isImplicit())
1118*0a6a1f1dSLionel Sambuc     return;
1119*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = Method->getLocStart();
1120*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = Method->getLocEnd();
1121*0a6a1f1dSLionel Sambuc 
1122*0a6a1f1dSLionel Sambuc   if (SM->getExpansionLineNumber(LocEnd) >
1123*0a6a1f1dSLionel Sambuc       SM->getExpansionLineNumber(LocStart)) {
1124*0a6a1f1dSLionel Sambuc     InsertText(LocStart, "#if 0\n");
1125*0a6a1f1dSLionel Sambuc     ReplaceText(LocEnd, 1, ";\n#endif\n");
1126*0a6a1f1dSLionel Sambuc   } else {
1127*0a6a1f1dSLionel Sambuc     InsertText(LocStart, "// ");
1128*0a6a1f1dSLionel Sambuc   }
1129*0a6a1f1dSLionel Sambuc }
1130*0a6a1f1dSLionel Sambuc 
RewriteProperty(ObjCPropertyDecl * prop)1131*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1132*0a6a1f1dSLionel Sambuc   SourceLocation Loc = prop->getAtLoc();
1133*0a6a1f1dSLionel Sambuc 
1134*0a6a1f1dSLionel Sambuc   ReplaceText(Loc, 0, "// ");
1135*0a6a1f1dSLionel Sambuc   // FIXME: handle properties that are declared across multiple lines.
1136*0a6a1f1dSLionel Sambuc }
1137*0a6a1f1dSLionel Sambuc 
RewriteCategoryDecl(ObjCCategoryDecl * CatDecl)1138*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1139*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CatDecl->getLocStart();
1140*0a6a1f1dSLionel Sambuc 
1141*0a6a1f1dSLionel Sambuc   // FIXME: handle category headers that are declared across multiple lines.
1142*0a6a1f1dSLionel Sambuc   if (CatDecl->getIvarRBraceLoc().isValid()) {
1143*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, 1, "/** ");
1144*0a6a1f1dSLionel Sambuc     ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1145*0a6a1f1dSLionel Sambuc   }
1146*0a6a1f1dSLionel Sambuc   else {
1147*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, 0, "// ");
1148*0a6a1f1dSLionel Sambuc   }
1149*0a6a1f1dSLionel Sambuc 
1150*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->properties())
1151*0a6a1f1dSLionel Sambuc     RewriteProperty(I);
1152*0a6a1f1dSLionel Sambuc 
1153*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->instance_methods())
1154*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1155*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->class_methods())
1156*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1157*0a6a1f1dSLionel Sambuc 
1158*0a6a1f1dSLionel Sambuc   // Lastly, comment out the @end.
1159*0a6a1f1dSLionel Sambuc   ReplaceText(CatDecl->getAtEndRange().getBegin(),
1160*0a6a1f1dSLionel Sambuc               strlen("@end"), "/* @end */\n");
1161*0a6a1f1dSLionel Sambuc }
1162*0a6a1f1dSLionel Sambuc 
RewriteProtocolDecl(ObjCProtocolDecl * PDecl)1163*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1164*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = PDecl->getLocStart();
1165*0a6a1f1dSLionel Sambuc   assert(PDecl->isThisDeclarationADefinition());
1166*0a6a1f1dSLionel Sambuc 
1167*0a6a1f1dSLionel Sambuc   // FIXME: handle protocol headers that are declared across multiple lines.
1168*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1169*0a6a1f1dSLionel Sambuc 
1170*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->instance_methods())
1171*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1172*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->class_methods())
1173*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1174*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->properties())
1175*0a6a1f1dSLionel Sambuc     RewriteProperty(I);
1176*0a6a1f1dSLionel Sambuc 
1177*0a6a1f1dSLionel Sambuc   // Lastly, comment out the @end.
1178*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1179*0a6a1f1dSLionel Sambuc   ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1180*0a6a1f1dSLionel Sambuc 
1181*0a6a1f1dSLionel Sambuc   // Must comment out @optional/@required
1182*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
1183*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
1184*0a6a1f1dSLionel Sambuc   for (const char *p = startBuf; p < endBuf; p++) {
1185*0a6a1f1dSLionel Sambuc     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1186*0a6a1f1dSLionel Sambuc       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187*0a6a1f1dSLionel Sambuc       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1188*0a6a1f1dSLionel Sambuc 
1189*0a6a1f1dSLionel Sambuc     }
1190*0a6a1f1dSLionel Sambuc     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1191*0a6a1f1dSLionel Sambuc       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1192*0a6a1f1dSLionel Sambuc       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1193*0a6a1f1dSLionel Sambuc 
1194*0a6a1f1dSLionel Sambuc     }
1195*0a6a1f1dSLionel Sambuc   }
1196*0a6a1f1dSLionel Sambuc }
1197*0a6a1f1dSLionel Sambuc 
RewriteForwardProtocolDecl(DeclGroupRef D)1198*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1199*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = (*D.begin())->getLocStart();
1200*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
1201*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid SourceLocation");
1202*0a6a1f1dSLionel Sambuc   // FIXME: handle forward protocol that are declared across multiple lines.
1203*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1204*0a6a1f1dSLionel Sambuc }
1205*0a6a1f1dSLionel Sambuc 
1206*0a6a1f1dSLionel Sambuc void
RewriteForwardProtocolDecl(const SmallVectorImpl<Decl * > & DG)1207*0a6a1f1dSLionel Sambuc RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1208*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = DG[0]->getLocStart();
1209*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
1210*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid SourceLocation");
1211*0a6a1f1dSLionel Sambuc   // FIXME: handle forward protocol that are declared across multiple lines.
1212*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1213*0a6a1f1dSLionel Sambuc }
1214*0a6a1f1dSLionel Sambuc 
1215*0a6a1f1dSLionel Sambuc void
RewriteLinkageSpec(LinkageSpecDecl * LSD)1216*0a6a1f1dSLionel Sambuc RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1217*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = LSD->getExternLoc();
1218*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
1219*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid extern SourceLocation");
1220*0a6a1f1dSLionel Sambuc 
1221*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1222*0a6a1f1dSLionel Sambuc   if (!LSD->hasBraces())
1223*0a6a1f1dSLionel Sambuc     return;
1224*0a6a1f1dSLionel Sambuc   // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1225*0a6a1f1dSLionel Sambuc   SourceLocation LocRBrace = LSD->getRBraceLoc();
1226*0a6a1f1dSLionel Sambuc   if (LocRBrace.isInvalid())
1227*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid rbrace SourceLocation");
1228*0a6a1f1dSLionel Sambuc   ReplaceText(LocRBrace, 0, "// ");
1229*0a6a1f1dSLionel Sambuc }
1230*0a6a1f1dSLionel Sambuc 
RewriteTypeIntoString(QualType T,std::string & ResultStr,const FunctionType * & FPRetType)1231*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1232*0a6a1f1dSLionel Sambuc                                         const FunctionType *&FPRetType) {
1233*0a6a1f1dSLionel Sambuc   if (T->isObjCQualifiedIdType())
1234*0a6a1f1dSLionel Sambuc     ResultStr += "id";
1235*0a6a1f1dSLionel Sambuc   else if (T->isFunctionPointerType() ||
1236*0a6a1f1dSLionel Sambuc            T->isBlockPointerType()) {
1237*0a6a1f1dSLionel Sambuc     // needs special handling, since pointer-to-functions have special
1238*0a6a1f1dSLionel Sambuc     // syntax (where a decaration models use).
1239*0a6a1f1dSLionel Sambuc     QualType retType = T;
1240*0a6a1f1dSLionel Sambuc     QualType PointeeTy;
1241*0a6a1f1dSLionel Sambuc     if (const PointerType* PT = retType->getAs<PointerType>())
1242*0a6a1f1dSLionel Sambuc       PointeeTy = PT->getPointeeType();
1243*0a6a1f1dSLionel Sambuc     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1244*0a6a1f1dSLionel Sambuc       PointeeTy = BPT->getPointeeType();
1245*0a6a1f1dSLionel Sambuc     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1246*0a6a1f1dSLionel Sambuc       ResultStr +=
1247*0a6a1f1dSLionel Sambuc           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1248*0a6a1f1dSLionel Sambuc       ResultStr += "(*";
1249*0a6a1f1dSLionel Sambuc     }
1250*0a6a1f1dSLionel Sambuc   } else
1251*0a6a1f1dSLionel Sambuc     ResultStr += T.getAsString(Context->getPrintingPolicy());
1252*0a6a1f1dSLionel Sambuc }
1253*0a6a1f1dSLionel Sambuc 
RewriteObjCMethodDecl(const ObjCInterfaceDecl * IDecl,ObjCMethodDecl * OMD,std::string & ResultStr)1254*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1255*0a6a1f1dSLionel Sambuc                                         ObjCMethodDecl *OMD,
1256*0a6a1f1dSLionel Sambuc                                         std::string &ResultStr) {
1257*0a6a1f1dSLionel Sambuc   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1258*0a6a1f1dSLionel Sambuc   const FunctionType *FPRetType = nullptr;
1259*0a6a1f1dSLionel Sambuc   ResultStr += "\nstatic ";
1260*0a6a1f1dSLionel Sambuc   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1261*0a6a1f1dSLionel Sambuc   ResultStr += " ";
1262*0a6a1f1dSLionel Sambuc 
1263*0a6a1f1dSLionel Sambuc   // Unique method name
1264*0a6a1f1dSLionel Sambuc   std::string NameStr;
1265*0a6a1f1dSLionel Sambuc 
1266*0a6a1f1dSLionel Sambuc   if (OMD->isInstanceMethod())
1267*0a6a1f1dSLionel Sambuc     NameStr += "_I_";
1268*0a6a1f1dSLionel Sambuc   else
1269*0a6a1f1dSLionel Sambuc     NameStr += "_C_";
1270*0a6a1f1dSLionel Sambuc 
1271*0a6a1f1dSLionel Sambuc   NameStr += IDecl->getNameAsString();
1272*0a6a1f1dSLionel Sambuc   NameStr += "_";
1273*0a6a1f1dSLionel Sambuc 
1274*0a6a1f1dSLionel Sambuc   if (ObjCCategoryImplDecl *CID =
1275*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1276*0a6a1f1dSLionel Sambuc     NameStr += CID->getNameAsString();
1277*0a6a1f1dSLionel Sambuc     NameStr += "_";
1278*0a6a1f1dSLionel Sambuc   }
1279*0a6a1f1dSLionel Sambuc   // Append selector names, replacing ':' with '_'
1280*0a6a1f1dSLionel Sambuc   {
1281*0a6a1f1dSLionel Sambuc     std::string selString = OMD->getSelector().getAsString();
1282*0a6a1f1dSLionel Sambuc     int len = selString.size();
1283*0a6a1f1dSLionel Sambuc     for (int i = 0; i < len; i++)
1284*0a6a1f1dSLionel Sambuc       if (selString[i] == ':')
1285*0a6a1f1dSLionel Sambuc         selString[i] = '_';
1286*0a6a1f1dSLionel Sambuc     NameStr += selString;
1287*0a6a1f1dSLionel Sambuc   }
1288*0a6a1f1dSLionel Sambuc   // Remember this name for metadata emission
1289*0a6a1f1dSLionel Sambuc   MethodInternalNames[OMD] = NameStr;
1290*0a6a1f1dSLionel Sambuc   ResultStr += NameStr;
1291*0a6a1f1dSLionel Sambuc 
1292*0a6a1f1dSLionel Sambuc   // Rewrite arguments
1293*0a6a1f1dSLionel Sambuc   ResultStr += "(";
1294*0a6a1f1dSLionel Sambuc 
1295*0a6a1f1dSLionel Sambuc   // invisible arguments
1296*0a6a1f1dSLionel Sambuc   if (OMD->isInstanceMethod()) {
1297*0a6a1f1dSLionel Sambuc     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1298*0a6a1f1dSLionel Sambuc     selfTy = Context->getPointerType(selfTy);
1299*0a6a1f1dSLionel Sambuc     if (!LangOpts.MicrosoftExt) {
1300*0a6a1f1dSLionel Sambuc       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1301*0a6a1f1dSLionel Sambuc         ResultStr += "struct ";
1302*0a6a1f1dSLionel Sambuc     }
1303*0a6a1f1dSLionel Sambuc     // When rewriting for Microsoft, explicitly omit the structure name.
1304*0a6a1f1dSLionel Sambuc     ResultStr += IDecl->getNameAsString();
1305*0a6a1f1dSLionel Sambuc     ResultStr += " *";
1306*0a6a1f1dSLionel Sambuc   }
1307*0a6a1f1dSLionel Sambuc   else
1308*0a6a1f1dSLionel Sambuc     ResultStr += Context->getObjCClassType().getAsString(
1309*0a6a1f1dSLionel Sambuc       Context->getPrintingPolicy());
1310*0a6a1f1dSLionel Sambuc 
1311*0a6a1f1dSLionel Sambuc   ResultStr += " self, ";
1312*0a6a1f1dSLionel Sambuc   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1313*0a6a1f1dSLionel Sambuc   ResultStr += " _cmd";
1314*0a6a1f1dSLionel Sambuc 
1315*0a6a1f1dSLionel Sambuc   // Method arguments.
1316*0a6a1f1dSLionel Sambuc   for (const auto *PDecl : OMD->params()) {
1317*0a6a1f1dSLionel Sambuc     ResultStr += ", ";
1318*0a6a1f1dSLionel Sambuc     if (PDecl->getType()->isObjCQualifiedIdType()) {
1319*0a6a1f1dSLionel Sambuc       ResultStr += "id ";
1320*0a6a1f1dSLionel Sambuc       ResultStr += PDecl->getNameAsString();
1321*0a6a1f1dSLionel Sambuc     } else {
1322*0a6a1f1dSLionel Sambuc       std::string Name = PDecl->getNameAsString();
1323*0a6a1f1dSLionel Sambuc       QualType QT = PDecl->getType();
1324*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1325*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(QT);
1326*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1327*0a6a1f1dSLionel Sambuc       ResultStr += Name;
1328*0a6a1f1dSLionel Sambuc     }
1329*0a6a1f1dSLionel Sambuc   }
1330*0a6a1f1dSLionel Sambuc   if (OMD->isVariadic())
1331*0a6a1f1dSLionel Sambuc     ResultStr += ", ...";
1332*0a6a1f1dSLionel Sambuc   ResultStr += ") ";
1333*0a6a1f1dSLionel Sambuc 
1334*0a6a1f1dSLionel Sambuc   if (FPRetType) {
1335*0a6a1f1dSLionel Sambuc     ResultStr += ")"; // close the precedence "scope" for "*".
1336*0a6a1f1dSLionel Sambuc 
1337*0a6a1f1dSLionel Sambuc     // Now, emit the argument types (if any).
1338*0a6a1f1dSLionel Sambuc     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1339*0a6a1f1dSLionel Sambuc       ResultStr += "(";
1340*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1341*0a6a1f1dSLionel Sambuc         if (i) ResultStr += ", ";
1342*0a6a1f1dSLionel Sambuc         std::string ParamStr =
1343*0a6a1f1dSLionel Sambuc             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1344*0a6a1f1dSLionel Sambuc         ResultStr += ParamStr;
1345*0a6a1f1dSLionel Sambuc       }
1346*0a6a1f1dSLionel Sambuc       if (FT->isVariadic()) {
1347*0a6a1f1dSLionel Sambuc         if (FT->getNumParams())
1348*0a6a1f1dSLionel Sambuc           ResultStr += ", ";
1349*0a6a1f1dSLionel Sambuc         ResultStr += "...";
1350*0a6a1f1dSLionel Sambuc       }
1351*0a6a1f1dSLionel Sambuc       ResultStr += ")";
1352*0a6a1f1dSLionel Sambuc     } else {
1353*0a6a1f1dSLionel Sambuc       ResultStr += "()";
1354*0a6a1f1dSLionel Sambuc     }
1355*0a6a1f1dSLionel Sambuc   }
1356*0a6a1f1dSLionel Sambuc }
RewriteImplementationDecl(Decl * OID)1357*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358*0a6a1f1dSLionel Sambuc   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359*0a6a1f1dSLionel Sambuc   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1360*0a6a1f1dSLionel Sambuc 
1361*0a6a1f1dSLionel Sambuc   if (IMD) {
1362*0a6a1f1dSLionel Sambuc     if (IMD->getIvarRBraceLoc().isValid()) {
1363*0a6a1f1dSLionel Sambuc       ReplaceText(IMD->getLocStart(), 1, "/** ");
1364*0a6a1f1dSLionel Sambuc       ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1365*0a6a1f1dSLionel Sambuc     }
1366*0a6a1f1dSLionel Sambuc     else {
1367*0a6a1f1dSLionel Sambuc       InsertText(IMD->getLocStart(), "// ");
1368*0a6a1f1dSLionel Sambuc     }
1369*0a6a1f1dSLionel Sambuc   }
1370*0a6a1f1dSLionel Sambuc   else
1371*0a6a1f1dSLionel Sambuc     InsertText(CID->getLocStart(), "// ");
1372*0a6a1f1dSLionel Sambuc 
1373*0a6a1f1dSLionel Sambuc   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1374*0a6a1f1dSLionel Sambuc     std::string ResultStr;
1375*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1376*0a6a1f1dSLionel Sambuc     SourceLocation LocStart = OMD->getLocStart();
1377*0a6a1f1dSLionel Sambuc     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1378*0a6a1f1dSLionel Sambuc 
1379*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(LocStart);
1380*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(LocEnd);
1381*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1382*0a6a1f1dSLionel Sambuc   }
1383*0a6a1f1dSLionel Sambuc 
1384*0a6a1f1dSLionel Sambuc   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1385*0a6a1f1dSLionel Sambuc     std::string ResultStr;
1386*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1387*0a6a1f1dSLionel Sambuc     SourceLocation LocStart = OMD->getLocStart();
1388*0a6a1f1dSLionel Sambuc     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1389*0a6a1f1dSLionel Sambuc 
1390*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(LocStart);
1391*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(LocEnd);
1392*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1393*0a6a1f1dSLionel Sambuc   }
1394*0a6a1f1dSLionel Sambuc   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1395*0a6a1f1dSLionel Sambuc     RewritePropertyImplDecl(I, IMD, CID);
1396*0a6a1f1dSLionel Sambuc 
1397*0a6a1f1dSLionel Sambuc   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1398*0a6a1f1dSLionel Sambuc }
1399*0a6a1f1dSLionel Sambuc 
RewriteInterfaceDecl(ObjCInterfaceDecl * ClassDecl)1400*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1401*0a6a1f1dSLionel Sambuc   // Do not synthesize more than once.
1402*0a6a1f1dSLionel Sambuc   if (ObjCSynthesizedStructs.count(ClassDecl))
1403*0a6a1f1dSLionel Sambuc     return;
1404*0a6a1f1dSLionel Sambuc   // Make sure super class's are written before current class is written.
1405*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1406*0a6a1f1dSLionel Sambuc   while (SuperClass) {
1407*0a6a1f1dSLionel Sambuc     RewriteInterfaceDecl(SuperClass);
1408*0a6a1f1dSLionel Sambuc     SuperClass = SuperClass->getSuperClass();
1409*0a6a1f1dSLionel Sambuc   }
1410*0a6a1f1dSLionel Sambuc   std::string ResultStr;
1411*0a6a1f1dSLionel Sambuc   if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1412*0a6a1f1dSLionel Sambuc     // we haven't seen a forward decl - generate a typedef.
1413*0a6a1f1dSLionel Sambuc     RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1414*0a6a1f1dSLionel Sambuc     RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1415*0a6a1f1dSLionel Sambuc 
1416*0a6a1f1dSLionel Sambuc     RewriteObjCInternalStruct(ClassDecl, ResultStr);
1417*0a6a1f1dSLionel Sambuc     // Mark this typedef as having been written into its c++ equivalent.
1418*0a6a1f1dSLionel Sambuc     ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1419*0a6a1f1dSLionel Sambuc 
1420*0a6a1f1dSLionel Sambuc     for (auto *I : ClassDecl->properties())
1421*0a6a1f1dSLionel Sambuc       RewriteProperty(I);
1422*0a6a1f1dSLionel Sambuc     for (auto *I : ClassDecl->instance_methods())
1423*0a6a1f1dSLionel Sambuc       RewriteMethodDeclaration(I);
1424*0a6a1f1dSLionel Sambuc     for (auto *I : ClassDecl->class_methods())
1425*0a6a1f1dSLionel Sambuc       RewriteMethodDeclaration(I);
1426*0a6a1f1dSLionel Sambuc 
1427*0a6a1f1dSLionel Sambuc     // Lastly, comment out the @end.
1428*0a6a1f1dSLionel Sambuc     ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1429*0a6a1f1dSLionel Sambuc                 "/* @end */\n");
1430*0a6a1f1dSLionel Sambuc   }
1431*0a6a1f1dSLionel Sambuc }
1432*0a6a1f1dSLionel Sambuc 
RewritePropertyOrImplicitSetter(PseudoObjectExpr * PseudoOp)1433*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1434*0a6a1f1dSLionel Sambuc   SourceRange OldRange = PseudoOp->getSourceRange();
1435*0a6a1f1dSLionel Sambuc 
1436*0a6a1f1dSLionel Sambuc   // We just magically know some things about the structure of this
1437*0a6a1f1dSLionel Sambuc   // expression.
1438*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *OldMsg =
1439*0a6a1f1dSLionel Sambuc     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1440*0a6a1f1dSLionel Sambuc                             PseudoOp->getNumSemanticExprs() - 1));
1441*0a6a1f1dSLionel Sambuc 
1442*0a6a1f1dSLionel Sambuc   // Because the rewriter doesn't allow us to rewrite rewritten code,
1443*0a6a1f1dSLionel Sambuc   // we need to suppress rewriting the sub-statements.
1444*0a6a1f1dSLionel Sambuc   Expr *Base;
1445*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 2> Args;
1446*0a6a1f1dSLionel Sambuc   {
1447*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
1448*0a6a1f1dSLionel Sambuc 
1449*0a6a1f1dSLionel Sambuc     // Rebuild the base expression if we have one.
1450*0a6a1f1dSLionel Sambuc     Base = nullptr;
1451*0a6a1f1dSLionel Sambuc     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1452*0a6a1f1dSLionel Sambuc       Base = OldMsg->getInstanceReceiver();
1453*0a6a1f1dSLionel Sambuc       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1454*0a6a1f1dSLionel Sambuc       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1455*0a6a1f1dSLionel Sambuc     }
1456*0a6a1f1dSLionel Sambuc 
1457*0a6a1f1dSLionel Sambuc     unsigned numArgs = OldMsg->getNumArgs();
1458*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < numArgs; i++) {
1459*0a6a1f1dSLionel Sambuc       Expr *Arg = OldMsg->getArg(i);
1460*0a6a1f1dSLionel Sambuc       if (isa<OpaqueValueExpr>(Arg))
1461*0a6a1f1dSLionel Sambuc         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1462*0a6a1f1dSLionel Sambuc       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1463*0a6a1f1dSLionel Sambuc       Args.push_back(Arg);
1464*0a6a1f1dSLionel Sambuc     }
1465*0a6a1f1dSLionel Sambuc   }
1466*0a6a1f1dSLionel Sambuc 
1467*0a6a1f1dSLionel Sambuc   // TODO: avoid this copy.
1468*0a6a1f1dSLionel Sambuc   SmallVector<SourceLocation, 1> SelLocs;
1469*0a6a1f1dSLionel Sambuc   OldMsg->getSelectorLocs(SelLocs);
1470*0a6a1f1dSLionel Sambuc 
1471*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *NewMsg = nullptr;
1472*0a6a1f1dSLionel Sambuc   switch (OldMsg->getReceiverKind()) {
1473*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class:
1474*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1475*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1476*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1477*0a6a1f1dSLionel Sambuc                                      OldMsg->getClassReceiverTypeInfo(),
1478*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1479*0a6a1f1dSLionel Sambuc                                      SelLocs,
1480*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1481*0a6a1f1dSLionel Sambuc                                      Args,
1482*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1483*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1484*0a6a1f1dSLionel Sambuc     break;
1485*0a6a1f1dSLionel Sambuc 
1486*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance:
1487*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1489*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1490*0a6a1f1dSLionel Sambuc                                      Base,
1491*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1492*0a6a1f1dSLionel Sambuc                                      SelLocs,
1493*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1494*0a6a1f1dSLionel Sambuc                                      Args,
1495*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1496*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1497*0a6a1f1dSLionel Sambuc     break;
1498*0a6a1f1dSLionel Sambuc 
1499*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass:
1500*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
1501*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1503*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1504*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperLoc(),
1505*0a6a1f1dSLionel Sambuc                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1506*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperType(),
1507*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1508*0a6a1f1dSLionel Sambuc                                      SelLocs,
1509*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1510*0a6a1f1dSLionel Sambuc                                      Args,
1511*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1512*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1513*0a6a1f1dSLionel Sambuc     break;
1514*0a6a1f1dSLionel Sambuc   }
1515*0a6a1f1dSLionel Sambuc 
1516*0a6a1f1dSLionel Sambuc   Stmt *Replacement = SynthMessageExpr(NewMsg);
1517*0a6a1f1dSLionel Sambuc   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1518*0a6a1f1dSLionel Sambuc   return Replacement;
1519*0a6a1f1dSLionel Sambuc }
1520*0a6a1f1dSLionel Sambuc 
RewritePropertyOrImplicitGetter(PseudoObjectExpr * PseudoOp)1521*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1522*0a6a1f1dSLionel Sambuc   SourceRange OldRange = PseudoOp->getSourceRange();
1523*0a6a1f1dSLionel Sambuc 
1524*0a6a1f1dSLionel Sambuc   // We just magically know some things about the structure of this
1525*0a6a1f1dSLionel Sambuc   // expression.
1526*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *OldMsg =
1527*0a6a1f1dSLionel Sambuc     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1528*0a6a1f1dSLionel Sambuc 
1529*0a6a1f1dSLionel Sambuc   // Because the rewriter doesn't allow us to rewrite rewritten code,
1530*0a6a1f1dSLionel Sambuc   // we need to suppress rewriting the sub-statements.
1531*0a6a1f1dSLionel Sambuc   Expr *Base = nullptr;
1532*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 1> Args;
1533*0a6a1f1dSLionel Sambuc   {
1534*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
1535*0a6a1f1dSLionel Sambuc     // Rebuild the base expression if we have one.
1536*0a6a1f1dSLionel Sambuc     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1537*0a6a1f1dSLionel Sambuc       Base = OldMsg->getInstanceReceiver();
1538*0a6a1f1dSLionel Sambuc       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1539*0a6a1f1dSLionel Sambuc       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1540*0a6a1f1dSLionel Sambuc     }
1541*0a6a1f1dSLionel Sambuc     unsigned numArgs = OldMsg->getNumArgs();
1542*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < numArgs; i++) {
1543*0a6a1f1dSLionel Sambuc       Expr *Arg = OldMsg->getArg(i);
1544*0a6a1f1dSLionel Sambuc       if (isa<OpaqueValueExpr>(Arg))
1545*0a6a1f1dSLionel Sambuc         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1546*0a6a1f1dSLionel Sambuc       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1547*0a6a1f1dSLionel Sambuc       Args.push_back(Arg);
1548*0a6a1f1dSLionel Sambuc     }
1549*0a6a1f1dSLionel Sambuc   }
1550*0a6a1f1dSLionel Sambuc 
1551*0a6a1f1dSLionel Sambuc   // Intentionally empty.
1552*0a6a1f1dSLionel Sambuc   SmallVector<SourceLocation, 1> SelLocs;
1553*0a6a1f1dSLionel Sambuc 
1554*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *NewMsg = nullptr;
1555*0a6a1f1dSLionel Sambuc   switch (OldMsg->getReceiverKind()) {
1556*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class:
1557*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1558*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1559*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1560*0a6a1f1dSLionel Sambuc                                      OldMsg->getClassReceiverTypeInfo(),
1561*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1562*0a6a1f1dSLionel Sambuc                                      SelLocs,
1563*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1564*0a6a1f1dSLionel Sambuc                                      Args,
1565*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1566*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1567*0a6a1f1dSLionel Sambuc     break;
1568*0a6a1f1dSLionel Sambuc 
1569*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance:
1570*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1572*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1573*0a6a1f1dSLionel Sambuc                                      Base,
1574*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1575*0a6a1f1dSLionel Sambuc                                      SelLocs,
1576*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1577*0a6a1f1dSLionel Sambuc                                      Args,
1578*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1579*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1580*0a6a1f1dSLionel Sambuc     break;
1581*0a6a1f1dSLionel Sambuc 
1582*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass:
1583*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
1584*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1586*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1587*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperLoc(),
1588*0a6a1f1dSLionel Sambuc                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1589*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperType(),
1590*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1591*0a6a1f1dSLionel Sambuc                                      SelLocs,
1592*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1593*0a6a1f1dSLionel Sambuc                                      Args,
1594*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1595*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1596*0a6a1f1dSLionel Sambuc     break;
1597*0a6a1f1dSLionel Sambuc   }
1598*0a6a1f1dSLionel Sambuc 
1599*0a6a1f1dSLionel Sambuc   Stmt *Replacement = SynthMessageExpr(NewMsg);
1600*0a6a1f1dSLionel Sambuc   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1601*0a6a1f1dSLionel Sambuc   return Replacement;
1602*0a6a1f1dSLionel Sambuc }
1603*0a6a1f1dSLionel Sambuc 
1604*0a6a1f1dSLionel Sambuc /// SynthCountByEnumWithState - To print:
1605*0a6a1f1dSLionel Sambuc /// ((NSUInteger (*)
1606*0a6a1f1dSLionel Sambuc ///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1607*0a6a1f1dSLionel Sambuc ///  (void *)objc_msgSend)((id)l_collection,
1608*0a6a1f1dSLionel Sambuc ///                        sel_registerName(
1609*0a6a1f1dSLionel Sambuc ///                          "countByEnumeratingWithState:objects:count:"),
1610*0a6a1f1dSLionel Sambuc ///                        &enumState,
1611*0a6a1f1dSLionel Sambuc ///                        (id *)__rw_items, (NSUInteger)16)
1612*0a6a1f1dSLionel Sambuc ///
SynthCountByEnumWithState(std::string & buf)1613*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1614*0a6a1f1dSLionel Sambuc   buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1615*0a6a1f1dSLionel Sambuc   "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1616*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1617*0a6a1f1dSLionel Sambuc   buf += "((id)l_collection,\n\t\t";
1618*0a6a1f1dSLionel Sambuc   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1619*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1620*0a6a1f1dSLionel Sambuc   buf += "&enumState, "
1621*0a6a1f1dSLionel Sambuc          "(id *)__rw_items, (_WIN_NSUInteger)16)";
1622*0a6a1f1dSLionel Sambuc }
1623*0a6a1f1dSLionel Sambuc 
1624*0a6a1f1dSLionel Sambuc /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1625*0a6a1f1dSLionel Sambuc /// statement to exit to its outer synthesized loop.
1626*0a6a1f1dSLionel Sambuc ///
RewriteBreakStmt(BreakStmt * S)1627*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1628*0a6a1f1dSLionel Sambuc   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1629*0a6a1f1dSLionel Sambuc     return S;
1630*0a6a1f1dSLionel Sambuc   // replace break with goto __break_label
1631*0a6a1f1dSLionel Sambuc   std::string buf;
1632*0a6a1f1dSLionel Sambuc 
1633*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1634*0a6a1f1dSLionel Sambuc   buf = "goto __break_label_";
1635*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1636*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, strlen("break"), buf);
1637*0a6a1f1dSLionel Sambuc 
1638*0a6a1f1dSLionel Sambuc   return nullptr;
1639*0a6a1f1dSLionel Sambuc }
1640*0a6a1f1dSLionel Sambuc 
ConvertSourceLocationToLineDirective(SourceLocation Loc,std::string & LineString)1641*0a6a1f1dSLionel Sambuc void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1642*0a6a1f1dSLionel Sambuc                                           SourceLocation Loc,
1643*0a6a1f1dSLionel Sambuc                                           std::string &LineString) {
1644*0a6a1f1dSLionel Sambuc   if (Loc.isFileID() && GenerateLineInfo) {
1645*0a6a1f1dSLionel Sambuc     LineString += "\n#line ";
1646*0a6a1f1dSLionel Sambuc     PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1647*0a6a1f1dSLionel Sambuc     LineString += utostr(PLoc.getLine());
1648*0a6a1f1dSLionel Sambuc     LineString += " \"";
1649*0a6a1f1dSLionel Sambuc     LineString += Lexer::Stringify(PLoc.getFilename());
1650*0a6a1f1dSLionel Sambuc     LineString += "\"\n";
1651*0a6a1f1dSLionel Sambuc   }
1652*0a6a1f1dSLionel Sambuc }
1653*0a6a1f1dSLionel Sambuc 
1654*0a6a1f1dSLionel Sambuc /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1655*0a6a1f1dSLionel Sambuc /// statement to continue with its inner synthesized loop.
1656*0a6a1f1dSLionel Sambuc ///
RewriteContinueStmt(ContinueStmt * S)1657*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1658*0a6a1f1dSLionel Sambuc   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1659*0a6a1f1dSLionel Sambuc     return S;
1660*0a6a1f1dSLionel Sambuc   // replace continue with goto __continue_label
1661*0a6a1f1dSLionel Sambuc   std::string buf;
1662*0a6a1f1dSLionel Sambuc 
1663*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1664*0a6a1f1dSLionel Sambuc   buf = "goto __continue_label_";
1665*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1666*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, strlen("continue"), buf);
1667*0a6a1f1dSLionel Sambuc 
1668*0a6a1f1dSLionel Sambuc   return nullptr;
1669*0a6a1f1dSLionel Sambuc }
1670*0a6a1f1dSLionel Sambuc 
1671*0a6a1f1dSLionel Sambuc /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1672*0a6a1f1dSLionel Sambuc ///  It rewrites:
1673*0a6a1f1dSLionel Sambuc /// for ( type elem in collection) { stmts; }
1674*0a6a1f1dSLionel Sambuc 
1675*0a6a1f1dSLionel Sambuc /// Into:
1676*0a6a1f1dSLionel Sambuc /// {
1677*0a6a1f1dSLionel Sambuc ///   type elem;
1678*0a6a1f1dSLionel Sambuc ///   struct __objcFastEnumerationState enumState = { 0 };
1679*0a6a1f1dSLionel Sambuc ///   id __rw_items[16];
1680*0a6a1f1dSLionel Sambuc ///   id l_collection = (id)collection;
1681*0a6a1f1dSLionel Sambuc ///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1682*0a6a1f1dSLionel Sambuc ///                                       objects:__rw_items count:16];
1683*0a6a1f1dSLionel Sambuc /// if (limit) {
1684*0a6a1f1dSLionel Sambuc ///   unsigned long startMutations = *enumState.mutationsPtr;
1685*0a6a1f1dSLionel Sambuc ///   do {
1686*0a6a1f1dSLionel Sambuc ///        unsigned long counter = 0;
1687*0a6a1f1dSLionel Sambuc ///        do {
1688*0a6a1f1dSLionel Sambuc ///             if (startMutations != *enumState.mutationsPtr)
1689*0a6a1f1dSLionel Sambuc ///               objc_enumerationMutation(l_collection);
1690*0a6a1f1dSLionel Sambuc ///             elem = (type)enumState.itemsPtr[counter++];
1691*0a6a1f1dSLionel Sambuc ///             stmts;
1692*0a6a1f1dSLionel Sambuc ///             __continue_label: ;
1693*0a6a1f1dSLionel Sambuc ///        } while (counter < limit);
1694*0a6a1f1dSLionel Sambuc ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1695*0a6a1f1dSLionel Sambuc ///                                  objects:__rw_items count:16]));
1696*0a6a1f1dSLionel Sambuc ///   elem = nil;
1697*0a6a1f1dSLionel Sambuc ///   __break_label: ;
1698*0a6a1f1dSLionel Sambuc ///  }
1699*0a6a1f1dSLionel Sambuc ///  else
1700*0a6a1f1dSLionel Sambuc ///       elem = nil;
1701*0a6a1f1dSLionel Sambuc ///  }
1702*0a6a1f1dSLionel Sambuc ///
RewriteObjCForCollectionStmt(ObjCForCollectionStmt * S,SourceLocation OrigEnd)1703*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1704*0a6a1f1dSLionel Sambuc                                                 SourceLocation OrigEnd) {
1705*0a6a1f1dSLionel Sambuc   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1706*0a6a1f1dSLionel Sambuc   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1707*0a6a1f1dSLionel Sambuc          "ObjCForCollectionStmt Statement stack mismatch");
1708*0a6a1f1dSLionel Sambuc   assert(!ObjCBcLabelNo.empty() &&
1709*0a6a1f1dSLionel Sambuc          "ObjCForCollectionStmt - Label No stack empty");
1710*0a6a1f1dSLionel Sambuc 
1711*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1712*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1713*0a6a1f1dSLionel Sambuc   StringRef elementName;
1714*0a6a1f1dSLionel Sambuc   std::string elementTypeAsString;
1715*0a6a1f1dSLionel Sambuc   std::string buf;
1716*0a6a1f1dSLionel Sambuc   // line directive first.
1717*0a6a1f1dSLionel Sambuc   SourceLocation ForEachLoc = S->getForLoc();
1718*0a6a1f1dSLionel Sambuc   ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1719*0a6a1f1dSLionel Sambuc   buf += "{\n\t";
1720*0a6a1f1dSLionel Sambuc   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1721*0a6a1f1dSLionel Sambuc     // type elem;
1722*0a6a1f1dSLionel Sambuc     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1723*0a6a1f1dSLionel Sambuc     QualType ElementType = cast<ValueDecl>(D)->getType();
1724*0a6a1f1dSLionel Sambuc     if (ElementType->isObjCQualifiedIdType() ||
1725*0a6a1f1dSLionel Sambuc         ElementType->isObjCQualifiedInterfaceType())
1726*0a6a1f1dSLionel Sambuc       // Simply use 'id' for all qualified types.
1727*0a6a1f1dSLionel Sambuc       elementTypeAsString = "id";
1728*0a6a1f1dSLionel Sambuc     else
1729*0a6a1f1dSLionel Sambuc       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1730*0a6a1f1dSLionel Sambuc     buf += elementTypeAsString;
1731*0a6a1f1dSLionel Sambuc     buf += " ";
1732*0a6a1f1dSLionel Sambuc     elementName = D->getName();
1733*0a6a1f1dSLionel Sambuc     buf += elementName;
1734*0a6a1f1dSLionel Sambuc     buf += ";\n\t";
1735*0a6a1f1dSLionel Sambuc   }
1736*0a6a1f1dSLionel Sambuc   else {
1737*0a6a1f1dSLionel Sambuc     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1738*0a6a1f1dSLionel Sambuc     elementName = DR->getDecl()->getName();
1739*0a6a1f1dSLionel Sambuc     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1740*0a6a1f1dSLionel Sambuc     if (VD->getType()->isObjCQualifiedIdType() ||
1741*0a6a1f1dSLionel Sambuc         VD->getType()->isObjCQualifiedInterfaceType())
1742*0a6a1f1dSLionel Sambuc       // Simply use 'id' for all qualified types.
1743*0a6a1f1dSLionel Sambuc       elementTypeAsString = "id";
1744*0a6a1f1dSLionel Sambuc     else
1745*0a6a1f1dSLionel Sambuc       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1746*0a6a1f1dSLionel Sambuc   }
1747*0a6a1f1dSLionel Sambuc 
1748*0a6a1f1dSLionel Sambuc   // struct __objcFastEnumerationState enumState = { 0 };
1749*0a6a1f1dSLionel Sambuc   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1750*0a6a1f1dSLionel Sambuc   // id __rw_items[16];
1751*0a6a1f1dSLionel Sambuc   buf += "id __rw_items[16];\n\t";
1752*0a6a1f1dSLionel Sambuc   // id l_collection = (id)
1753*0a6a1f1dSLionel Sambuc   buf += "id l_collection = (id)";
1754*0a6a1f1dSLionel Sambuc   // Find start location of 'collection' the hard way!
1755*0a6a1f1dSLionel Sambuc   const char *startCollectionBuf = startBuf;
1756*0a6a1f1dSLionel Sambuc   startCollectionBuf += 3;  // skip 'for'
1757*0a6a1f1dSLionel Sambuc   startCollectionBuf = strchr(startCollectionBuf, '(');
1758*0a6a1f1dSLionel Sambuc   startCollectionBuf++; // skip '('
1759*0a6a1f1dSLionel Sambuc   // find 'in' and skip it.
1760*0a6a1f1dSLionel Sambuc   while (*startCollectionBuf != ' ' ||
1761*0a6a1f1dSLionel Sambuc          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1762*0a6a1f1dSLionel Sambuc          (*(startCollectionBuf+3) != ' ' &&
1763*0a6a1f1dSLionel Sambuc           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1764*0a6a1f1dSLionel Sambuc     startCollectionBuf++;
1765*0a6a1f1dSLionel Sambuc   startCollectionBuf += 3;
1766*0a6a1f1dSLionel Sambuc 
1767*0a6a1f1dSLionel Sambuc   // Replace: "for (type element in" with string constructed thus far.
1768*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1769*0a6a1f1dSLionel Sambuc   // Replace ')' in for '(' type elem in collection ')' with ';'
1770*0a6a1f1dSLionel Sambuc   SourceLocation rightParenLoc = S->getRParenLoc();
1771*0a6a1f1dSLionel Sambuc   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1772*0a6a1f1dSLionel Sambuc   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1773*0a6a1f1dSLionel Sambuc   buf = ";\n\t";
1774*0a6a1f1dSLionel Sambuc 
1775*0a6a1f1dSLionel Sambuc   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1776*0a6a1f1dSLionel Sambuc   //                                   objects:__rw_items count:16];
1777*0a6a1f1dSLionel Sambuc   // which is synthesized into:
1778*0a6a1f1dSLionel Sambuc   // NSUInteger limit =
1779*0a6a1f1dSLionel Sambuc   // ((NSUInteger (*)
1780*0a6a1f1dSLionel Sambuc   //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1781*0a6a1f1dSLionel Sambuc   //  (void *)objc_msgSend)((id)l_collection,
1782*0a6a1f1dSLionel Sambuc   //                        sel_registerName(
1783*0a6a1f1dSLionel Sambuc   //                          "countByEnumeratingWithState:objects:count:"),
1784*0a6a1f1dSLionel Sambuc   //                        (struct __objcFastEnumerationState *)&state,
1785*0a6a1f1dSLionel Sambuc   //                        (id *)__rw_items, (NSUInteger)16);
1786*0a6a1f1dSLionel Sambuc   buf += "_WIN_NSUInteger limit =\n\t\t";
1787*0a6a1f1dSLionel Sambuc   SynthCountByEnumWithState(buf);
1788*0a6a1f1dSLionel Sambuc   buf += ";\n\t";
1789*0a6a1f1dSLionel Sambuc   /// if (limit) {
1790*0a6a1f1dSLionel Sambuc   ///   unsigned long startMutations = *enumState.mutationsPtr;
1791*0a6a1f1dSLionel Sambuc   ///   do {
1792*0a6a1f1dSLionel Sambuc   ///        unsigned long counter = 0;
1793*0a6a1f1dSLionel Sambuc   ///        do {
1794*0a6a1f1dSLionel Sambuc   ///             if (startMutations != *enumState.mutationsPtr)
1795*0a6a1f1dSLionel Sambuc   ///               objc_enumerationMutation(l_collection);
1796*0a6a1f1dSLionel Sambuc   ///             elem = (type)enumState.itemsPtr[counter++];
1797*0a6a1f1dSLionel Sambuc   buf += "if (limit) {\n\t";
1798*0a6a1f1dSLionel Sambuc   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1799*0a6a1f1dSLionel Sambuc   buf += "do {\n\t\t";
1800*0a6a1f1dSLionel Sambuc   buf += "unsigned long counter = 0;\n\t\t";
1801*0a6a1f1dSLionel Sambuc   buf += "do {\n\t\t\t";
1802*0a6a1f1dSLionel Sambuc   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1803*0a6a1f1dSLionel Sambuc   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1804*0a6a1f1dSLionel Sambuc   buf += elementName;
1805*0a6a1f1dSLionel Sambuc   buf += " = (";
1806*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1807*0a6a1f1dSLionel Sambuc   buf += ")enumState.itemsPtr[counter++];";
1808*0a6a1f1dSLionel Sambuc   // Replace ')' in for '(' type elem in collection ')' with all of these.
1809*0a6a1f1dSLionel Sambuc   ReplaceText(lparenLoc, 1, buf);
1810*0a6a1f1dSLionel Sambuc 
1811*0a6a1f1dSLionel Sambuc   ///            __continue_label: ;
1812*0a6a1f1dSLionel Sambuc   ///        } while (counter < limit);
1813*0a6a1f1dSLionel Sambuc   ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1814*0a6a1f1dSLionel Sambuc   ///                                  objects:__rw_items count:16]));
1815*0a6a1f1dSLionel Sambuc   ///   elem = nil;
1816*0a6a1f1dSLionel Sambuc   ///   __break_label: ;
1817*0a6a1f1dSLionel Sambuc   ///  }
1818*0a6a1f1dSLionel Sambuc   ///  else
1819*0a6a1f1dSLionel Sambuc   ///       elem = nil;
1820*0a6a1f1dSLionel Sambuc   ///  }
1821*0a6a1f1dSLionel Sambuc   ///
1822*0a6a1f1dSLionel Sambuc   buf = ";\n\t";
1823*0a6a1f1dSLionel Sambuc   buf += "__continue_label_";
1824*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1825*0a6a1f1dSLionel Sambuc   buf += ": ;";
1826*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1827*0a6a1f1dSLionel Sambuc   buf += "} while (counter < limit);\n\t";
1828*0a6a1f1dSLionel Sambuc   buf += "} while ((limit = ";
1829*0a6a1f1dSLionel Sambuc   SynthCountByEnumWithState(buf);
1830*0a6a1f1dSLionel Sambuc   buf += "));\n\t";
1831*0a6a1f1dSLionel Sambuc   buf += elementName;
1832*0a6a1f1dSLionel Sambuc   buf += " = ((";
1833*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1834*0a6a1f1dSLionel Sambuc   buf += ")0);\n\t";
1835*0a6a1f1dSLionel Sambuc   buf += "__break_label_";
1836*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1837*0a6a1f1dSLionel Sambuc   buf += ": ;\n\t";
1838*0a6a1f1dSLionel Sambuc   buf += "}\n\t";
1839*0a6a1f1dSLionel Sambuc   buf += "else\n\t\t";
1840*0a6a1f1dSLionel Sambuc   buf += elementName;
1841*0a6a1f1dSLionel Sambuc   buf += " = ((";
1842*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1843*0a6a1f1dSLionel Sambuc   buf += ")0);\n\t";
1844*0a6a1f1dSLionel Sambuc   buf += "}\n";
1845*0a6a1f1dSLionel Sambuc 
1846*0a6a1f1dSLionel Sambuc   // Insert all these *after* the statement body.
1847*0a6a1f1dSLionel Sambuc   // FIXME: If this should support Obj-C++, support CXXTryStmt
1848*0a6a1f1dSLionel Sambuc   if (isa<CompoundStmt>(S->getBody())) {
1849*0a6a1f1dSLionel Sambuc     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1850*0a6a1f1dSLionel Sambuc     InsertText(endBodyLoc, buf);
1851*0a6a1f1dSLionel Sambuc   } else {
1852*0a6a1f1dSLionel Sambuc     /* Need to treat single statements specially. For example:
1853*0a6a1f1dSLionel Sambuc      *
1854*0a6a1f1dSLionel Sambuc      *     for (A *a in b) if (stuff()) break;
1855*0a6a1f1dSLionel Sambuc      *     for (A *a in b) xxxyy;
1856*0a6a1f1dSLionel Sambuc      *
1857*0a6a1f1dSLionel Sambuc      * The following code simply scans ahead to the semi to find the actual end.
1858*0a6a1f1dSLionel Sambuc      */
1859*0a6a1f1dSLionel Sambuc     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1860*0a6a1f1dSLionel Sambuc     const char *semiBuf = strchr(stmtBuf, ';');
1861*0a6a1f1dSLionel Sambuc     assert(semiBuf && "Can't find ';'");
1862*0a6a1f1dSLionel Sambuc     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1863*0a6a1f1dSLionel Sambuc     InsertText(endBodyLoc, buf);
1864*0a6a1f1dSLionel Sambuc   }
1865*0a6a1f1dSLionel Sambuc   Stmts.pop_back();
1866*0a6a1f1dSLionel Sambuc   ObjCBcLabelNo.pop_back();
1867*0a6a1f1dSLionel Sambuc   return nullptr;
1868*0a6a1f1dSLionel Sambuc }
1869*0a6a1f1dSLionel Sambuc 
Write_RethrowObject(std::string & buf)1870*0a6a1f1dSLionel Sambuc static void Write_RethrowObject(std::string &buf) {
1871*0a6a1f1dSLionel Sambuc   buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1872*0a6a1f1dSLionel Sambuc   buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1873*0a6a1f1dSLionel Sambuc   buf += "\tid rethrow;\n";
1874*0a6a1f1dSLionel Sambuc   buf += "\t} _fin_force_rethow(_rethrow);";
1875*0a6a1f1dSLionel Sambuc }
1876*0a6a1f1dSLionel Sambuc 
1877*0a6a1f1dSLionel Sambuc /// RewriteObjCSynchronizedStmt -
1878*0a6a1f1dSLionel Sambuc /// This routine rewrites @synchronized(expr) stmt;
1879*0a6a1f1dSLionel Sambuc /// into:
1880*0a6a1f1dSLionel Sambuc /// objc_sync_enter(expr);
1881*0a6a1f1dSLionel Sambuc /// @try stmt @finally { objc_sync_exit(expr); }
1882*0a6a1f1dSLionel Sambuc ///
RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt * S)1883*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1884*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
1885*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1886*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1887*0a6a1f1dSLionel Sambuc 
1888*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @synchronized location");
1889*0a6a1f1dSLionel Sambuc 
1890*0a6a1f1dSLionel Sambuc   std::string buf;
1891*0a6a1f1dSLionel Sambuc   SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1892*0a6a1f1dSLionel Sambuc   ConvertSourceLocationToLineDirective(SynchLoc, buf);
1893*0a6a1f1dSLionel Sambuc   buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1894*0a6a1f1dSLionel Sambuc 
1895*0a6a1f1dSLionel Sambuc   const char *lparenBuf = startBuf;
1896*0a6a1f1dSLionel Sambuc   while (*lparenBuf != '(') lparenBuf++;
1897*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1898*0a6a1f1dSLionel Sambuc 
1899*0a6a1f1dSLionel Sambuc   buf = "; objc_sync_enter(_sync_obj);\n";
1900*0a6a1f1dSLionel Sambuc   buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1901*0a6a1f1dSLionel Sambuc   buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1902*0a6a1f1dSLionel Sambuc   buf += "\n\tid sync_exit;";
1903*0a6a1f1dSLionel Sambuc   buf += "\n\t} _sync_exit(_sync_obj);\n";
1904*0a6a1f1dSLionel Sambuc 
1905*0a6a1f1dSLionel Sambuc   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1906*0a6a1f1dSLionel Sambuc   // the sync expression is typically a message expression that's already
1907*0a6a1f1dSLionel Sambuc   // been rewritten! (which implies the SourceLocation's are invalid).
1908*0a6a1f1dSLionel Sambuc   SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1909*0a6a1f1dSLionel Sambuc   const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1910*0a6a1f1dSLionel Sambuc   while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1911*0a6a1f1dSLionel Sambuc   RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1912*0a6a1f1dSLionel Sambuc 
1913*0a6a1f1dSLionel Sambuc   SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1914*0a6a1f1dSLionel Sambuc   const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1915*0a6a1f1dSLionel Sambuc   assert (*LBraceLocBuf == '{');
1916*0a6a1f1dSLionel Sambuc   ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1917*0a6a1f1dSLionel Sambuc 
1918*0a6a1f1dSLionel Sambuc   SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1919*0a6a1f1dSLionel Sambuc   assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1920*0a6a1f1dSLionel Sambuc          "bogus @synchronized block");
1921*0a6a1f1dSLionel Sambuc 
1922*0a6a1f1dSLionel Sambuc   buf = "} catch (id e) {_rethrow = e;}\n";
1923*0a6a1f1dSLionel Sambuc   Write_RethrowObject(buf);
1924*0a6a1f1dSLionel Sambuc   buf += "}\n";
1925*0a6a1f1dSLionel Sambuc   buf += "}\n";
1926*0a6a1f1dSLionel Sambuc 
1927*0a6a1f1dSLionel Sambuc   ReplaceText(startRBraceLoc, 1, buf);
1928*0a6a1f1dSLionel Sambuc 
1929*0a6a1f1dSLionel Sambuc   return nullptr;
1930*0a6a1f1dSLionel Sambuc }
1931*0a6a1f1dSLionel Sambuc 
WarnAboutReturnGotoStmts(Stmt * S)1932*0a6a1f1dSLionel Sambuc void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1933*0a6a1f1dSLionel Sambuc {
1934*0a6a1f1dSLionel Sambuc   // Perform a bottom up traversal of all children.
1935*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
1936*0a6a1f1dSLionel Sambuc     if (*CI)
1937*0a6a1f1dSLionel Sambuc       WarnAboutReturnGotoStmts(*CI);
1938*0a6a1f1dSLionel Sambuc 
1939*0a6a1f1dSLionel Sambuc   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1940*0a6a1f1dSLionel Sambuc     Diags.Report(Context->getFullLoc(S->getLocStart()),
1941*0a6a1f1dSLionel Sambuc                  TryFinallyContainsReturnDiag);
1942*0a6a1f1dSLionel Sambuc   }
1943*0a6a1f1dSLionel Sambuc   return;
1944*0a6a1f1dSLionel Sambuc }
1945*0a6a1f1dSLionel Sambuc 
RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt * S)1946*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1947*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getAtLoc();
1948*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1949*0a6a1f1dSLionel Sambuc   ReplaceText(S->getSubStmt()->getLocStart(), 1,
1950*0a6a1f1dSLionel Sambuc               "{ __AtAutoreleasePool __autoreleasepool; ");
1951*0a6a1f1dSLionel Sambuc 
1952*0a6a1f1dSLionel Sambuc   return nullptr;
1953*0a6a1f1dSLionel Sambuc }
1954*0a6a1f1dSLionel Sambuc 
RewriteObjCTryStmt(ObjCAtTryStmt * S)1955*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1956*0a6a1f1dSLionel Sambuc   ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1957*0a6a1f1dSLionel Sambuc   bool noCatch = S->getNumCatchStmts() == 0;
1958*0a6a1f1dSLionel Sambuc   std::string buf;
1959*0a6a1f1dSLionel Sambuc   SourceLocation TryLocation = S->getAtTryLoc();
1960*0a6a1f1dSLionel Sambuc   ConvertSourceLocationToLineDirective(TryLocation, buf);
1961*0a6a1f1dSLionel Sambuc 
1962*0a6a1f1dSLionel Sambuc   if (finalStmt) {
1963*0a6a1f1dSLionel Sambuc     if (noCatch)
1964*0a6a1f1dSLionel Sambuc       buf += "{ id volatile _rethrow = 0;\n";
1965*0a6a1f1dSLionel Sambuc     else {
1966*0a6a1f1dSLionel Sambuc       buf += "{ id volatile _rethrow = 0;\ntry {\n";
1967*0a6a1f1dSLionel Sambuc     }
1968*0a6a1f1dSLionel Sambuc   }
1969*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
1970*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1971*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1972*0a6a1f1dSLionel Sambuc 
1973*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @try location");
1974*0a6a1f1dSLionel Sambuc   if (finalStmt)
1975*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, 1, buf);
1976*0a6a1f1dSLionel Sambuc   else
1977*0a6a1f1dSLionel Sambuc     // @try -> try
1978*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, 1, "");
1979*0a6a1f1dSLionel Sambuc 
1980*0a6a1f1dSLionel Sambuc   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1981*0a6a1f1dSLionel Sambuc     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1982*0a6a1f1dSLionel Sambuc     VarDecl *catchDecl = Catch->getCatchParamDecl();
1983*0a6a1f1dSLionel Sambuc 
1984*0a6a1f1dSLionel Sambuc     startLoc = Catch->getLocStart();
1985*0a6a1f1dSLionel Sambuc     bool AtRemoved = false;
1986*0a6a1f1dSLionel Sambuc     if (catchDecl) {
1987*0a6a1f1dSLionel Sambuc       QualType t = catchDecl->getType();
1988*0a6a1f1dSLionel Sambuc       if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1989*0a6a1f1dSLionel Sambuc         // Should be a pointer to a class.
1990*0a6a1f1dSLionel Sambuc         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991*0a6a1f1dSLionel Sambuc         if (IDecl) {
1992*0a6a1f1dSLionel Sambuc           std::string Result;
1993*0a6a1f1dSLionel Sambuc           ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1994*0a6a1f1dSLionel Sambuc 
1995*0a6a1f1dSLionel Sambuc           startBuf = SM->getCharacterData(startLoc);
1996*0a6a1f1dSLionel Sambuc           assert((*startBuf == '@') && "bogus @catch location");
1997*0a6a1f1dSLionel Sambuc           SourceLocation rParenLoc = Catch->getRParenLoc();
1998*0a6a1f1dSLionel Sambuc           const char *rParenBuf = SM->getCharacterData(rParenLoc);
1999*0a6a1f1dSLionel Sambuc 
2000*0a6a1f1dSLionel Sambuc           // _objc_exc_Foo *_e as argument to catch.
2001*0a6a1f1dSLionel Sambuc           Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
2002*0a6a1f1dSLionel Sambuc           Result += " *_"; Result += catchDecl->getNameAsString();
2003*0a6a1f1dSLionel Sambuc           Result += ")";
2004*0a6a1f1dSLionel Sambuc           ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2005*0a6a1f1dSLionel Sambuc           // Foo *e = (Foo *)_e;
2006*0a6a1f1dSLionel Sambuc           Result.clear();
2007*0a6a1f1dSLionel Sambuc           Result = "{ ";
2008*0a6a1f1dSLionel Sambuc           Result += IDecl->getNameAsString();
2009*0a6a1f1dSLionel Sambuc           Result += " *"; Result += catchDecl->getNameAsString();
2010*0a6a1f1dSLionel Sambuc           Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2011*0a6a1f1dSLionel Sambuc           Result += "_"; Result += catchDecl->getNameAsString();
2012*0a6a1f1dSLionel Sambuc 
2013*0a6a1f1dSLionel Sambuc           Result += "; ";
2014*0a6a1f1dSLionel Sambuc           SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2015*0a6a1f1dSLionel Sambuc           ReplaceText(lBraceLoc, 1, Result);
2016*0a6a1f1dSLionel Sambuc           AtRemoved = true;
2017*0a6a1f1dSLionel Sambuc         }
2018*0a6a1f1dSLionel Sambuc       }
2019*0a6a1f1dSLionel Sambuc     }
2020*0a6a1f1dSLionel Sambuc     if (!AtRemoved)
2021*0a6a1f1dSLionel Sambuc       // @catch -> catch
2022*0a6a1f1dSLionel Sambuc       ReplaceText(startLoc, 1, "");
2023*0a6a1f1dSLionel Sambuc 
2024*0a6a1f1dSLionel Sambuc   }
2025*0a6a1f1dSLionel Sambuc   if (finalStmt) {
2026*0a6a1f1dSLionel Sambuc     buf.clear();
2027*0a6a1f1dSLionel Sambuc     SourceLocation FinallyLoc = finalStmt->getLocStart();
2028*0a6a1f1dSLionel Sambuc 
2029*0a6a1f1dSLionel Sambuc     if (noCatch) {
2030*0a6a1f1dSLionel Sambuc       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2031*0a6a1f1dSLionel Sambuc       buf += "catch (id e) {_rethrow = e;}\n";
2032*0a6a1f1dSLionel Sambuc     }
2033*0a6a1f1dSLionel Sambuc     else {
2034*0a6a1f1dSLionel Sambuc       buf += "}\n";
2035*0a6a1f1dSLionel Sambuc       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2036*0a6a1f1dSLionel Sambuc       buf += "catch (id e) {_rethrow = e;}\n";
2037*0a6a1f1dSLionel Sambuc     }
2038*0a6a1f1dSLionel Sambuc 
2039*0a6a1f1dSLionel Sambuc     SourceLocation startFinalLoc = finalStmt->getLocStart();
2040*0a6a1f1dSLionel Sambuc     ReplaceText(startFinalLoc, 8, buf);
2041*0a6a1f1dSLionel Sambuc     Stmt *body = finalStmt->getFinallyBody();
2042*0a6a1f1dSLionel Sambuc     SourceLocation startFinalBodyLoc = body->getLocStart();
2043*0a6a1f1dSLionel Sambuc     buf.clear();
2044*0a6a1f1dSLionel Sambuc     Write_RethrowObject(buf);
2045*0a6a1f1dSLionel Sambuc     ReplaceText(startFinalBodyLoc, 1, buf);
2046*0a6a1f1dSLionel Sambuc 
2047*0a6a1f1dSLionel Sambuc     SourceLocation endFinalBodyLoc = body->getLocEnd();
2048*0a6a1f1dSLionel Sambuc     ReplaceText(endFinalBodyLoc, 1, "}\n}");
2049*0a6a1f1dSLionel Sambuc     // Now check for any return/continue/go statements within the @try.
2050*0a6a1f1dSLionel Sambuc     WarnAboutReturnGotoStmts(S->getTryBody());
2051*0a6a1f1dSLionel Sambuc   }
2052*0a6a1f1dSLionel Sambuc 
2053*0a6a1f1dSLionel Sambuc   return nullptr;
2054*0a6a1f1dSLionel Sambuc }
2055*0a6a1f1dSLionel Sambuc 
2056*0a6a1f1dSLionel Sambuc // This can't be done with ReplaceStmt(S, ThrowExpr), since
2057*0a6a1f1dSLionel Sambuc // the throw expression is typically a message expression that's already
2058*0a6a1f1dSLionel Sambuc // been rewritten! (which implies the SourceLocation's are invalid).
RewriteObjCThrowStmt(ObjCAtThrowStmt * S)2059*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2060*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
2061*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
2062*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
2063*0a6a1f1dSLionel Sambuc 
2064*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @throw location");
2065*0a6a1f1dSLionel Sambuc 
2066*0a6a1f1dSLionel Sambuc   std::string buf;
2067*0a6a1f1dSLionel Sambuc   /* void objc_exception_throw(id) __attribute__((noreturn)); */
2068*0a6a1f1dSLionel Sambuc   if (S->getThrowExpr())
2069*0a6a1f1dSLionel Sambuc     buf = "objc_exception_throw(";
2070*0a6a1f1dSLionel Sambuc   else
2071*0a6a1f1dSLionel Sambuc     buf = "throw";
2072*0a6a1f1dSLionel Sambuc 
2073*0a6a1f1dSLionel Sambuc   // handle "@  throw" correctly.
2074*0a6a1f1dSLionel Sambuc   const char *wBuf = strchr(startBuf, 'w');
2075*0a6a1f1dSLionel Sambuc   assert((*wBuf == 'w') && "@throw: can't find 'w'");
2076*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, wBuf-startBuf+1, buf);
2077*0a6a1f1dSLionel Sambuc 
2078*0a6a1f1dSLionel Sambuc   SourceLocation endLoc = S->getLocEnd();
2079*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(endLoc);
2080*0a6a1f1dSLionel Sambuc   const char *semiBuf = strchr(endBuf, ';');
2081*0a6a1f1dSLionel Sambuc   assert((*semiBuf == ';') && "@throw: can't find ';'");
2082*0a6a1f1dSLionel Sambuc   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2083*0a6a1f1dSLionel Sambuc   if (S->getThrowExpr())
2084*0a6a1f1dSLionel Sambuc     ReplaceText(semiLoc, 1, ");");
2085*0a6a1f1dSLionel Sambuc   return nullptr;
2086*0a6a1f1dSLionel Sambuc }
2087*0a6a1f1dSLionel Sambuc 
RewriteAtEncode(ObjCEncodeExpr * Exp)2088*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2089*0a6a1f1dSLionel Sambuc   // Create a new string expression.
2090*0a6a1f1dSLionel Sambuc   std::string StrEncoding;
2091*0a6a1f1dSLionel Sambuc   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2092*0a6a1f1dSLionel Sambuc   Expr *Replacement = getStringLiteral(StrEncoding);
2093*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, Replacement);
2094*0a6a1f1dSLionel Sambuc 
2095*0a6a1f1dSLionel Sambuc   // Replace this subexpr in the parent.
2096*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2097*0a6a1f1dSLionel Sambuc   return Replacement;
2098*0a6a1f1dSLionel Sambuc }
2099*0a6a1f1dSLionel Sambuc 
RewriteAtSelector(ObjCSelectorExpr * Exp)2100*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2101*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
2102*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
2103*0a6a1f1dSLionel Sambuc   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2104*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("selName").
2105*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> SelExprs;
2106*0a6a1f1dSLionel Sambuc   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2107*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2108*0a6a1f1dSLionel Sambuc                                                  &SelExprs[0], SelExprs.size());
2109*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, SelExp);
2110*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2111*0a6a1f1dSLionel Sambuc   return SelExp;
2112*0a6a1f1dSLionel Sambuc }
2113*0a6a1f1dSLionel Sambuc 
SynthesizeCallToFunctionDecl(FunctionDecl * FD,Expr ** args,unsigned nargs,SourceLocation StartLoc,SourceLocation EndLoc)2114*0a6a1f1dSLionel Sambuc CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2115*0a6a1f1dSLionel Sambuc   FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2116*0a6a1f1dSLionel Sambuc                                                     SourceLocation EndLoc) {
2117*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2118*0a6a1f1dSLionel Sambuc   QualType msgSendType = FD->getType();
2119*0a6a1f1dSLionel Sambuc 
2120*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2121*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE =
2122*0a6a1f1dSLionel Sambuc     new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2123*0a6a1f1dSLionel Sambuc 
2124*0a6a1f1dSLionel Sambuc   // Now, we cast the reference to a pointer to the objc_msgSend type.
2125*0a6a1f1dSLionel Sambuc   QualType pToFunc = Context->getPointerType(msgSendType);
2126*0a6a1f1dSLionel Sambuc   ImplicitCastExpr *ICE =
2127*0a6a1f1dSLionel Sambuc     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2128*0a6a1f1dSLionel Sambuc                              DRE, nullptr, VK_RValue);
2129*0a6a1f1dSLionel Sambuc 
2130*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2131*0a6a1f1dSLionel Sambuc 
2132*0a6a1f1dSLionel Sambuc   CallExpr *Exp =
2133*0a6a1f1dSLionel Sambuc     new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
2134*0a6a1f1dSLionel Sambuc                            FT->getCallResultType(*Context),
2135*0a6a1f1dSLionel Sambuc                            VK_RValue, EndLoc);
2136*0a6a1f1dSLionel Sambuc   return Exp;
2137*0a6a1f1dSLionel Sambuc }
2138*0a6a1f1dSLionel Sambuc 
scanForProtocolRefs(const char * startBuf,const char * endBuf,const char * & startRef,const char * & endRef)2139*0a6a1f1dSLionel Sambuc static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2140*0a6a1f1dSLionel Sambuc                                 const char *&startRef, const char *&endRef) {
2141*0a6a1f1dSLionel Sambuc   while (startBuf < endBuf) {
2142*0a6a1f1dSLionel Sambuc     if (*startBuf == '<')
2143*0a6a1f1dSLionel Sambuc       startRef = startBuf; // mark the start.
2144*0a6a1f1dSLionel Sambuc     if (*startBuf == '>') {
2145*0a6a1f1dSLionel Sambuc       if (startRef && *startRef == '<') {
2146*0a6a1f1dSLionel Sambuc         endRef = startBuf; // mark the end.
2147*0a6a1f1dSLionel Sambuc         return true;
2148*0a6a1f1dSLionel Sambuc       }
2149*0a6a1f1dSLionel Sambuc       return false;
2150*0a6a1f1dSLionel Sambuc     }
2151*0a6a1f1dSLionel Sambuc     startBuf++;
2152*0a6a1f1dSLionel Sambuc   }
2153*0a6a1f1dSLionel Sambuc   return false;
2154*0a6a1f1dSLionel Sambuc }
2155*0a6a1f1dSLionel Sambuc 
scanToNextArgument(const char * & argRef)2156*0a6a1f1dSLionel Sambuc static void scanToNextArgument(const char *&argRef) {
2157*0a6a1f1dSLionel Sambuc   int angle = 0;
2158*0a6a1f1dSLionel Sambuc   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2159*0a6a1f1dSLionel Sambuc     if (*argRef == '<')
2160*0a6a1f1dSLionel Sambuc       angle++;
2161*0a6a1f1dSLionel Sambuc     else if (*argRef == '>')
2162*0a6a1f1dSLionel Sambuc       angle--;
2163*0a6a1f1dSLionel Sambuc     argRef++;
2164*0a6a1f1dSLionel Sambuc   }
2165*0a6a1f1dSLionel Sambuc   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2166*0a6a1f1dSLionel Sambuc }
2167*0a6a1f1dSLionel Sambuc 
needToScanForQualifiers(QualType T)2168*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2169*0a6a1f1dSLionel Sambuc   if (T->isObjCQualifiedIdType())
2170*0a6a1f1dSLionel Sambuc     return true;
2171*0a6a1f1dSLionel Sambuc   if (const PointerType *PT = T->getAs<PointerType>()) {
2172*0a6a1f1dSLionel Sambuc     if (PT->getPointeeType()->isObjCQualifiedIdType())
2173*0a6a1f1dSLionel Sambuc       return true;
2174*0a6a1f1dSLionel Sambuc   }
2175*0a6a1f1dSLionel Sambuc   if (T->isObjCObjectPointerType()) {
2176*0a6a1f1dSLionel Sambuc     T = T->getPointeeType();
2177*0a6a1f1dSLionel Sambuc     return T->isObjCQualifiedInterfaceType();
2178*0a6a1f1dSLionel Sambuc   }
2179*0a6a1f1dSLionel Sambuc   if (T->isArrayType()) {
2180*0a6a1f1dSLionel Sambuc     QualType ElemTy = Context->getBaseElementType(T);
2181*0a6a1f1dSLionel Sambuc     return needToScanForQualifiers(ElemTy);
2182*0a6a1f1dSLionel Sambuc   }
2183*0a6a1f1dSLionel Sambuc   return false;
2184*0a6a1f1dSLionel Sambuc }
2185*0a6a1f1dSLionel Sambuc 
RewriteObjCQualifiedInterfaceTypes(Expr * E)2186*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2187*0a6a1f1dSLionel Sambuc   QualType Type = E->getType();
2188*0a6a1f1dSLionel Sambuc   if (needToScanForQualifiers(Type)) {
2189*0a6a1f1dSLionel Sambuc     SourceLocation Loc, EndLoc;
2190*0a6a1f1dSLionel Sambuc 
2191*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2192*0a6a1f1dSLionel Sambuc       Loc = ECE->getLParenLoc();
2193*0a6a1f1dSLionel Sambuc       EndLoc = ECE->getRParenLoc();
2194*0a6a1f1dSLionel Sambuc     } else {
2195*0a6a1f1dSLionel Sambuc       Loc = E->getLocStart();
2196*0a6a1f1dSLionel Sambuc       EndLoc = E->getLocEnd();
2197*0a6a1f1dSLionel Sambuc     }
2198*0a6a1f1dSLionel Sambuc     // This will defend against trying to rewrite synthesized expressions.
2199*0a6a1f1dSLionel Sambuc     if (Loc.isInvalid() || EndLoc.isInvalid())
2200*0a6a1f1dSLionel Sambuc       return;
2201*0a6a1f1dSLionel Sambuc 
2202*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(Loc);
2203*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(EndLoc);
2204*0a6a1f1dSLionel Sambuc     const char *startRef = nullptr, *endRef = nullptr;
2205*0a6a1f1dSLionel Sambuc     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206*0a6a1f1dSLionel Sambuc       // Get the locations of the startRef, endRef.
2207*0a6a1f1dSLionel Sambuc       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2208*0a6a1f1dSLionel Sambuc       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2209*0a6a1f1dSLionel Sambuc       // Comment out the protocol references.
2210*0a6a1f1dSLionel Sambuc       InsertText(LessLoc, "/*");
2211*0a6a1f1dSLionel Sambuc       InsertText(GreaterLoc, "*/");
2212*0a6a1f1dSLionel Sambuc     }
2213*0a6a1f1dSLionel Sambuc   }
2214*0a6a1f1dSLionel Sambuc }
2215*0a6a1f1dSLionel Sambuc 
RewriteObjCQualifiedInterfaceTypes(Decl * Dcl)2216*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2217*0a6a1f1dSLionel Sambuc   SourceLocation Loc;
2218*0a6a1f1dSLionel Sambuc   QualType Type;
2219*0a6a1f1dSLionel Sambuc   const FunctionProtoType *proto = nullptr;
2220*0a6a1f1dSLionel Sambuc   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2221*0a6a1f1dSLionel Sambuc     Loc = VD->getLocation();
2222*0a6a1f1dSLionel Sambuc     Type = VD->getType();
2223*0a6a1f1dSLionel Sambuc   }
2224*0a6a1f1dSLionel Sambuc   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2225*0a6a1f1dSLionel Sambuc     Loc = FD->getLocation();
2226*0a6a1f1dSLionel Sambuc     // Check for ObjC 'id' and class types that have been adorned with protocol
2227*0a6a1f1dSLionel Sambuc     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2228*0a6a1f1dSLionel Sambuc     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2229*0a6a1f1dSLionel Sambuc     assert(funcType && "missing function type");
2230*0a6a1f1dSLionel Sambuc     proto = dyn_cast<FunctionProtoType>(funcType);
2231*0a6a1f1dSLionel Sambuc     if (!proto)
2232*0a6a1f1dSLionel Sambuc       return;
2233*0a6a1f1dSLionel Sambuc     Type = proto->getReturnType();
2234*0a6a1f1dSLionel Sambuc   }
2235*0a6a1f1dSLionel Sambuc   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2236*0a6a1f1dSLionel Sambuc     Loc = FD->getLocation();
2237*0a6a1f1dSLionel Sambuc     Type = FD->getType();
2238*0a6a1f1dSLionel Sambuc   }
2239*0a6a1f1dSLionel Sambuc   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2240*0a6a1f1dSLionel Sambuc     Loc = TD->getLocation();
2241*0a6a1f1dSLionel Sambuc     Type = TD->getUnderlyingType();
2242*0a6a1f1dSLionel Sambuc   }
2243*0a6a1f1dSLionel Sambuc   else
2244*0a6a1f1dSLionel Sambuc     return;
2245*0a6a1f1dSLionel Sambuc 
2246*0a6a1f1dSLionel Sambuc   if (needToScanForQualifiers(Type)) {
2247*0a6a1f1dSLionel Sambuc     // Since types are unique, we need to scan the buffer.
2248*0a6a1f1dSLionel Sambuc 
2249*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(Loc);
2250*0a6a1f1dSLionel Sambuc     const char *startBuf = endBuf;
2251*0a6a1f1dSLionel Sambuc     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2252*0a6a1f1dSLionel Sambuc       startBuf--; // scan backward (from the decl location) for return type.
2253*0a6a1f1dSLionel Sambuc     const char *startRef = nullptr, *endRef = nullptr;
2254*0a6a1f1dSLionel Sambuc     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255*0a6a1f1dSLionel Sambuc       // Get the locations of the startRef, endRef.
2256*0a6a1f1dSLionel Sambuc       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2257*0a6a1f1dSLionel Sambuc       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2258*0a6a1f1dSLionel Sambuc       // Comment out the protocol references.
2259*0a6a1f1dSLionel Sambuc       InsertText(LessLoc, "/*");
2260*0a6a1f1dSLionel Sambuc       InsertText(GreaterLoc, "*/");
2261*0a6a1f1dSLionel Sambuc     }
2262*0a6a1f1dSLionel Sambuc   }
2263*0a6a1f1dSLionel Sambuc   if (!proto)
2264*0a6a1f1dSLionel Sambuc       return; // most likely, was a variable
2265*0a6a1f1dSLionel Sambuc   // Now check arguments.
2266*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(Loc);
2267*0a6a1f1dSLionel Sambuc   const char *startFuncBuf = startBuf;
2268*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2269*0a6a1f1dSLionel Sambuc     if (needToScanForQualifiers(proto->getParamType(i))) {
2270*0a6a1f1dSLionel Sambuc       // Since types are unique, we need to scan the buffer.
2271*0a6a1f1dSLionel Sambuc 
2272*0a6a1f1dSLionel Sambuc       const char *endBuf = startBuf;
2273*0a6a1f1dSLionel Sambuc       // scan forward (from the decl location) for argument types.
2274*0a6a1f1dSLionel Sambuc       scanToNextArgument(endBuf);
2275*0a6a1f1dSLionel Sambuc       const char *startRef = nullptr, *endRef = nullptr;
2276*0a6a1f1dSLionel Sambuc       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2277*0a6a1f1dSLionel Sambuc         // Get the locations of the startRef, endRef.
2278*0a6a1f1dSLionel Sambuc         SourceLocation LessLoc =
2279*0a6a1f1dSLionel Sambuc           Loc.getLocWithOffset(startRef-startFuncBuf);
2280*0a6a1f1dSLionel Sambuc         SourceLocation GreaterLoc =
2281*0a6a1f1dSLionel Sambuc           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2282*0a6a1f1dSLionel Sambuc         // Comment out the protocol references.
2283*0a6a1f1dSLionel Sambuc         InsertText(LessLoc, "/*");
2284*0a6a1f1dSLionel Sambuc         InsertText(GreaterLoc, "*/");
2285*0a6a1f1dSLionel Sambuc       }
2286*0a6a1f1dSLionel Sambuc       startBuf = ++endBuf;
2287*0a6a1f1dSLionel Sambuc     }
2288*0a6a1f1dSLionel Sambuc     else {
2289*0a6a1f1dSLionel Sambuc       // If the function name is derived from a macro expansion, then the
2290*0a6a1f1dSLionel Sambuc       // argument buffer will not follow the name. Need to speak with Chris.
2291*0a6a1f1dSLionel Sambuc       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2292*0a6a1f1dSLionel Sambuc         startBuf++; // scan forward (from the decl location) for argument types.
2293*0a6a1f1dSLionel Sambuc       startBuf++;
2294*0a6a1f1dSLionel Sambuc     }
2295*0a6a1f1dSLionel Sambuc   }
2296*0a6a1f1dSLionel Sambuc }
2297*0a6a1f1dSLionel Sambuc 
RewriteTypeOfDecl(VarDecl * ND)2298*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2299*0a6a1f1dSLionel Sambuc   QualType QT = ND->getType();
2300*0a6a1f1dSLionel Sambuc   const Type* TypePtr = QT->getAs<Type>();
2301*0a6a1f1dSLionel Sambuc   if (!isa<TypeOfExprType>(TypePtr))
2302*0a6a1f1dSLionel Sambuc     return;
2303*0a6a1f1dSLionel Sambuc   while (isa<TypeOfExprType>(TypePtr)) {
2304*0a6a1f1dSLionel Sambuc     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2305*0a6a1f1dSLionel Sambuc     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2306*0a6a1f1dSLionel Sambuc     TypePtr = QT->getAs<Type>();
2307*0a6a1f1dSLionel Sambuc   }
2308*0a6a1f1dSLionel Sambuc   // FIXME. This will not work for multiple declarators; as in:
2309*0a6a1f1dSLionel Sambuc   // __typeof__(a) b,c,d;
2310*0a6a1f1dSLionel Sambuc   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2311*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2312*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
2313*0a6a1f1dSLionel Sambuc   if (ND->getInit()) {
2314*0a6a1f1dSLionel Sambuc     std::string Name(ND->getNameAsString());
2315*0a6a1f1dSLionel Sambuc     TypeAsString += " " + Name + " = ";
2316*0a6a1f1dSLionel Sambuc     Expr *E = ND->getInit();
2317*0a6a1f1dSLionel Sambuc     SourceLocation startLoc;
2318*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2319*0a6a1f1dSLionel Sambuc       startLoc = ECE->getLParenLoc();
2320*0a6a1f1dSLionel Sambuc     else
2321*0a6a1f1dSLionel Sambuc       startLoc = E->getLocStart();
2322*0a6a1f1dSLionel Sambuc     startLoc = SM->getExpansionLoc(startLoc);
2323*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(startLoc);
2324*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2325*0a6a1f1dSLionel Sambuc   }
2326*0a6a1f1dSLionel Sambuc   else {
2327*0a6a1f1dSLionel Sambuc     SourceLocation X = ND->getLocEnd();
2328*0a6a1f1dSLionel Sambuc     X = SM->getExpansionLoc(X);
2329*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(X);
2330*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2331*0a6a1f1dSLionel Sambuc   }
2332*0a6a1f1dSLionel Sambuc }
2333*0a6a1f1dSLionel Sambuc 
2334*0a6a1f1dSLionel Sambuc // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
SynthSelGetUidFunctionDecl()2335*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2336*0a6a1f1dSLionel Sambuc   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2337*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2338*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2339*0a6a1f1dSLionel Sambuc   QualType getFuncType =
2340*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2341*0a6a1f1dSLionel Sambuc   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2342*0a6a1f1dSLionel Sambuc                                                SourceLocation(),
2343*0a6a1f1dSLionel Sambuc                                                SourceLocation(),
2344*0a6a1f1dSLionel Sambuc                                                SelGetUidIdent, getFuncType,
2345*0a6a1f1dSLionel Sambuc                                                nullptr, SC_Extern);
2346*0a6a1f1dSLionel Sambuc }
2347*0a6a1f1dSLionel Sambuc 
RewriteFunctionDecl(FunctionDecl * FD)2348*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2349*0a6a1f1dSLionel Sambuc   // declared in <objc/objc.h>
2350*0a6a1f1dSLionel Sambuc   if (FD->getIdentifier() &&
2351*0a6a1f1dSLionel Sambuc       FD->getName() == "sel_registerName") {
2352*0a6a1f1dSLionel Sambuc     SelGetUidFunctionDecl = FD;
2353*0a6a1f1dSLionel Sambuc     return;
2354*0a6a1f1dSLionel Sambuc   }
2355*0a6a1f1dSLionel Sambuc   RewriteObjCQualifiedInterfaceTypes(FD);
2356*0a6a1f1dSLionel Sambuc }
2357*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerType(std::string & Str,QualType Type)2358*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2359*0a6a1f1dSLionel Sambuc   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2360*0a6a1f1dSLionel Sambuc   const char *argPtr = TypeString.c_str();
2361*0a6a1f1dSLionel Sambuc   if (!strchr(argPtr, '^')) {
2362*0a6a1f1dSLionel Sambuc     Str += TypeString;
2363*0a6a1f1dSLionel Sambuc     return;
2364*0a6a1f1dSLionel Sambuc   }
2365*0a6a1f1dSLionel Sambuc   while (*argPtr) {
2366*0a6a1f1dSLionel Sambuc     Str += (*argPtr == '^' ? '*' : *argPtr);
2367*0a6a1f1dSLionel Sambuc     argPtr++;
2368*0a6a1f1dSLionel Sambuc   }
2369*0a6a1f1dSLionel Sambuc }
2370*0a6a1f1dSLionel Sambuc 
2371*0a6a1f1dSLionel Sambuc // FIXME. Consolidate this routine with RewriteBlockPointerType.
RewriteBlockPointerTypeVariable(std::string & Str,ValueDecl * VD)2372*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2373*0a6a1f1dSLionel Sambuc                                                   ValueDecl *VD) {
2374*0a6a1f1dSLionel Sambuc   QualType Type = VD->getType();
2375*0a6a1f1dSLionel Sambuc   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2376*0a6a1f1dSLionel Sambuc   const char *argPtr = TypeString.c_str();
2377*0a6a1f1dSLionel Sambuc   int paren = 0;
2378*0a6a1f1dSLionel Sambuc   while (*argPtr) {
2379*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
2380*0a6a1f1dSLionel Sambuc       case '(':
2381*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2382*0a6a1f1dSLionel Sambuc         paren++;
2383*0a6a1f1dSLionel Sambuc         break;
2384*0a6a1f1dSLionel Sambuc       case ')':
2385*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2386*0a6a1f1dSLionel Sambuc         paren--;
2387*0a6a1f1dSLionel Sambuc         break;
2388*0a6a1f1dSLionel Sambuc       case '^':
2389*0a6a1f1dSLionel Sambuc         Str += '*';
2390*0a6a1f1dSLionel Sambuc         if (paren == 1)
2391*0a6a1f1dSLionel Sambuc           Str += VD->getNameAsString();
2392*0a6a1f1dSLionel Sambuc         break;
2393*0a6a1f1dSLionel Sambuc       default:
2394*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2395*0a6a1f1dSLionel Sambuc         break;
2396*0a6a1f1dSLionel Sambuc     }
2397*0a6a1f1dSLionel Sambuc     argPtr++;
2398*0a6a1f1dSLionel Sambuc   }
2399*0a6a1f1dSLionel Sambuc }
2400*0a6a1f1dSLionel Sambuc 
RewriteBlockLiteralFunctionDecl(FunctionDecl * FD)2401*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2402*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2403*0a6a1f1dSLionel Sambuc   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2404*0a6a1f1dSLionel Sambuc   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2405*0a6a1f1dSLionel Sambuc   if (!proto)
2406*0a6a1f1dSLionel Sambuc     return;
2407*0a6a1f1dSLionel Sambuc   QualType Type = proto->getReturnType();
2408*0a6a1f1dSLionel Sambuc   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2409*0a6a1f1dSLionel Sambuc   FdStr += " ";
2410*0a6a1f1dSLionel Sambuc   FdStr += FD->getName();
2411*0a6a1f1dSLionel Sambuc   FdStr +=  "(";
2412*0a6a1f1dSLionel Sambuc   unsigned numArgs = proto->getNumParams();
2413*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < numArgs; i++) {
2414*0a6a1f1dSLionel Sambuc     QualType ArgType = proto->getParamType(i);
2415*0a6a1f1dSLionel Sambuc   RewriteBlockPointerType(FdStr, ArgType);
2416*0a6a1f1dSLionel Sambuc   if (i+1 < numArgs)
2417*0a6a1f1dSLionel Sambuc     FdStr += ", ";
2418*0a6a1f1dSLionel Sambuc   }
2419*0a6a1f1dSLionel Sambuc   if (FD->isVariadic()) {
2420*0a6a1f1dSLionel Sambuc     FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
2421*0a6a1f1dSLionel Sambuc   }
2422*0a6a1f1dSLionel Sambuc   else
2423*0a6a1f1dSLionel Sambuc     FdStr +=  ");\n";
2424*0a6a1f1dSLionel Sambuc   InsertText(FunLocStart, FdStr);
2425*0a6a1f1dSLionel Sambuc }
2426*0a6a1f1dSLionel Sambuc 
2427*0a6a1f1dSLionel Sambuc // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
SynthSuperConstructorFunctionDecl()2428*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2429*0a6a1f1dSLionel Sambuc   if (SuperConstructorFunctionDecl)
2430*0a6a1f1dSLionel Sambuc     return;
2431*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2432*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2433*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2434*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2435*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2436*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2437*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2438*0a6a1f1dSLionel Sambuc                                                ArgTys);
2439*0a6a1f1dSLionel Sambuc   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2440*0a6a1f1dSLionel Sambuc                                                      SourceLocation(),
2441*0a6a1f1dSLionel Sambuc                                                      SourceLocation(),
2442*0a6a1f1dSLionel Sambuc                                                      msgSendIdent, msgSendType,
2443*0a6a1f1dSLionel Sambuc                                                      nullptr, SC_Extern);
2444*0a6a1f1dSLionel Sambuc }
2445*0a6a1f1dSLionel Sambuc 
2446*0a6a1f1dSLionel Sambuc // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
SynthMsgSendFunctionDecl()2447*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2448*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2449*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2450*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2451*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2452*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2453*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2454*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2455*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2456*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2457*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2458*0a6a1f1dSLionel Sambuc   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2459*0a6a1f1dSLionel Sambuc                                              SourceLocation(),
2460*0a6a1f1dSLionel Sambuc                                              SourceLocation(),
2461*0a6a1f1dSLionel Sambuc                                              msgSendIdent, msgSendType, nullptr,
2462*0a6a1f1dSLionel Sambuc                                              SC_Extern);
2463*0a6a1f1dSLionel Sambuc }
2464*0a6a1f1dSLionel Sambuc 
2465*0a6a1f1dSLionel Sambuc // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
SynthMsgSendSuperFunctionDecl()2466*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2467*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2468*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 2> ArgTys;
2469*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->VoidTy);
2470*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2471*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2472*0a6a1f1dSLionel Sambuc   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2473*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2474*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2475*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2476*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2477*0a6a1f1dSLionel Sambuc }
2478*0a6a1f1dSLionel Sambuc 
2479*0a6a1f1dSLionel Sambuc // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
SynthMsgSendStretFunctionDecl()2480*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2481*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2482*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2483*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2484*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2485*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2486*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2487*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2488*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2489*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2490*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2491*0a6a1f1dSLionel Sambuc   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2492*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2493*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2494*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2495*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2496*0a6a1f1dSLionel Sambuc }
2497*0a6a1f1dSLionel Sambuc 
2498*0a6a1f1dSLionel Sambuc // SynthMsgSendSuperStretFunctionDecl -
2499*0a6a1f1dSLionel Sambuc // id objc_msgSendSuper_stret(void);
SynthMsgSendSuperStretFunctionDecl()2500*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2501*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent =
2502*0a6a1f1dSLionel Sambuc     &Context->Idents.get("objc_msgSendSuper_stret");
2503*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 2> ArgTys;
2504*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->VoidTy);
2505*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2506*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2507*0a6a1f1dSLionel Sambuc   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508*0a6a1f1dSLionel Sambuc                                                        SourceLocation(),
2509*0a6a1f1dSLionel Sambuc                                                        SourceLocation(),
2510*0a6a1f1dSLionel Sambuc                                                        msgSendIdent,
2511*0a6a1f1dSLionel Sambuc                                                        msgSendType, nullptr,
2512*0a6a1f1dSLionel Sambuc                                                        SC_Extern);
2513*0a6a1f1dSLionel Sambuc }
2514*0a6a1f1dSLionel Sambuc 
2515*0a6a1f1dSLionel Sambuc // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
SynthMsgSendFpretFunctionDecl()2516*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2517*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2518*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2519*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2520*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2521*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2522*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2523*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2524*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2525*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2526*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2527*0a6a1f1dSLionel Sambuc   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2528*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2529*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2530*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2531*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2532*0a6a1f1dSLionel Sambuc }
2533*0a6a1f1dSLionel Sambuc 
2534*0a6a1f1dSLionel Sambuc // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
SynthGetClassFunctionDecl()2535*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthGetClassFunctionDecl() {
2536*0a6a1f1dSLionel Sambuc   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2537*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2538*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2539*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2540*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2541*0a6a1f1dSLionel Sambuc   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2542*0a6a1f1dSLionel Sambuc                                               SourceLocation(),
2543*0a6a1f1dSLionel Sambuc                                               SourceLocation(),
2544*0a6a1f1dSLionel Sambuc                                               getClassIdent, getClassType,
2545*0a6a1f1dSLionel Sambuc                                               nullptr, SC_Extern);
2546*0a6a1f1dSLionel Sambuc }
2547*0a6a1f1dSLionel Sambuc 
2548*0a6a1f1dSLionel Sambuc // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
SynthGetSuperClassFunctionDecl()2549*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2550*0a6a1f1dSLionel Sambuc   IdentifierInfo *getSuperClassIdent =
2551*0a6a1f1dSLionel Sambuc     &Context->Idents.get("class_getSuperclass");
2552*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2553*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getObjCClassType());
2554*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2555*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2556*0a6a1f1dSLionel Sambuc   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2557*0a6a1f1dSLionel Sambuc                                                    SourceLocation(),
2558*0a6a1f1dSLionel Sambuc                                                    SourceLocation(),
2559*0a6a1f1dSLionel Sambuc                                                    getSuperClassIdent,
2560*0a6a1f1dSLionel Sambuc                                                    getClassType, nullptr,
2561*0a6a1f1dSLionel Sambuc                                                    SC_Extern);
2562*0a6a1f1dSLionel Sambuc }
2563*0a6a1f1dSLionel Sambuc 
2564*0a6a1f1dSLionel Sambuc // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
SynthGetMetaClassFunctionDecl()2565*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2566*0a6a1f1dSLionel Sambuc   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2567*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2568*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2569*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2570*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2571*0a6a1f1dSLionel Sambuc   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2572*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2573*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2574*0a6a1f1dSLionel Sambuc                                                   getClassIdent, getClassType,
2575*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2576*0a6a1f1dSLionel Sambuc }
2577*0a6a1f1dSLionel Sambuc 
RewriteObjCStringLiteral(ObjCStringLiteral * Exp)2578*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2579*0a6a1f1dSLionel Sambuc   assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2580*0a6a1f1dSLionel Sambuc   QualType strType = getConstantStringStructType();
2581*0a6a1f1dSLionel Sambuc 
2582*0a6a1f1dSLionel Sambuc   std::string S = "__NSConstantStringImpl_";
2583*0a6a1f1dSLionel Sambuc 
2584*0a6a1f1dSLionel Sambuc   std::string tmpName = InFileName;
2585*0a6a1f1dSLionel Sambuc   unsigned i;
2586*0a6a1f1dSLionel Sambuc   for (i=0; i < tmpName.length(); i++) {
2587*0a6a1f1dSLionel Sambuc     char c = tmpName.at(i);
2588*0a6a1f1dSLionel Sambuc     // replace any non-alphanumeric characters with '_'.
2589*0a6a1f1dSLionel Sambuc     if (!isAlphanumeric(c))
2590*0a6a1f1dSLionel Sambuc       tmpName[i] = '_';
2591*0a6a1f1dSLionel Sambuc   }
2592*0a6a1f1dSLionel Sambuc   S += tmpName;
2593*0a6a1f1dSLionel Sambuc   S += "_";
2594*0a6a1f1dSLionel Sambuc   S += utostr(NumObjCStringLiterals++);
2595*0a6a1f1dSLionel Sambuc 
2596*0a6a1f1dSLionel Sambuc   Preamble += "static __NSConstantStringImpl " + S;
2597*0a6a1f1dSLionel Sambuc   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2598*0a6a1f1dSLionel Sambuc   Preamble += "0x000007c8,"; // utf8_str
2599*0a6a1f1dSLionel Sambuc   // The pretty printer for StringLiteral handles escape characters properly.
2600*0a6a1f1dSLionel Sambuc   std::string prettyBufS;
2601*0a6a1f1dSLionel Sambuc   llvm::raw_string_ostream prettyBuf(prettyBufS);
2602*0a6a1f1dSLionel Sambuc   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2603*0a6a1f1dSLionel Sambuc   Preamble += prettyBuf.str();
2604*0a6a1f1dSLionel Sambuc   Preamble += ",";
2605*0a6a1f1dSLionel Sambuc   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2606*0a6a1f1dSLionel Sambuc 
2607*0a6a1f1dSLionel Sambuc   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2608*0a6a1f1dSLionel Sambuc                                    SourceLocation(), &Context->Idents.get(S),
2609*0a6a1f1dSLionel Sambuc                                    strType, nullptr, SC_Static);
2610*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2611*0a6a1f1dSLionel Sambuc                                                SourceLocation());
2612*0a6a1f1dSLionel Sambuc   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2613*0a6a1f1dSLionel Sambuc                                  Context->getPointerType(DRE->getType()),
2614*0a6a1f1dSLionel Sambuc                                            VK_RValue, OK_Ordinary,
2615*0a6a1f1dSLionel Sambuc                                            SourceLocation());
2616*0a6a1f1dSLionel Sambuc   // cast to NSConstantString *
2617*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2618*0a6a1f1dSLionel Sambuc                                             CK_CPointerToObjCPointerCast, Unop);
2619*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, cast);
2620*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2621*0a6a1f1dSLionel Sambuc   return cast;
2622*0a6a1f1dSLionel Sambuc }
2623*0a6a1f1dSLionel Sambuc 
RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr * Exp)2624*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2625*0a6a1f1dSLionel Sambuc   unsigned IntSize =
2626*0a6a1f1dSLionel Sambuc     static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2627*0a6a1f1dSLionel Sambuc 
2628*0a6a1f1dSLionel Sambuc   Expr *FlagExp = IntegerLiteral::Create(*Context,
2629*0a6a1f1dSLionel Sambuc                                          llvm::APInt(IntSize, Exp->getValue()),
2630*0a6a1f1dSLionel Sambuc                                          Context->IntTy, Exp->getLocation());
2631*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2632*0a6a1f1dSLionel Sambuc                                             CK_BitCast, FlagExp);
2633*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2634*0a6a1f1dSLionel Sambuc                                           cast);
2635*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, PE);
2636*0a6a1f1dSLionel Sambuc   return PE;
2637*0a6a1f1dSLionel Sambuc }
2638*0a6a1f1dSLionel Sambuc 
RewriteObjCBoxedExpr(ObjCBoxedExpr * Exp)2639*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2640*0a6a1f1dSLionel Sambuc   // synthesize declaration of helper functions needed in this routine.
2641*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
2642*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
2643*0a6a1f1dSLionel Sambuc   // use objc_msgSend() for all.
2644*0a6a1f1dSLionel Sambuc   if (!MsgSendFunctionDecl)
2645*0a6a1f1dSLionel Sambuc     SynthMsgSendFunctionDecl();
2646*0a6a1f1dSLionel Sambuc   if (!GetClassFunctionDecl)
2647*0a6a1f1dSLionel Sambuc     SynthGetClassFunctionDecl();
2648*0a6a1f1dSLionel Sambuc 
2649*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2650*0a6a1f1dSLionel Sambuc   SourceLocation StartLoc = Exp->getLocStart();
2651*0a6a1f1dSLionel Sambuc   SourceLocation EndLoc = Exp->getLocEnd();
2652*0a6a1f1dSLionel Sambuc 
2653*0a6a1f1dSLionel Sambuc   // Synthesize a call to objc_msgSend().
2654*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> MsgExprs;
2655*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> ClsExprs;
2656*0a6a1f1dSLionel Sambuc 
2657*0a6a1f1dSLionel Sambuc   // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2658*0a6a1f1dSLionel Sambuc   ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2659*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2660*0a6a1f1dSLionel Sambuc 
2661*0a6a1f1dSLionel Sambuc   IdentifierInfo *clsName = BoxingClass->getIdentifier();
2662*0a6a1f1dSLionel Sambuc   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2663*0a6a1f1dSLionel Sambuc   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2664*0a6a1f1dSLionel Sambuc                                                &ClsExprs[0],
2665*0a6a1f1dSLionel Sambuc                                                ClsExprs.size(),
2666*0a6a1f1dSLionel Sambuc                                                StartLoc, EndLoc);
2667*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(Cls);
2668*0a6a1f1dSLionel Sambuc 
2669*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2670*0a6a1f1dSLionel Sambuc   // it will be the 2nd argument.
2671*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> SelExprs;
2672*0a6a1f1dSLionel Sambuc   SelExprs.push_back(
2673*0a6a1f1dSLionel Sambuc       getStringLiteral(BoxingMethod->getSelector().getAsString()));
2674*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2675*0a6a1f1dSLionel Sambuc                                                   &SelExprs[0], SelExprs.size(),
2676*0a6a1f1dSLionel Sambuc                                                   StartLoc, EndLoc);
2677*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(SelExp);
2678*0a6a1f1dSLionel Sambuc 
2679*0a6a1f1dSLionel Sambuc   // User provided sub-expression is the 3rd, and last, argument.
2680*0a6a1f1dSLionel Sambuc   Expr *subExpr  = Exp->getSubExpr();
2681*0a6a1f1dSLionel Sambuc   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2682*0a6a1f1dSLionel Sambuc     QualType type = ICE->getType();
2683*0a6a1f1dSLionel Sambuc     const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2684*0a6a1f1dSLionel Sambuc     CastKind CK = CK_BitCast;
2685*0a6a1f1dSLionel Sambuc     if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2686*0a6a1f1dSLionel Sambuc       CK = CK_IntegralToBoolean;
2687*0a6a1f1dSLionel Sambuc     subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2688*0a6a1f1dSLionel Sambuc   }
2689*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(subExpr);
2690*0a6a1f1dSLionel Sambuc 
2691*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 4> ArgTypes;
2692*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCIdType());
2693*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCSelType());
2694*0a6a1f1dSLionel Sambuc   for (const auto PI : BoxingMethod->parameters())
2695*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(PI->getType());
2696*0a6a1f1dSLionel Sambuc 
2697*0a6a1f1dSLionel Sambuc   QualType returnType = Exp->getType();
2698*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2699*0a6a1f1dSLionel Sambuc   QualType msgSendType = MsgSendFlavor->getType();
2700*0a6a1f1dSLionel Sambuc 
2701*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2702*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2703*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
2704*0a6a1f1dSLionel Sambuc 
2705*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2706*0a6a1f1dSLionel Sambuc                                             Context->getPointerType(Context->VoidTy),
2707*0a6a1f1dSLionel Sambuc                                             CK_BitCast, DRE);
2708*0a6a1f1dSLionel Sambuc 
2709*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
2710*0a6a1f1dSLionel Sambuc   QualType castType =
2711*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2712*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
2713*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2714*0a6a1f1dSLionel Sambuc                                   cast);
2715*0a6a1f1dSLionel Sambuc 
2716*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
2717*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2718*0a6a1f1dSLionel Sambuc 
2719*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2720*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context)
2721*0a6a1f1dSLionel Sambuc       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2722*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, CE);
2723*0a6a1f1dSLionel Sambuc   return CE;
2724*0a6a1f1dSLionel Sambuc }
2725*0a6a1f1dSLionel Sambuc 
RewriteObjCArrayLiteralExpr(ObjCArrayLiteral * Exp)2726*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2727*0a6a1f1dSLionel Sambuc   // synthesize declaration of helper functions needed in this routine.
2728*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
2729*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
2730*0a6a1f1dSLionel Sambuc   // use objc_msgSend() for all.
2731*0a6a1f1dSLionel Sambuc   if (!MsgSendFunctionDecl)
2732*0a6a1f1dSLionel Sambuc     SynthMsgSendFunctionDecl();
2733*0a6a1f1dSLionel Sambuc   if (!GetClassFunctionDecl)
2734*0a6a1f1dSLionel Sambuc     SynthGetClassFunctionDecl();
2735*0a6a1f1dSLionel Sambuc 
2736*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2737*0a6a1f1dSLionel Sambuc   SourceLocation StartLoc = Exp->getLocStart();
2738*0a6a1f1dSLionel Sambuc   SourceLocation EndLoc = Exp->getLocEnd();
2739*0a6a1f1dSLionel Sambuc 
2740*0a6a1f1dSLionel Sambuc   // Build the expression: __NSContainer_literal(int, ...).arr
2741*0a6a1f1dSLionel Sambuc   QualType IntQT = Context->IntTy;
2742*0a6a1f1dSLionel Sambuc   QualType NSArrayFType =
2743*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2744*0a6a1f1dSLionel Sambuc   std::string NSArrayFName("__NSContainer_literal");
2745*0a6a1f1dSLionel Sambuc   FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2746*0a6a1f1dSLionel Sambuc   DeclRefExpr *NSArrayDRE =
2747*0a6a1f1dSLionel Sambuc     new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2748*0a6a1f1dSLionel Sambuc                               SourceLocation());
2749*0a6a1f1dSLionel Sambuc 
2750*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 16> InitExprs;
2751*0a6a1f1dSLionel Sambuc   unsigned NumElements = Exp->getNumElements();
2752*0a6a1f1dSLionel Sambuc   unsigned UnsignedIntSize =
2753*0a6a1f1dSLionel Sambuc     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2754*0a6a1f1dSLionel Sambuc   Expr *count = IntegerLiteral::Create(*Context,
2755*0a6a1f1dSLionel Sambuc                                        llvm::APInt(UnsignedIntSize, NumElements),
2756*0a6a1f1dSLionel Sambuc                                        Context->UnsignedIntTy, SourceLocation());
2757*0a6a1f1dSLionel Sambuc   InitExprs.push_back(count);
2758*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < NumElements; i++)
2759*0a6a1f1dSLionel Sambuc     InitExprs.push_back(Exp->getElement(i));
2760*0a6a1f1dSLionel Sambuc   Expr *NSArrayCallExpr =
2761*0a6a1f1dSLionel Sambuc     new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2762*0a6a1f1dSLionel Sambuc                            NSArrayFType, VK_LValue, SourceLocation());
2763*0a6a1f1dSLionel Sambuc 
2764*0a6a1f1dSLionel Sambuc   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2765*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
2766*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("arr"),
2767*0a6a1f1dSLionel Sambuc                                     Context->getPointerType(Context->VoidPtrTy),
2768*0a6a1f1dSLionel Sambuc                                     nullptr, /*BitWidth=*/nullptr,
2769*0a6a1f1dSLionel Sambuc                                     /*Mutable=*/true, ICIS_NoInit);
2770*0a6a1f1dSLionel Sambuc   MemberExpr *ArrayLiteralME =
2771*0a6a1f1dSLionel Sambuc     new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2772*0a6a1f1dSLionel Sambuc                              SourceLocation(),
2773*0a6a1f1dSLionel Sambuc                              ARRFD->getType(), VK_LValue,
2774*0a6a1f1dSLionel Sambuc                              OK_Ordinary);
2775*0a6a1f1dSLionel Sambuc   QualType ConstIdT = Context->getObjCIdType().withConst();
2776*0a6a1f1dSLionel Sambuc   CStyleCastExpr * ArrayLiteralObjects =
2777*0a6a1f1dSLionel Sambuc     NoTypeInfoCStyleCastExpr(Context,
2778*0a6a1f1dSLionel Sambuc                              Context->getPointerType(ConstIdT),
2779*0a6a1f1dSLionel Sambuc                              CK_BitCast,
2780*0a6a1f1dSLionel Sambuc                              ArrayLiteralME);
2781*0a6a1f1dSLionel Sambuc 
2782*0a6a1f1dSLionel Sambuc   // Synthesize a call to objc_msgSend().
2783*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 32> MsgExprs;
2784*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> ClsExprs;
2785*0a6a1f1dSLionel Sambuc   QualType expType = Exp->getType();
2786*0a6a1f1dSLionel Sambuc 
2787*0a6a1f1dSLionel Sambuc   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2788*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *Class =
2789*0a6a1f1dSLionel Sambuc     expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2790*0a6a1f1dSLionel Sambuc 
2791*0a6a1f1dSLionel Sambuc   IdentifierInfo *clsName = Class->getIdentifier();
2792*0a6a1f1dSLionel Sambuc   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2793*0a6a1f1dSLionel Sambuc   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2794*0a6a1f1dSLionel Sambuc                                                &ClsExprs[0],
2795*0a6a1f1dSLionel Sambuc                                                ClsExprs.size(),
2796*0a6a1f1dSLionel Sambuc                                                StartLoc, EndLoc);
2797*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(Cls);
2798*0a6a1f1dSLionel Sambuc 
2799*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("arrayWithObjects:count:").
2800*0a6a1f1dSLionel Sambuc   // it will be the 2nd argument.
2801*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> SelExprs;
2802*0a6a1f1dSLionel Sambuc   ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2803*0a6a1f1dSLionel Sambuc   SelExprs.push_back(
2804*0a6a1f1dSLionel Sambuc       getStringLiteral(ArrayMethod->getSelector().getAsString()));
2805*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2806*0a6a1f1dSLionel Sambuc                                                   &SelExprs[0], SelExprs.size(),
2807*0a6a1f1dSLionel Sambuc                                                   StartLoc, EndLoc);
2808*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(SelExp);
2809*0a6a1f1dSLionel Sambuc 
2810*0a6a1f1dSLionel Sambuc   // (const id [])objects
2811*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(ArrayLiteralObjects);
2812*0a6a1f1dSLionel Sambuc 
2813*0a6a1f1dSLionel Sambuc   // (NSUInteger)cnt
2814*0a6a1f1dSLionel Sambuc   Expr *cnt = IntegerLiteral::Create(*Context,
2815*0a6a1f1dSLionel Sambuc                                      llvm::APInt(UnsignedIntSize, NumElements),
2816*0a6a1f1dSLionel Sambuc                                      Context->UnsignedIntTy, SourceLocation());
2817*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(cnt);
2818*0a6a1f1dSLionel Sambuc 
2819*0a6a1f1dSLionel Sambuc 
2820*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 4> ArgTypes;
2821*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCIdType());
2822*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCSelType());
2823*0a6a1f1dSLionel Sambuc   for (const auto *PI : ArrayMethod->params())
2824*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(PI->getType());
2825*0a6a1f1dSLionel Sambuc 
2826*0a6a1f1dSLionel Sambuc   QualType returnType = Exp->getType();
2827*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2828*0a6a1f1dSLionel Sambuc   QualType msgSendType = MsgSendFlavor->getType();
2829*0a6a1f1dSLionel Sambuc 
2830*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2831*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2832*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
2833*0a6a1f1dSLionel Sambuc 
2834*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2835*0a6a1f1dSLionel Sambuc                                             Context->getPointerType(Context->VoidTy),
2836*0a6a1f1dSLionel Sambuc                                             CK_BitCast, DRE);
2837*0a6a1f1dSLionel Sambuc 
2838*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
2839*0a6a1f1dSLionel Sambuc   QualType castType =
2840*0a6a1f1dSLionel Sambuc   getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2841*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
2842*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2843*0a6a1f1dSLionel Sambuc                                   cast);
2844*0a6a1f1dSLionel Sambuc 
2845*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
2846*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2847*0a6a1f1dSLionel Sambuc 
2848*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2849*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context)
2850*0a6a1f1dSLionel Sambuc       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2851*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, CE);
2852*0a6a1f1dSLionel Sambuc   return CE;
2853*0a6a1f1dSLionel Sambuc }
2854*0a6a1f1dSLionel Sambuc 
RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral * Exp)2855*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2856*0a6a1f1dSLionel Sambuc   // synthesize declaration of helper functions needed in this routine.
2857*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
2858*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
2859*0a6a1f1dSLionel Sambuc   // use objc_msgSend() for all.
2860*0a6a1f1dSLionel Sambuc   if (!MsgSendFunctionDecl)
2861*0a6a1f1dSLionel Sambuc     SynthMsgSendFunctionDecl();
2862*0a6a1f1dSLionel Sambuc   if (!GetClassFunctionDecl)
2863*0a6a1f1dSLionel Sambuc     SynthGetClassFunctionDecl();
2864*0a6a1f1dSLionel Sambuc 
2865*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2866*0a6a1f1dSLionel Sambuc   SourceLocation StartLoc = Exp->getLocStart();
2867*0a6a1f1dSLionel Sambuc   SourceLocation EndLoc = Exp->getLocEnd();
2868*0a6a1f1dSLionel Sambuc 
2869*0a6a1f1dSLionel Sambuc   // Build the expression: __NSContainer_literal(int, ...).arr
2870*0a6a1f1dSLionel Sambuc   QualType IntQT = Context->IntTy;
2871*0a6a1f1dSLionel Sambuc   QualType NSDictFType =
2872*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2873*0a6a1f1dSLionel Sambuc   std::string NSDictFName("__NSContainer_literal");
2874*0a6a1f1dSLionel Sambuc   FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2875*0a6a1f1dSLionel Sambuc   DeclRefExpr *NSDictDRE =
2876*0a6a1f1dSLionel Sambuc     new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2877*0a6a1f1dSLionel Sambuc                               SourceLocation());
2878*0a6a1f1dSLionel Sambuc 
2879*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 16> KeyExprs;
2880*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 16> ValueExprs;
2881*0a6a1f1dSLionel Sambuc 
2882*0a6a1f1dSLionel Sambuc   unsigned NumElements = Exp->getNumElements();
2883*0a6a1f1dSLionel Sambuc   unsigned UnsignedIntSize =
2884*0a6a1f1dSLionel Sambuc     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2885*0a6a1f1dSLionel Sambuc   Expr *count = IntegerLiteral::Create(*Context,
2886*0a6a1f1dSLionel Sambuc                                        llvm::APInt(UnsignedIntSize, NumElements),
2887*0a6a1f1dSLionel Sambuc                                        Context->UnsignedIntTy, SourceLocation());
2888*0a6a1f1dSLionel Sambuc   KeyExprs.push_back(count);
2889*0a6a1f1dSLionel Sambuc   ValueExprs.push_back(count);
2890*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < NumElements; i++) {
2891*0a6a1f1dSLionel Sambuc     ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2892*0a6a1f1dSLionel Sambuc     KeyExprs.push_back(Element.Key);
2893*0a6a1f1dSLionel Sambuc     ValueExprs.push_back(Element.Value);
2894*0a6a1f1dSLionel Sambuc   }
2895*0a6a1f1dSLionel Sambuc 
2896*0a6a1f1dSLionel Sambuc   // (const id [])objects
2897*0a6a1f1dSLionel Sambuc   Expr *NSValueCallExpr =
2898*0a6a1f1dSLionel Sambuc     new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2899*0a6a1f1dSLionel Sambuc                            NSDictFType, VK_LValue, SourceLocation());
2900*0a6a1f1dSLionel Sambuc 
2901*0a6a1f1dSLionel Sambuc   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2902*0a6a1f1dSLionel Sambuc                                        SourceLocation(),
2903*0a6a1f1dSLionel Sambuc                                        &Context->Idents.get("arr"),
2904*0a6a1f1dSLionel Sambuc                                        Context->getPointerType(Context->VoidPtrTy),
2905*0a6a1f1dSLionel Sambuc                                        nullptr, /*BitWidth=*/nullptr,
2906*0a6a1f1dSLionel Sambuc                                        /*Mutable=*/true, ICIS_NoInit);
2907*0a6a1f1dSLionel Sambuc   MemberExpr *DictLiteralValueME =
2908*0a6a1f1dSLionel Sambuc     new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2909*0a6a1f1dSLionel Sambuc                              SourceLocation(),
2910*0a6a1f1dSLionel Sambuc                              ARRFD->getType(), VK_LValue,
2911*0a6a1f1dSLionel Sambuc                              OK_Ordinary);
2912*0a6a1f1dSLionel Sambuc   QualType ConstIdT = Context->getObjCIdType().withConst();
2913*0a6a1f1dSLionel Sambuc   CStyleCastExpr * DictValueObjects =
2914*0a6a1f1dSLionel Sambuc     NoTypeInfoCStyleCastExpr(Context,
2915*0a6a1f1dSLionel Sambuc                              Context->getPointerType(ConstIdT),
2916*0a6a1f1dSLionel Sambuc                              CK_BitCast,
2917*0a6a1f1dSLionel Sambuc                              DictLiteralValueME);
2918*0a6a1f1dSLionel Sambuc   // (const id <NSCopying> [])keys
2919*0a6a1f1dSLionel Sambuc   Expr *NSKeyCallExpr =
2920*0a6a1f1dSLionel Sambuc     new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2921*0a6a1f1dSLionel Sambuc                            NSDictFType, VK_LValue, SourceLocation());
2922*0a6a1f1dSLionel Sambuc 
2923*0a6a1f1dSLionel Sambuc   MemberExpr *DictLiteralKeyME =
2924*0a6a1f1dSLionel Sambuc     new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2925*0a6a1f1dSLionel Sambuc                              SourceLocation(),
2926*0a6a1f1dSLionel Sambuc                              ARRFD->getType(), VK_LValue,
2927*0a6a1f1dSLionel Sambuc                              OK_Ordinary);
2928*0a6a1f1dSLionel Sambuc 
2929*0a6a1f1dSLionel Sambuc   CStyleCastExpr * DictKeyObjects =
2930*0a6a1f1dSLionel Sambuc     NoTypeInfoCStyleCastExpr(Context,
2931*0a6a1f1dSLionel Sambuc                              Context->getPointerType(ConstIdT),
2932*0a6a1f1dSLionel Sambuc                              CK_BitCast,
2933*0a6a1f1dSLionel Sambuc                              DictLiteralKeyME);
2934*0a6a1f1dSLionel Sambuc 
2935*0a6a1f1dSLionel Sambuc 
2936*0a6a1f1dSLionel Sambuc 
2937*0a6a1f1dSLionel Sambuc   // Synthesize a call to objc_msgSend().
2938*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 32> MsgExprs;
2939*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> ClsExprs;
2940*0a6a1f1dSLionel Sambuc   QualType expType = Exp->getType();
2941*0a6a1f1dSLionel Sambuc 
2942*0a6a1f1dSLionel Sambuc   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2943*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *Class =
2944*0a6a1f1dSLionel Sambuc   expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2945*0a6a1f1dSLionel Sambuc 
2946*0a6a1f1dSLionel Sambuc   IdentifierInfo *clsName = Class->getIdentifier();
2947*0a6a1f1dSLionel Sambuc   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2948*0a6a1f1dSLionel Sambuc   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2949*0a6a1f1dSLionel Sambuc                                                &ClsExprs[0],
2950*0a6a1f1dSLionel Sambuc                                                ClsExprs.size(),
2951*0a6a1f1dSLionel Sambuc                                                StartLoc, EndLoc);
2952*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(Cls);
2953*0a6a1f1dSLionel Sambuc 
2954*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("arrayWithObjects:count:").
2955*0a6a1f1dSLionel Sambuc   // it will be the 2nd argument.
2956*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> SelExprs;
2957*0a6a1f1dSLionel Sambuc   ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2958*0a6a1f1dSLionel Sambuc   SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2959*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2960*0a6a1f1dSLionel Sambuc                                                   &SelExprs[0], SelExprs.size(),
2961*0a6a1f1dSLionel Sambuc                                                   StartLoc, EndLoc);
2962*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(SelExp);
2963*0a6a1f1dSLionel Sambuc 
2964*0a6a1f1dSLionel Sambuc   // (const id [])objects
2965*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(DictValueObjects);
2966*0a6a1f1dSLionel Sambuc 
2967*0a6a1f1dSLionel Sambuc   // (const id <NSCopying> [])keys
2968*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(DictKeyObjects);
2969*0a6a1f1dSLionel Sambuc 
2970*0a6a1f1dSLionel Sambuc   // (NSUInteger)cnt
2971*0a6a1f1dSLionel Sambuc   Expr *cnt = IntegerLiteral::Create(*Context,
2972*0a6a1f1dSLionel Sambuc                                      llvm::APInt(UnsignedIntSize, NumElements),
2973*0a6a1f1dSLionel Sambuc                                      Context->UnsignedIntTy, SourceLocation());
2974*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(cnt);
2975*0a6a1f1dSLionel Sambuc 
2976*0a6a1f1dSLionel Sambuc 
2977*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
2978*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCIdType());
2979*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCSelType());
2980*0a6a1f1dSLionel Sambuc   for (const auto *PI : DictMethod->params()) {
2981*0a6a1f1dSLionel Sambuc     QualType T = PI->getType();
2982*0a6a1f1dSLionel Sambuc     if (const PointerType* PT = T->getAs<PointerType>()) {
2983*0a6a1f1dSLionel Sambuc       QualType PointeeTy = PT->getPointeeType();
2984*0a6a1f1dSLionel Sambuc       convertToUnqualifiedObjCType(PointeeTy);
2985*0a6a1f1dSLionel Sambuc       T = Context->getPointerType(PointeeTy);
2986*0a6a1f1dSLionel Sambuc     }
2987*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(T);
2988*0a6a1f1dSLionel Sambuc   }
2989*0a6a1f1dSLionel Sambuc 
2990*0a6a1f1dSLionel Sambuc   QualType returnType = Exp->getType();
2991*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2992*0a6a1f1dSLionel Sambuc   QualType msgSendType = MsgSendFlavor->getType();
2993*0a6a1f1dSLionel Sambuc 
2994*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2995*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2996*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
2997*0a6a1f1dSLionel Sambuc 
2998*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2999*0a6a1f1dSLionel Sambuc                                             Context->getPointerType(Context->VoidTy),
3000*0a6a1f1dSLionel Sambuc                                             CK_BitCast, DRE);
3001*0a6a1f1dSLionel Sambuc 
3002*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
3003*0a6a1f1dSLionel Sambuc   QualType castType =
3004*0a6a1f1dSLionel Sambuc   getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
3005*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
3006*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3007*0a6a1f1dSLionel Sambuc                                   cast);
3008*0a6a1f1dSLionel Sambuc 
3009*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
3010*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3011*0a6a1f1dSLionel Sambuc 
3012*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
3013*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context)
3014*0a6a1f1dSLionel Sambuc       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3015*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, CE);
3016*0a6a1f1dSLionel Sambuc   return CE;
3017*0a6a1f1dSLionel Sambuc }
3018*0a6a1f1dSLionel Sambuc 
3019*0a6a1f1dSLionel Sambuc // struct __rw_objc_super {
3020*0a6a1f1dSLionel Sambuc //   struct objc_object *object; struct objc_object *superClass;
3021*0a6a1f1dSLionel Sambuc // };
getSuperStructType()3022*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::getSuperStructType() {
3023*0a6a1f1dSLionel Sambuc   if (!SuperStructDecl) {
3024*0a6a1f1dSLionel Sambuc     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3025*0a6a1f1dSLionel Sambuc                                          SourceLocation(), SourceLocation(),
3026*0a6a1f1dSLionel Sambuc                                          &Context->Idents.get("__rw_objc_super"));
3027*0a6a1f1dSLionel Sambuc     QualType FieldTypes[2];
3028*0a6a1f1dSLionel Sambuc 
3029*0a6a1f1dSLionel Sambuc     // struct objc_object *object;
3030*0a6a1f1dSLionel Sambuc     FieldTypes[0] = Context->getObjCIdType();
3031*0a6a1f1dSLionel Sambuc     // struct objc_object *superClass;
3032*0a6a1f1dSLionel Sambuc     FieldTypes[1] = Context->getObjCIdType();
3033*0a6a1f1dSLionel Sambuc 
3034*0a6a1f1dSLionel Sambuc     // Create fields
3035*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < 2; ++i) {
3036*0a6a1f1dSLionel Sambuc       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3037*0a6a1f1dSLionel Sambuc                                                  SourceLocation(),
3038*0a6a1f1dSLionel Sambuc                                                  SourceLocation(), nullptr,
3039*0a6a1f1dSLionel Sambuc                                                  FieldTypes[i], nullptr,
3040*0a6a1f1dSLionel Sambuc                                                  /*BitWidth=*/nullptr,
3041*0a6a1f1dSLionel Sambuc                                                  /*Mutable=*/false,
3042*0a6a1f1dSLionel Sambuc                                                  ICIS_NoInit));
3043*0a6a1f1dSLionel Sambuc     }
3044*0a6a1f1dSLionel Sambuc 
3045*0a6a1f1dSLionel Sambuc     SuperStructDecl->completeDefinition();
3046*0a6a1f1dSLionel Sambuc   }
3047*0a6a1f1dSLionel Sambuc   return Context->getTagDeclType(SuperStructDecl);
3048*0a6a1f1dSLionel Sambuc }
3049*0a6a1f1dSLionel Sambuc 
getConstantStringStructType()3050*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::getConstantStringStructType() {
3051*0a6a1f1dSLionel Sambuc   if (!ConstantStringDecl) {
3052*0a6a1f1dSLionel Sambuc     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3053*0a6a1f1dSLionel Sambuc                                             SourceLocation(), SourceLocation(),
3054*0a6a1f1dSLionel Sambuc                          &Context->Idents.get("__NSConstantStringImpl"));
3055*0a6a1f1dSLionel Sambuc     QualType FieldTypes[4];
3056*0a6a1f1dSLionel Sambuc 
3057*0a6a1f1dSLionel Sambuc     // struct objc_object *receiver;
3058*0a6a1f1dSLionel Sambuc     FieldTypes[0] = Context->getObjCIdType();
3059*0a6a1f1dSLionel Sambuc     // int flags;
3060*0a6a1f1dSLionel Sambuc     FieldTypes[1] = Context->IntTy;
3061*0a6a1f1dSLionel Sambuc     // char *str;
3062*0a6a1f1dSLionel Sambuc     FieldTypes[2] = Context->getPointerType(Context->CharTy);
3063*0a6a1f1dSLionel Sambuc     // long length;
3064*0a6a1f1dSLionel Sambuc     FieldTypes[3] = Context->LongTy;
3065*0a6a1f1dSLionel Sambuc 
3066*0a6a1f1dSLionel Sambuc     // Create fields
3067*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < 4; ++i) {
3068*0a6a1f1dSLionel Sambuc       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3069*0a6a1f1dSLionel Sambuc                                                     ConstantStringDecl,
3070*0a6a1f1dSLionel Sambuc                                                     SourceLocation(),
3071*0a6a1f1dSLionel Sambuc                                                     SourceLocation(), nullptr,
3072*0a6a1f1dSLionel Sambuc                                                     FieldTypes[i], nullptr,
3073*0a6a1f1dSLionel Sambuc                                                     /*BitWidth=*/nullptr,
3074*0a6a1f1dSLionel Sambuc                                                     /*Mutable=*/true,
3075*0a6a1f1dSLionel Sambuc                                                     ICIS_NoInit));
3076*0a6a1f1dSLionel Sambuc     }
3077*0a6a1f1dSLionel Sambuc 
3078*0a6a1f1dSLionel Sambuc     ConstantStringDecl->completeDefinition();
3079*0a6a1f1dSLionel Sambuc   }
3080*0a6a1f1dSLionel Sambuc   return Context->getTagDeclType(ConstantStringDecl);
3081*0a6a1f1dSLionel Sambuc }
3082*0a6a1f1dSLionel Sambuc 
3083*0a6a1f1dSLionel Sambuc /// getFunctionSourceLocation - returns start location of a function
3084*0a6a1f1dSLionel Sambuc /// definition. Complication arises when function has declared as
3085*0a6a1f1dSLionel Sambuc /// extern "C" or extern "C" {...}
getFunctionSourceLocation(RewriteModernObjC & R,FunctionDecl * FD)3086*0a6a1f1dSLionel Sambuc static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3087*0a6a1f1dSLionel Sambuc                                                  FunctionDecl *FD) {
3088*0a6a1f1dSLionel Sambuc   if (FD->isExternC()  && !FD->isMain()) {
3089*0a6a1f1dSLionel Sambuc     const DeclContext *DC = FD->getDeclContext();
3090*0a6a1f1dSLionel Sambuc     if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3091*0a6a1f1dSLionel Sambuc       // if it is extern "C" {...}, return function decl's own location.
3092*0a6a1f1dSLionel Sambuc       if (!LSD->getRBraceLoc().isValid())
3093*0a6a1f1dSLionel Sambuc         return LSD->getExternLoc();
3094*0a6a1f1dSLionel Sambuc   }
3095*0a6a1f1dSLionel Sambuc   if (FD->getStorageClass() != SC_None)
3096*0a6a1f1dSLionel Sambuc     R.RewriteBlockLiteralFunctionDecl(FD);
3097*0a6a1f1dSLionel Sambuc   return FD->getTypeSpecStartLoc();
3098*0a6a1f1dSLionel Sambuc }
3099*0a6a1f1dSLionel Sambuc 
RewriteLineDirective(const Decl * D)3100*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3101*0a6a1f1dSLionel Sambuc 
3102*0a6a1f1dSLionel Sambuc   SourceLocation Location = D->getLocation();
3103*0a6a1f1dSLionel Sambuc 
3104*0a6a1f1dSLionel Sambuc   if (Location.isFileID() && GenerateLineInfo) {
3105*0a6a1f1dSLionel Sambuc     std::string LineString("\n#line ");
3106*0a6a1f1dSLionel Sambuc     PresumedLoc PLoc = SM->getPresumedLoc(Location);
3107*0a6a1f1dSLionel Sambuc     LineString += utostr(PLoc.getLine());
3108*0a6a1f1dSLionel Sambuc     LineString += " \"";
3109*0a6a1f1dSLionel Sambuc     LineString += Lexer::Stringify(PLoc.getFilename());
3110*0a6a1f1dSLionel Sambuc     if (isa<ObjCMethodDecl>(D))
3111*0a6a1f1dSLionel Sambuc       LineString += "\"";
3112*0a6a1f1dSLionel Sambuc     else LineString += "\"\n";
3113*0a6a1f1dSLionel Sambuc 
3114*0a6a1f1dSLionel Sambuc     Location = D->getLocStart();
3115*0a6a1f1dSLionel Sambuc     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3116*0a6a1f1dSLionel Sambuc       if (FD->isExternC()  && !FD->isMain()) {
3117*0a6a1f1dSLionel Sambuc         const DeclContext *DC = FD->getDeclContext();
3118*0a6a1f1dSLionel Sambuc         if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3119*0a6a1f1dSLionel Sambuc           // if it is extern "C" {...}, return function decl's own location.
3120*0a6a1f1dSLionel Sambuc           if (!LSD->getRBraceLoc().isValid())
3121*0a6a1f1dSLionel Sambuc             Location = LSD->getExternLoc();
3122*0a6a1f1dSLionel Sambuc       }
3123*0a6a1f1dSLionel Sambuc     }
3124*0a6a1f1dSLionel Sambuc     InsertText(Location, LineString);
3125*0a6a1f1dSLionel Sambuc   }
3126*0a6a1f1dSLionel Sambuc }
3127*0a6a1f1dSLionel Sambuc 
3128*0a6a1f1dSLionel Sambuc /// SynthMsgSendStretCallExpr - This routine translates message expression
3129*0a6a1f1dSLionel Sambuc /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3130*0a6a1f1dSLionel Sambuc /// nil check on receiver must be performed before calling objc_msgSend_stret.
3131*0a6a1f1dSLionel Sambuc /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3132*0a6a1f1dSLionel Sambuc /// msgSendType - function type of objc_msgSend_stret(...)
3133*0a6a1f1dSLionel Sambuc /// returnType - Result type of the method being synthesized.
3134*0a6a1f1dSLionel Sambuc /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3135*0a6a1f1dSLionel Sambuc /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3136*0a6a1f1dSLionel Sambuc /// starting with receiver.
3137*0a6a1f1dSLionel Sambuc /// Method - Method being rewritten.
SynthMsgSendStretCallExpr(FunctionDecl * MsgSendStretFlavor,QualType returnType,SmallVectorImpl<QualType> & ArgTypes,SmallVectorImpl<Expr * > & MsgExprs,ObjCMethodDecl * Method)3138*0a6a1f1dSLionel Sambuc Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3139*0a6a1f1dSLionel Sambuc                                                  QualType returnType,
3140*0a6a1f1dSLionel Sambuc                                                  SmallVectorImpl<QualType> &ArgTypes,
3141*0a6a1f1dSLionel Sambuc                                                  SmallVectorImpl<Expr*> &MsgExprs,
3142*0a6a1f1dSLionel Sambuc                                                  ObjCMethodDecl *Method) {
3143*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
3144*0a6a1f1dSLionel Sambuc   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3145*0a6a1f1dSLionel Sambuc                                             Method ? Method->isVariadic()
3146*0a6a1f1dSLionel Sambuc                                                    : false);
3147*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
3148*0a6a1f1dSLionel Sambuc 
3149*0a6a1f1dSLionel Sambuc   // build type for containing the objc_msgSend_stret object.
3150*0a6a1f1dSLionel Sambuc   static unsigned stretCount=0;
3151*0a6a1f1dSLionel Sambuc   std::string name = "__Stret"; name += utostr(stretCount);
3152*0a6a1f1dSLionel Sambuc   std::string str =
3153*0a6a1f1dSLionel Sambuc     "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3154*0a6a1f1dSLionel Sambuc   str += "namespace {\n";
3155*0a6a1f1dSLionel Sambuc   str += "struct "; str += name;
3156*0a6a1f1dSLionel Sambuc   str += " {\n\t";
3157*0a6a1f1dSLionel Sambuc   str += name;
3158*0a6a1f1dSLionel Sambuc   str += "(id receiver, SEL sel";
3159*0a6a1f1dSLionel Sambuc   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3160*0a6a1f1dSLionel Sambuc     std::string ArgName = "arg"; ArgName += utostr(i);
3161*0a6a1f1dSLionel Sambuc     ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3162*0a6a1f1dSLionel Sambuc     str += ", "; str += ArgName;
3163*0a6a1f1dSLionel Sambuc   }
3164*0a6a1f1dSLionel Sambuc   // could be vararg.
3165*0a6a1f1dSLionel Sambuc   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3166*0a6a1f1dSLionel Sambuc     std::string ArgName = "arg"; ArgName += utostr(i);
3167*0a6a1f1dSLionel Sambuc     MsgExprs[i]->getType().getAsStringInternal(ArgName,
3168*0a6a1f1dSLionel Sambuc                                                Context->getPrintingPolicy());
3169*0a6a1f1dSLionel Sambuc     str += ", "; str += ArgName;
3170*0a6a1f1dSLionel Sambuc   }
3171*0a6a1f1dSLionel Sambuc 
3172*0a6a1f1dSLionel Sambuc   str += ") {\n";
3173*0a6a1f1dSLionel Sambuc   str += "\t  unsigned size = sizeof(";
3174*0a6a1f1dSLionel Sambuc   str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3175*0a6a1f1dSLionel Sambuc 
3176*0a6a1f1dSLionel Sambuc   str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3177*0a6a1f1dSLionel Sambuc 
3178*0a6a1f1dSLionel Sambuc   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3179*0a6a1f1dSLionel Sambuc   str += ")(void *)objc_msgSend)(receiver, sel";
3180*0a6a1f1dSLionel Sambuc   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3181*0a6a1f1dSLionel Sambuc     str += ", arg"; str += utostr(i);
3182*0a6a1f1dSLionel Sambuc   }
3183*0a6a1f1dSLionel Sambuc   // could be vararg.
3184*0a6a1f1dSLionel Sambuc   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3185*0a6a1f1dSLionel Sambuc     str += ", arg"; str += utostr(i);
3186*0a6a1f1dSLionel Sambuc   }
3187*0a6a1f1dSLionel Sambuc   str+= ");\n";
3188*0a6a1f1dSLionel Sambuc 
3189*0a6a1f1dSLionel Sambuc   str += "\t  else if (receiver == 0)\n";
3190*0a6a1f1dSLionel Sambuc   str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3191*0a6a1f1dSLionel Sambuc   str += "\t  else\n";
3192*0a6a1f1dSLionel Sambuc 
3193*0a6a1f1dSLionel Sambuc 
3194*0a6a1f1dSLionel Sambuc   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3195*0a6a1f1dSLionel Sambuc   str += ")(void *)objc_msgSend_stret)(receiver, sel";
3196*0a6a1f1dSLionel Sambuc   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3197*0a6a1f1dSLionel Sambuc     str += ", arg"; str += utostr(i);
3198*0a6a1f1dSLionel Sambuc   }
3199*0a6a1f1dSLionel Sambuc   // could be vararg.
3200*0a6a1f1dSLionel Sambuc   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3201*0a6a1f1dSLionel Sambuc     str += ", arg"; str += utostr(i);
3202*0a6a1f1dSLionel Sambuc   }
3203*0a6a1f1dSLionel Sambuc   str += ");\n";
3204*0a6a1f1dSLionel Sambuc 
3205*0a6a1f1dSLionel Sambuc 
3206*0a6a1f1dSLionel Sambuc   str += "\t}\n";
3207*0a6a1f1dSLionel Sambuc   str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3208*0a6a1f1dSLionel Sambuc   str += " s;\n";
3209*0a6a1f1dSLionel Sambuc   str += "};\n};\n\n";
3210*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart;
3211*0a6a1f1dSLionel Sambuc   if (CurFunctionDef)
3212*0a6a1f1dSLionel Sambuc     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3213*0a6a1f1dSLionel Sambuc   else {
3214*0a6a1f1dSLionel Sambuc     assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3215*0a6a1f1dSLionel Sambuc     FunLocStart = CurMethodDef->getLocStart();
3216*0a6a1f1dSLionel Sambuc   }
3217*0a6a1f1dSLionel Sambuc 
3218*0a6a1f1dSLionel Sambuc   InsertText(FunLocStart, str);
3219*0a6a1f1dSLionel Sambuc   ++stretCount;
3220*0a6a1f1dSLionel Sambuc 
3221*0a6a1f1dSLionel Sambuc   // AST for __Stretn(receiver, args).s;
3222*0a6a1f1dSLionel Sambuc   IdentifierInfo *ID = &Context->Idents.get(name);
3223*0a6a1f1dSLionel Sambuc   FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3224*0a6a1f1dSLionel Sambuc                                           SourceLocation(), ID, castType,
3225*0a6a1f1dSLionel Sambuc                                           nullptr, SC_Extern, false, false);
3226*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3227*0a6a1f1dSLionel Sambuc                                                SourceLocation());
3228*0a6a1f1dSLionel Sambuc   CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3229*0a6a1f1dSLionel Sambuc                                           castType, VK_LValue, SourceLocation());
3230*0a6a1f1dSLionel Sambuc 
3231*0a6a1f1dSLionel Sambuc   FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3232*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
3233*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("s"),
3234*0a6a1f1dSLionel Sambuc                                     returnType, nullptr,
3235*0a6a1f1dSLionel Sambuc                                     /*BitWidth=*/nullptr,
3236*0a6a1f1dSLionel Sambuc                                     /*Mutable=*/true, ICIS_NoInit);
3237*0a6a1f1dSLionel Sambuc   MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3238*0a6a1f1dSLionel Sambuc                                             FieldD->getType(), VK_LValue,
3239*0a6a1f1dSLionel Sambuc                                             OK_Ordinary);
3240*0a6a1f1dSLionel Sambuc 
3241*0a6a1f1dSLionel Sambuc   return ME;
3242*0a6a1f1dSLionel Sambuc }
3243*0a6a1f1dSLionel Sambuc 
SynthMessageExpr(ObjCMessageExpr * Exp,SourceLocation StartLoc,SourceLocation EndLoc)3244*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3245*0a6a1f1dSLionel Sambuc                                     SourceLocation StartLoc,
3246*0a6a1f1dSLionel Sambuc                                     SourceLocation EndLoc) {
3247*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
3248*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
3249*0a6a1f1dSLionel Sambuc   if (!MsgSendFunctionDecl)
3250*0a6a1f1dSLionel Sambuc     SynthMsgSendFunctionDecl();
3251*0a6a1f1dSLionel Sambuc   if (!MsgSendSuperFunctionDecl)
3252*0a6a1f1dSLionel Sambuc     SynthMsgSendSuperFunctionDecl();
3253*0a6a1f1dSLionel Sambuc   if (!MsgSendStretFunctionDecl)
3254*0a6a1f1dSLionel Sambuc     SynthMsgSendStretFunctionDecl();
3255*0a6a1f1dSLionel Sambuc   if (!MsgSendSuperStretFunctionDecl)
3256*0a6a1f1dSLionel Sambuc     SynthMsgSendSuperStretFunctionDecl();
3257*0a6a1f1dSLionel Sambuc   if (!MsgSendFpretFunctionDecl)
3258*0a6a1f1dSLionel Sambuc     SynthMsgSendFpretFunctionDecl();
3259*0a6a1f1dSLionel Sambuc   if (!GetClassFunctionDecl)
3260*0a6a1f1dSLionel Sambuc     SynthGetClassFunctionDecl();
3261*0a6a1f1dSLionel Sambuc   if (!GetSuperClassFunctionDecl)
3262*0a6a1f1dSLionel Sambuc     SynthGetSuperClassFunctionDecl();
3263*0a6a1f1dSLionel Sambuc   if (!GetMetaClassFunctionDecl)
3264*0a6a1f1dSLionel Sambuc     SynthGetMetaClassFunctionDecl();
3265*0a6a1f1dSLionel Sambuc 
3266*0a6a1f1dSLionel Sambuc   // default to objc_msgSend().
3267*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3268*0a6a1f1dSLionel Sambuc   // May need to use objc_msgSend_stret() as well.
3269*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendStretFlavor = nullptr;
3270*0a6a1f1dSLionel Sambuc   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3271*0a6a1f1dSLionel Sambuc     QualType resultType = mDecl->getReturnType();
3272*0a6a1f1dSLionel Sambuc     if (resultType->isRecordType())
3273*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendStretFunctionDecl;
3274*0a6a1f1dSLionel Sambuc     else if (resultType->isRealFloatingType())
3275*0a6a1f1dSLionel Sambuc       MsgSendFlavor = MsgSendFpretFunctionDecl;
3276*0a6a1f1dSLionel Sambuc   }
3277*0a6a1f1dSLionel Sambuc 
3278*0a6a1f1dSLionel Sambuc   // Synthesize a call to objc_msgSend().
3279*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> MsgExprs;
3280*0a6a1f1dSLionel Sambuc   switch (Exp->getReceiverKind()) {
3281*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass: {
3282*0a6a1f1dSLionel Sambuc     MsgSendFlavor = MsgSendSuperFunctionDecl;
3283*0a6a1f1dSLionel Sambuc     if (MsgSendStretFlavor)
3284*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3285*0a6a1f1dSLionel Sambuc     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3286*0a6a1f1dSLionel Sambuc 
3287*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3288*0a6a1f1dSLionel Sambuc 
3289*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 4> InitExprs;
3290*0a6a1f1dSLionel Sambuc 
3291*0a6a1f1dSLionel Sambuc     // set the receiver to self, the first argument to all methods.
3292*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
3293*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3294*0a6a1f1dSLionel Sambuc                                CK_BitCast,
3295*0a6a1f1dSLionel Sambuc                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3296*0a6a1f1dSLionel Sambuc                                              false,
3297*0a6a1f1dSLionel Sambuc                                              Context->getObjCIdType(),
3298*0a6a1f1dSLionel Sambuc                                              VK_RValue,
3299*0a6a1f1dSLionel Sambuc                                              SourceLocation()))
3300*0a6a1f1dSLionel Sambuc                         ); // set the 'receiver'.
3301*0a6a1f1dSLionel Sambuc 
3302*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3303*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
3304*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3305*0a6a1f1dSLionel Sambuc     // (Class)objc_getClass("CurrentClass")
3306*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3307*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
3308*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
3309*0a6a1f1dSLionel Sambuc                                                  StartLoc,
3310*0a6a1f1dSLionel Sambuc                                                  EndLoc);
3311*0a6a1f1dSLionel Sambuc     ClsExprs.clear();
3312*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(Cls);
3313*0a6a1f1dSLionel Sambuc     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3314*0a6a1f1dSLionel Sambuc                                        &ClsExprs[0], ClsExprs.size(),
3315*0a6a1f1dSLionel Sambuc                                        StartLoc, EndLoc);
3316*0a6a1f1dSLionel Sambuc 
3317*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3318*0a6a1f1dSLionel Sambuc     // To turn off a warning, type-cast to 'id'
3319*0a6a1f1dSLionel Sambuc     InitExprs.push_back( // set 'super class', using class_getSuperclass().
3320*0a6a1f1dSLionel Sambuc                         NoTypeInfoCStyleCastExpr(Context,
3321*0a6a1f1dSLionel Sambuc                                                  Context->getObjCIdType(),
3322*0a6a1f1dSLionel Sambuc                                                  CK_BitCast, Cls));
3323*0a6a1f1dSLionel Sambuc     // struct __rw_objc_super
3324*0a6a1f1dSLionel Sambuc     QualType superType = getSuperStructType();
3325*0a6a1f1dSLionel Sambuc     Expr *SuperRep;
3326*0a6a1f1dSLionel Sambuc 
3327*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt) {
3328*0a6a1f1dSLionel Sambuc       SynthSuperConstructorFunctionDecl();
3329*0a6a1f1dSLionel Sambuc       // Simulate a constructor call...
3330*0a6a1f1dSLionel Sambuc       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3331*0a6a1f1dSLionel Sambuc                                                    false, superType, VK_LValue,
3332*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
3333*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3334*0a6a1f1dSLionel Sambuc                                         superType, VK_LValue,
3335*0a6a1f1dSLionel Sambuc                                         SourceLocation());
3336*0a6a1f1dSLionel Sambuc       // The code for super is a little tricky to prevent collision with
3337*0a6a1f1dSLionel Sambuc       // the structure definition in the header. The rewriter has it's own
3338*0a6a1f1dSLionel Sambuc       // internal definition (__rw_objc_super) that is uses. This is why
3339*0a6a1f1dSLionel Sambuc       // we need the cast below. For example:
3340*0a6a1f1dSLionel Sambuc       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3341*0a6a1f1dSLionel Sambuc       //
3342*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3343*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
3344*0a6a1f1dSLionel Sambuc                                              VK_RValue, OK_Ordinary,
3345*0a6a1f1dSLionel Sambuc                                              SourceLocation());
3346*0a6a1f1dSLionel Sambuc       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3347*0a6a1f1dSLionel Sambuc                                           Context->getPointerType(superType),
3348*0a6a1f1dSLionel Sambuc                                           CK_BitCast, SuperRep);
3349*0a6a1f1dSLionel Sambuc     } else {
3350*0a6a1f1dSLionel Sambuc       // (struct __rw_objc_super) { <exprs from above> }
3351*0a6a1f1dSLionel Sambuc       InitListExpr *ILE =
3352*0a6a1f1dSLionel Sambuc         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3353*0a6a1f1dSLionel Sambuc                                    SourceLocation());
3354*0a6a1f1dSLionel Sambuc       TypeSourceInfo *superTInfo
3355*0a6a1f1dSLionel Sambuc         = Context->getTrivialTypeSourceInfo(superType);
3356*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3357*0a6a1f1dSLionel Sambuc                                                    superType, VK_LValue,
3358*0a6a1f1dSLionel Sambuc                                                    ILE, false);
3359*0a6a1f1dSLionel Sambuc       // struct __rw_objc_super *
3360*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3361*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
3362*0a6a1f1dSLionel Sambuc                                              VK_RValue, OK_Ordinary,
3363*0a6a1f1dSLionel Sambuc                                              SourceLocation());
3364*0a6a1f1dSLionel Sambuc     }
3365*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(SuperRep);
3366*0a6a1f1dSLionel Sambuc     break;
3367*0a6a1f1dSLionel Sambuc   }
3368*0a6a1f1dSLionel Sambuc 
3369*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class: {
3370*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
3371*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *Class
3372*0a6a1f1dSLionel Sambuc       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3373*0a6a1f1dSLionel Sambuc     IdentifierInfo *clsName = Class->getIdentifier();
3374*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(clsName->getName()));
3375*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3376*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
3377*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
3378*0a6a1f1dSLionel Sambuc                                                  StartLoc, EndLoc);
3379*0a6a1f1dSLionel Sambuc     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3380*0a6a1f1dSLionel Sambuc                                                  Context->getObjCIdType(),
3381*0a6a1f1dSLionel Sambuc                                                  CK_BitCast, Cls);
3382*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(ArgExpr);
3383*0a6a1f1dSLionel Sambuc     break;
3384*0a6a1f1dSLionel Sambuc   }
3385*0a6a1f1dSLionel Sambuc 
3386*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:{
3387*0a6a1f1dSLionel Sambuc     MsgSendFlavor = MsgSendSuperFunctionDecl;
3388*0a6a1f1dSLionel Sambuc     if (MsgSendStretFlavor)
3389*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3390*0a6a1f1dSLionel Sambuc     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3391*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3392*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 4> InitExprs;
3393*0a6a1f1dSLionel Sambuc 
3394*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
3395*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3396*0a6a1f1dSLionel Sambuc                                CK_BitCast,
3397*0a6a1f1dSLionel Sambuc                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3398*0a6a1f1dSLionel Sambuc                                              false,
3399*0a6a1f1dSLionel Sambuc                                              Context->getObjCIdType(),
3400*0a6a1f1dSLionel Sambuc                                              VK_RValue, SourceLocation()))
3401*0a6a1f1dSLionel Sambuc                         ); // set the 'receiver'.
3402*0a6a1f1dSLionel Sambuc 
3403*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3404*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
3405*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3406*0a6a1f1dSLionel Sambuc     // (Class)objc_getClass("CurrentClass")
3407*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3408*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
3409*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
3410*0a6a1f1dSLionel Sambuc                                                  StartLoc, EndLoc);
3411*0a6a1f1dSLionel Sambuc     ClsExprs.clear();
3412*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(Cls);
3413*0a6a1f1dSLionel Sambuc     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3414*0a6a1f1dSLionel Sambuc                                        &ClsExprs[0], ClsExprs.size(),
3415*0a6a1f1dSLionel Sambuc                                        StartLoc, EndLoc);
3416*0a6a1f1dSLionel Sambuc 
3417*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3418*0a6a1f1dSLionel Sambuc     // To turn off a warning, type-cast to 'id'
3419*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
3420*0a6a1f1dSLionel Sambuc       // set 'super class', using class_getSuperclass().
3421*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3422*0a6a1f1dSLionel Sambuc                                CK_BitCast, Cls));
3423*0a6a1f1dSLionel Sambuc     // struct __rw_objc_super
3424*0a6a1f1dSLionel Sambuc     QualType superType = getSuperStructType();
3425*0a6a1f1dSLionel Sambuc     Expr *SuperRep;
3426*0a6a1f1dSLionel Sambuc 
3427*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt) {
3428*0a6a1f1dSLionel Sambuc       SynthSuperConstructorFunctionDecl();
3429*0a6a1f1dSLionel Sambuc       // Simulate a constructor call...
3430*0a6a1f1dSLionel Sambuc       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3431*0a6a1f1dSLionel Sambuc                                                    false, superType, VK_LValue,
3432*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
3433*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3434*0a6a1f1dSLionel Sambuc                                         superType, VK_LValue, SourceLocation());
3435*0a6a1f1dSLionel Sambuc       // The code for super is a little tricky to prevent collision with
3436*0a6a1f1dSLionel Sambuc       // the structure definition in the header. The rewriter has it's own
3437*0a6a1f1dSLionel Sambuc       // internal definition (__rw_objc_super) that is uses. This is why
3438*0a6a1f1dSLionel Sambuc       // we need the cast below. For example:
3439*0a6a1f1dSLionel Sambuc       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3440*0a6a1f1dSLionel Sambuc       //
3441*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3442*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
3443*0a6a1f1dSLionel Sambuc                                VK_RValue, OK_Ordinary,
3444*0a6a1f1dSLionel Sambuc                                SourceLocation());
3445*0a6a1f1dSLionel Sambuc       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3446*0a6a1f1dSLionel Sambuc                                Context->getPointerType(superType),
3447*0a6a1f1dSLionel Sambuc                                CK_BitCast, SuperRep);
3448*0a6a1f1dSLionel Sambuc     } else {
3449*0a6a1f1dSLionel Sambuc       // (struct __rw_objc_super) { <exprs from above> }
3450*0a6a1f1dSLionel Sambuc       InitListExpr *ILE =
3451*0a6a1f1dSLionel Sambuc         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3452*0a6a1f1dSLionel Sambuc                                    SourceLocation());
3453*0a6a1f1dSLionel Sambuc       TypeSourceInfo *superTInfo
3454*0a6a1f1dSLionel Sambuc         = Context->getTrivialTypeSourceInfo(superType);
3455*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3456*0a6a1f1dSLionel Sambuc                                                    superType, VK_RValue, ILE,
3457*0a6a1f1dSLionel Sambuc                                                    false);
3458*0a6a1f1dSLionel Sambuc     }
3459*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(SuperRep);
3460*0a6a1f1dSLionel Sambuc     break;
3461*0a6a1f1dSLionel Sambuc   }
3462*0a6a1f1dSLionel Sambuc 
3463*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance: {
3464*0a6a1f1dSLionel Sambuc     // Remove all type-casts because it may contain objc-style types; e.g.
3465*0a6a1f1dSLionel Sambuc     // Foo<Proto> *.
3466*0a6a1f1dSLionel Sambuc     Expr *recExpr = Exp->getInstanceReceiver();
3467*0a6a1f1dSLionel Sambuc     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3468*0a6a1f1dSLionel Sambuc       recExpr = CE->getSubExpr();
3469*0a6a1f1dSLionel Sambuc     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3470*0a6a1f1dSLionel Sambuc                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3471*0a6a1f1dSLionel Sambuc                                      ? CK_BlockPointerToObjCPointerCast
3472*0a6a1f1dSLionel Sambuc                                      : CK_CPointerToObjCPointerCast;
3473*0a6a1f1dSLionel Sambuc 
3474*0a6a1f1dSLionel Sambuc     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3475*0a6a1f1dSLionel Sambuc                                        CK, recExpr);
3476*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(recExpr);
3477*0a6a1f1dSLionel Sambuc     break;
3478*0a6a1f1dSLionel Sambuc   }
3479*0a6a1f1dSLionel Sambuc   }
3480*0a6a1f1dSLionel Sambuc 
3481*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3482*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> SelExprs;
3483*0a6a1f1dSLionel Sambuc   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3484*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3485*0a6a1f1dSLionel Sambuc                                                  &SelExprs[0], SelExprs.size(),
3486*0a6a1f1dSLionel Sambuc                                                   StartLoc,
3487*0a6a1f1dSLionel Sambuc                                                   EndLoc);
3488*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(SelExp);
3489*0a6a1f1dSLionel Sambuc 
3490*0a6a1f1dSLionel Sambuc   // Now push any user supplied arguments.
3491*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3492*0a6a1f1dSLionel Sambuc     Expr *userExpr = Exp->getArg(i);
3493*0a6a1f1dSLionel Sambuc     // Make all implicit casts explicit...ICE comes in handy:-)
3494*0a6a1f1dSLionel Sambuc     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3495*0a6a1f1dSLionel Sambuc       // Reuse the ICE type, it is exactly what the doctor ordered.
3496*0a6a1f1dSLionel Sambuc       QualType type = ICE->getType();
3497*0a6a1f1dSLionel Sambuc       if (needToScanForQualifiers(type))
3498*0a6a1f1dSLionel Sambuc         type = Context->getObjCIdType();
3499*0a6a1f1dSLionel Sambuc       // Make sure we convert "type (^)(...)" to "type (*)(...)".
3500*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(type);
3501*0a6a1f1dSLionel Sambuc       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3502*0a6a1f1dSLionel Sambuc       CastKind CK;
3503*0a6a1f1dSLionel Sambuc       if (SubExpr->getType()->isIntegralType(*Context) &&
3504*0a6a1f1dSLionel Sambuc           type->isBooleanType()) {
3505*0a6a1f1dSLionel Sambuc         CK = CK_IntegralToBoolean;
3506*0a6a1f1dSLionel Sambuc       } else if (type->isObjCObjectPointerType()) {
3507*0a6a1f1dSLionel Sambuc         if (SubExpr->getType()->isBlockPointerType()) {
3508*0a6a1f1dSLionel Sambuc           CK = CK_BlockPointerToObjCPointerCast;
3509*0a6a1f1dSLionel Sambuc         } else if (SubExpr->getType()->isPointerType()) {
3510*0a6a1f1dSLionel Sambuc           CK = CK_CPointerToObjCPointerCast;
3511*0a6a1f1dSLionel Sambuc         } else {
3512*0a6a1f1dSLionel Sambuc           CK = CK_BitCast;
3513*0a6a1f1dSLionel Sambuc         }
3514*0a6a1f1dSLionel Sambuc       } else {
3515*0a6a1f1dSLionel Sambuc         CK = CK_BitCast;
3516*0a6a1f1dSLionel Sambuc       }
3517*0a6a1f1dSLionel Sambuc 
3518*0a6a1f1dSLionel Sambuc       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3519*0a6a1f1dSLionel Sambuc     }
3520*0a6a1f1dSLionel Sambuc     // Make id<P...> cast into an 'id' cast.
3521*0a6a1f1dSLionel Sambuc     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3522*0a6a1f1dSLionel Sambuc       if (CE->getType()->isObjCQualifiedIdType()) {
3523*0a6a1f1dSLionel Sambuc         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3524*0a6a1f1dSLionel Sambuc           userExpr = CE->getSubExpr();
3525*0a6a1f1dSLionel Sambuc         CastKind CK;
3526*0a6a1f1dSLionel Sambuc         if (userExpr->getType()->isIntegralType(*Context)) {
3527*0a6a1f1dSLionel Sambuc           CK = CK_IntegralToPointer;
3528*0a6a1f1dSLionel Sambuc         } else if (userExpr->getType()->isBlockPointerType()) {
3529*0a6a1f1dSLionel Sambuc           CK = CK_BlockPointerToObjCPointerCast;
3530*0a6a1f1dSLionel Sambuc         } else if (userExpr->getType()->isPointerType()) {
3531*0a6a1f1dSLionel Sambuc           CK = CK_CPointerToObjCPointerCast;
3532*0a6a1f1dSLionel Sambuc         } else {
3533*0a6a1f1dSLionel Sambuc           CK = CK_BitCast;
3534*0a6a1f1dSLionel Sambuc         }
3535*0a6a1f1dSLionel Sambuc         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3536*0a6a1f1dSLionel Sambuc                                             CK, userExpr);
3537*0a6a1f1dSLionel Sambuc       }
3538*0a6a1f1dSLionel Sambuc     }
3539*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(userExpr);
3540*0a6a1f1dSLionel Sambuc     // We've transferred the ownership to MsgExprs. For now, we *don't* null
3541*0a6a1f1dSLionel Sambuc     // out the argument in the original expression (since we aren't deleting
3542*0a6a1f1dSLionel Sambuc     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3543*0a6a1f1dSLionel Sambuc     //Exp->setArg(i, 0);
3544*0a6a1f1dSLionel Sambuc   }
3545*0a6a1f1dSLionel Sambuc   // Generate the funky cast.
3546*0a6a1f1dSLionel Sambuc   CastExpr *cast;
3547*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
3548*0a6a1f1dSLionel Sambuc   QualType returnType;
3549*0a6a1f1dSLionel Sambuc 
3550*0a6a1f1dSLionel Sambuc   // Push 'id' and 'SEL', the 2 implicit arguments.
3551*0a6a1f1dSLionel Sambuc   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3552*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3553*0a6a1f1dSLionel Sambuc   else
3554*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(Context->getObjCIdType());
3555*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCSelType());
3556*0a6a1f1dSLionel Sambuc   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3557*0a6a1f1dSLionel Sambuc     // Push any user argument types.
3558*0a6a1f1dSLionel Sambuc     for (const auto *PI : OMD->params()) {
3559*0a6a1f1dSLionel Sambuc       QualType t = PI->getType()->isObjCQualifiedIdType()
3560*0a6a1f1dSLionel Sambuc                      ? Context->getObjCIdType()
3561*0a6a1f1dSLionel Sambuc                      : PI->getType();
3562*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3563*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(t);
3564*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
3565*0a6a1f1dSLionel Sambuc     }
3566*0a6a1f1dSLionel Sambuc     returnType = Exp->getType();
3567*0a6a1f1dSLionel Sambuc     convertToUnqualifiedObjCType(returnType);
3568*0a6a1f1dSLionel Sambuc     (void)convertBlockPointerToFunctionPointer(returnType);
3569*0a6a1f1dSLionel Sambuc   } else {
3570*0a6a1f1dSLionel Sambuc     returnType = Context->getObjCIdType();
3571*0a6a1f1dSLionel Sambuc   }
3572*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
3573*0a6a1f1dSLionel Sambuc   QualType msgSendType = MsgSendFlavor->getType();
3574*0a6a1f1dSLionel Sambuc 
3575*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
3576*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3577*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
3578*0a6a1f1dSLionel Sambuc 
3579*0a6a1f1dSLionel Sambuc   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3580*0a6a1f1dSLionel Sambuc   // If we don't do this cast, we get the following bizarre warning/note:
3581*0a6a1f1dSLionel Sambuc   // xx.m:13: warning: function called through a non-compatible type
3582*0a6a1f1dSLionel Sambuc   // xx.m:13: note: if this code is reached, the program will abort
3583*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context,
3584*0a6a1f1dSLionel Sambuc                                   Context->getPointerType(Context->VoidTy),
3585*0a6a1f1dSLionel Sambuc                                   CK_BitCast, DRE);
3586*0a6a1f1dSLionel Sambuc 
3587*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
3588*0a6a1f1dSLionel Sambuc   // If we don't have a method decl, force a variadic cast.
3589*0a6a1f1dSLionel Sambuc   const ObjCMethodDecl *MD = Exp->getMethodDecl();
3590*0a6a1f1dSLionel Sambuc   QualType castType =
3591*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3592*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
3593*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3594*0a6a1f1dSLionel Sambuc                                   cast);
3595*0a6a1f1dSLionel Sambuc 
3596*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
3597*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3598*0a6a1f1dSLionel Sambuc 
3599*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
3600*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context)
3601*0a6a1f1dSLionel Sambuc       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3602*0a6a1f1dSLionel Sambuc   Stmt *ReplacingStmt = CE;
3603*0a6a1f1dSLionel Sambuc   if (MsgSendStretFlavor) {
3604*0a6a1f1dSLionel Sambuc     // We have the method which returns a struct/union. Must also generate
3605*0a6a1f1dSLionel Sambuc     // call to objc_msgSend_stret and hang both varieties on a conditional
3606*0a6a1f1dSLionel Sambuc     // expression which dictate which one to envoke depending on size of
3607*0a6a1f1dSLionel Sambuc     // method's return type.
3608*0a6a1f1dSLionel Sambuc 
3609*0a6a1f1dSLionel Sambuc     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3610*0a6a1f1dSLionel Sambuc                                            returnType,
3611*0a6a1f1dSLionel Sambuc                                            ArgTypes, MsgExprs,
3612*0a6a1f1dSLionel Sambuc                                            Exp->getMethodDecl());
3613*0a6a1f1dSLionel Sambuc     ReplacingStmt = STCE;
3614*0a6a1f1dSLionel Sambuc   }
3615*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3616*0a6a1f1dSLionel Sambuc   return ReplacingStmt;
3617*0a6a1f1dSLionel Sambuc }
3618*0a6a1f1dSLionel Sambuc 
RewriteMessageExpr(ObjCMessageExpr * Exp)3619*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3620*0a6a1f1dSLionel Sambuc   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3621*0a6a1f1dSLionel Sambuc                                          Exp->getLocEnd());
3622*0a6a1f1dSLionel Sambuc 
3623*0a6a1f1dSLionel Sambuc   // Now do the actual rewrite.
3624*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, ReplacingStmt);
3625*0a6a1f1dSLionel Sambuc 
3626*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3627*0a6a1f1dSLionel Sambuc   return ReplacingStmt;
3628*0a6a1f1dSLionel Sambuc }
3629*0a6a1f1dSLionel Sambuc 
3630*0a6a1f1dSLionel Sambuc // typedef struct objc_object Protocol;
getProtocolType()3631*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::getProtocolType() {
3632*0a6a1f1dSLionel Sambuc   if (!ProtocolTypeDecl) {
3633*0a6a1f1dSLionel Sambuc     TypeSourceInfo *TInfo
3634*0a6a1f1dSLionel Sambuc       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3635*0a6a1f1dSLionel Sambuc     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3636*0a6a1f1dSLionel Sambuc                                            SourceLocation(), SourceLocation(),
3637*0a6a1f1dSLionel Sambuc                                            &Context->Idents.get("Protocol"),
3638*0a6a1f1dSLionel Sambuc                                            TInfo);
3639*0a6a1f1dSLionel Sambuc   }
3640*0a6a1f1dSLionel Sambuc   return Context->getTypeDeclType(ProtocolTypeDecl);
3641*0a6a1f1dSLionel Sambuc }
3642*0a6a1f1dSLionel Sambuc 
3643*0a6a1f1dSLionel Sambuc /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3644*0a6a1f1dSLionel Sambuc /// a synthesized/forward data reference (to the protocol's metadata).
3645*0a6a1f1dSLionel Sambuc /// The forward references (and metadata) are generated in
3646*0a6a1f1dSLionel Sambuc /// RewriteModernObjC::HandleTranslationUnit().
RewriteObjCProtocolExpr(ObjCProtocolExpr * Exp)3647*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3648*0a6a1f1dSLionel Sambuc   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3649*0a6a1f1dSLionel Sambuc                       Exp->getProtocol()->getNameAsString();
3650*0a6a1f1dSLionel Sambuc   IdentifierInfo *ID = &Context->Idents.get(Name);
3651*0a6a1f1dSLionel Sambuc   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3652*0a6a1f1dSLionel Sambuc                                 SourceLocation(), ID, getProtocolType(),
3653*0a6a1f1dSLionel Sambuc                                 nullptr, SC_Extern);
3654*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3655*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
3656*0a6a1f1dSLionel Sambuc   CastExpr *castExpr =
3657*0a6a1f1dSLionel Sambuc     NoTypeInfoCStyleCastExpr(
3658*0a6a1f1dSLionel Sambuc       Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3659*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, castExpr);
3660*0a6a1f1dSLionel Sambuc   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3661*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3662*0a6a1f1dSLionel Sambuc   return castExpr;
3663*0a6a1f1dSLionel Sambuc 
3664*0a6a1f1dSLionel Sambuc }
3665*0a6a1f1dSLionel Sambuc 
BufferContainsPPDirectives(const char * startBuf,const char * endBuf)3666*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3667*0a6a1f1dSLionel Sambuc                                              const char *endBuf) {
3668*0a6a1f1dSLionel Sambuc   while (startBuf < endBuf) {
3669*0a6a1f1dSLionel Sambuc     if (*startBuf == '#') {
3670*0a6a1f1dSLionel Sambuc       // Skip whitespace.
3671*0a6a1f1dSLionel Sambuc       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3672*0a6a1f1dSLionel Sambuc         ;
3673*0a6a1f1dSLionel Sambuc       if (!strncmp(startBuf, "if", strlen("if")) ||
3674*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3675*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3676*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "define", strlen("define")) ||
3677*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "undef", strlen("undef")) ||
3678*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "else", strlen("else")) ||
3679*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "elif", strlen("elif")) ||
3680*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "endif", strlen("endif")) ||
3681*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "pragma", strlen("pragma")) ||
3682*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "include", strlen("include")) ||
3683*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "import", strlen("import")) ||
3684*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "include_next", strlen("include_next")))
3685*0a6a1f1dSLionel Sambuc         return true;
3686*0a6a1f1dSLionel Sambuc     }
3687*0a6a1f1dSLionel Sambuc     startBuf++;
3688*0a6a1f1dSLionel Sambuc   }
3689*0a6a1f1dSLionel Sambuc   return false;
3690*0a6a1f1dSLionel Sambuc }
3691*0a6a1f1dSLionel Sambuc 
3692*0a6a1f1dSLionel Sambuc /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3693*0a6a1f1dSLionel Sambuc /// is defined inside an objective-c class. If so, it returns true.
IsTagDefinedInsideClass(ObjCContainerDecl * IDecl,TagDecl * Tag,bool & IsNamedDefinition)3694*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3695*0a6a1f1dSLionel Sambuc                                                 TagDecl *Tag,
3696*0a6a1f1dSLionel Sambuc                                                 bool &IsNamedDefinition) {
3697*0a6a1f1dSLionel Sambuc   if (!IDecl)
3698*0a6a1f1dSLionel Sambuc     return false;
3699*0a6a1f1dSLionel Sambuc   SourceLocation TagLocation;
3700*0a6a1f1dSLionel Sambuc   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3701*0a6a1f1dSLionel Sambuc     RD = RD->getDefinition();
3702*0a6a1f1dSLionel Sambuc     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3703*0a6a1f1dSLionel Sambuc       return false;
3704*0a6a1f1dSLionel Sambuc     IsNamedDefinition = true;
3705*0a6a1f1dSLionel Sambuc     TagLocation = RD->getLocation();
3706*0a6a1f1dSLionel Sambuc     return Context->getSourceManager().isBeforeInTranslationUnit(
3707*0a6a1f1dSLionel Sambuc                                           IDecl->getLocation(), TagLocation);
3708*0a6a1f1dSLionel Sambuc   }
3709*0a6a1f1dSLionel Sambuc   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3710*0a6a1f1dSLionel Sambuc     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3711*0a6a1f1dSLionel Sambuc       return false;
3712*0a6a1f1dSLionel Sambuc     IsNamedDefinition = true;
3713*0a6a1f1dSLionel Sambuc     TagLocation = ED->getLocation();
3714*0a6a1f1dSLionel Sambuc     return Context->getSourceManager().isBeforeInTranslationUnit(
3715*0a6a1f1dSLionel Sambuc                                           IDecl->getLocation(), TagLocation);
3716*0a6a1f1dSLionel Sambuc 
3717*0a6a1f1dSLionel Sambuc   }
3718*0a6a1f1dSLionel Sambuc   return false;
3719*0a6a1f1dSLionel Sambuc }
3720*0a6a1f1dSLionel Sambuc 
3721*0a6a1f1dSLionel Sambuc /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3722*0a6a1f1dSLionel Sambuc /// It handles elaborated types, as well as enum types in the process.
RewriteObjCFieldDeclType(QualType & Type,std::string & Result)3723*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3724*0a6a1f1dSLionel Sambuc                                                  std::string &Result) {
3725*0a6a1f1dSLionel Sambuc   if (isa<TypedefType>(Type)) {
3726*0a6a1f1dSLionel Sambuc     Result += "\t";
3727*0a6a1f1dSLionel Sambuc     return false;
3728*0a6a1f1dSLionel Sambuc   }
3729*0a6a1f1dSLionel Sambuc 
3730*0a6a1f1dSLionel Sambuc   if (Type->isArrayType()) {
3731*0a6a1f1dSLionel Sambuc     QualType ElemTy = Context->getBaseElementType(Type);
3732*0a6a1f1dSLionel Sambuc     return RewriteObjCFieldDeclType(ElemTy, Result);
3733*0a6a1f1dSLionel Sambuc   }
3734*0a6a1f1dSLionel Sambuc   else if (Type->isRecordType()) {
3735*0a6a1f1dSLionel Sambuc     RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3736*0a6a1f1dSLionel Sambuc     if (RD->isCompleteDefinition()) {
3737*0a6a1f1dSLionel Sambuc       if (RD->isStruct())
3738*0a6a1f1dSLionel Sambuc         Result += "\n\tstruct ";
3739*0a6a1f1dSLionel Sambuc       else if (RD->isUnion())
3740*0a6a1f1dSLionel Sambuc         Result += "\n\tunion ";
3741*0a6a1f1dSLionel Sambuc       else
3742*0a6a1f1dSLionel Sambuc         assert(false && "class not allowed as an ivar type");
3743*0a6a1f1dSLionel Sambuc 
3744*0a6a1f1dSLionel Sambuc       Result += RD->getName();
3745*0a6a1f1dSLionel Sambuc       if (GlobalDefinedTags.count(RD)) {
3746*0a6a1f1dSLionel Sambuc         // struct/union is defined globally, use it.
3747*0a6a1f1dSLionel Sambuc         Result += " ";
3748*0a6a1f1dSLionel Sambuc         return true;
3749*0a6a1f1dSLionel Sambuc       }
3750*0a6a1f1dSLionel Sambuc       Result += " {\n";
3751*0a6a1f1dSLionel Sambuc       for (auto *FD : RD->fields())
3752*0a6a1f1dSLionel Sambuc         RewriteObjCFieldDecl(FD, Result);
3753*0a6a1f1dSLionel Sambuc       Result += "\t} ";
3754*0a6a1f1dSLionel Sambuc       return true;
3755*0a6a1f1dSLionel Sambuc     }
3756*0a6a1f1dSLionel Sambuc   }
3757*0a6a1f1dSLionel Sambuc   else if (Type->isEnumeralType()) {
3758*0a6a1f1dSLionel Sambuc     EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3759*0a6a1f1dSLionel Sambuc     if (ED->isCompleteDefinition()) {
3760*0a6a1f1dSLionel Sambuc       Result += "\n\tenum ";
3761*0a6a1f1dSLionel Sambuc       Result += ED->getName();
3762*0a6a1f1dSLionel Sambuc       if (GlobalDefinedTags.count(ED)) {
3763*0a6a1f1dSLionel Sambuc         // Enum is globall defined, use it.
3764*0a6a1f1dSLionel Sambuc         Result += " ";
3765*0a6a1f1dSLionel Sambuc         return true;
3766*0a6a1f1dSLionel Sambuc       }
3767*0a6a1f1dSLionel Sambuc 
3768*0a6a1f1dSLionel Sambuc       Result += " {\n";
3769*0a6a1f1dSLionel Sambuc       for (const auto *EC : ED->enumerators()) {
3770*0a6a1f1dSLionel Sambuc         Result += "\t"; Result += EC->getName(); Result += " = ";
3771*0a6a1f1dSLionel Sambuc         llvm::APSInt Val = EC->getInitVal();
3772*0a6a1f1dSLionel Sambuc         Result += Val.toString(10);
3773*0a6a1f1dSLionel Sambuc         Result += ",\n";
3774*0a6a1f1dSLionel Sambuc       }
3775*0a6a1f1dSLionel Sambuc       Result += "\t} ";
3776*0a6a1f1dSLionel Sambuc       return true;
3777*0a6a1f1dSLionel Sambuc     }
3778*0a6a1f1dSLionel Sambuc   }
3779*0a6a1f1dSLionel Sambuc 
3780*0a6a1f1dSLionel Sambuc   Result += "\t";
3781*0a6a1f1dSLionel Sambuc   convertObjCTypeToCStyleType(Type);
3782*0a6a1f1dSLionel Sambuc   return false;
3783*0a6a1f1dSLionel Sambuc }
3784*0a6a1f1dSLionel Sambuc 
3785*0a6a1f1dSLionel Sambuc 
3786*0a6a1f1dSLionel Sambuc /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3787*0a6a1f1dSLionel Sambuc /// It handles elaborated types, as well as enum types in the process.
RewriteObjCFieldDecl(FieldDecl * fieldDecl,std::string & Result)3788*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3789*0a6a1f1dSLionel Sambuc                                              std::string &Result) {
3790*0a6a1f1dSLionel Sambuc   QualType Type = fieldDecl->getType();
3791*0a6a1f1dSLionel Sambuc   std::string Name = fieldDecl->getNameAsString();
3792*0a6a1f1dSLionel Sambuc 
3793*0a6a1f1dSLionel Sambuc   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3794*0a6a1f1dSLionel Sambuc   if (!EleboratedType)
3795*0a6a1f1dSLionel Sambuc     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3796*0a6a1f1dSLionel Sambuc   Result += Name;
3797*0a6a1f1dSLionel Sambuc   if (fieldDecl->isBitField()) {
3798*0a6a1f1dSLionel Sambuc     Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3799*0a6a1f1dSLionel Sambuc   }
3800*0a6a1f1dSLionel Sambuc   else if (EleboratedType && Type->isArrayType()) {
3801*0a6a1f1dSLionel Sambuc     const ArrayType *AT = Context->getAsArrayType(Type);
3802*0a6a1f1dSLionel Sambuc     do {
3803*0a6a1f1dSLionel Sambuc       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3804*0a6a1f1dSLionel Sambuc         Result += "[";
3805*0a6a1f1dSLionel Sambuc         llvm::APInt Dim = CAT->getSize();
3806*0a6a1f1dSLionel Sambuc         Result += utostr(Dim.getZExtValue());
3807*0a6a1f1dSLionel Sambuc         Result += "]";
3808*0a6a1f1dSLionel Sambuc       }
3809*0a6a1f1dSLionel Sambuc       AT = Context->getAsArrayType(AT->getElementType());
3810*0a6a1f1dSLionel Sambuc     } while (AT);
3811*0a6a1f1dSLionel Sambuc   }
3812*0a6a1f1dSLionel Sambuc 
3813*0a6a1f1dSLionel Sambuc   Result += ";\n";
3814*0a6a1f1dSLionel Sambuc }
3815*0a6a1f1dSLionel Sambuc 
3816*0a6a1f1dSLionel Sambuc /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3817*0a6a1f1dSLionel Sambuc /// named aggregate types into the input buffer.
RewriteLocallyDefinedNamedAggregates(FieldDecl * fieldDecl,std::string & Result)3818*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3819*0a6a1f1dSLionel Sambuc                                              std::string &Result) {
3820*0a6a1f1dSLionel Sambuc   QualType Type = fieldDecl->getType();
3821*0a6a1f1dSLionel Sambuc   if (isa<TypedefType>(Type))
3822*0a6a1f1dSLionel Sambuc     return;
3823*0a6a1f1dSLionel Sambuc   if (Type->isArrayType())
3824*0a6a1f1dSLionel Sambuc     Type = Context->getBaseElementType(Type);
3825*0a6a1f1dSLionel Sambuc   ObjCContainerDecl *IDecl =
3826*0a6a1f1dSLionel Sambuc     dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3827*0a6a1f1dSLionel Sambuc 
3828*0a6a1f1dSLionel Sambuc   TagDecl *TD = nullptr;
3829*0a6a1f1dSLionel Sambuc   if (Type->isRecordType()) {
3830*0a6a1f1dSLionel Sambuc     TD = Type->getAs<RecordType>()->getDecl();
3831*0a6a1f1dSLionel Sambuc   }
3832*0a6a1f1dSLionel Sambuc   else if (Type->isEnumeralType()) {
3833*0a6a1f1dSLionel Sambuc     TD = Type->getAs<EnumType>()->getDecl();
3834*0a6a1f1dSLionel Sambuc   }
3835*0a6a1f1dSLionel Sambuc 
3836*0a6a1f1dSLionel Sambuc   if (TD) {
3837*0a6a1f1dSLionel Sambuc     if (GlobalDefinedTags.count(TD))
3838*0a6a1f1dSLionel Sambuc       return;
3839*0a6a1f1dSLionel Sambuc 
3840*0a6a1f1dSLionel Sambuc     bool IsNamedDefinition = false;
3841*0a6a1f1dSLionel Sambuc     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3842*0a6a1f1dSLionel Sambuc       RewriteObjCFieldDeclType(Type, Result);
3843*0a6a1f1dSLionel Sambuc       Result += ";";
3844*0a6a1f1dSLionel Sambuc     }
3845*0a6a1f1dSLionel Sambuc     if (IsNamedDefinition)
3846*0a6a1f1dSLionel Sambuc       GlobalDefinedTags.insert(TD);
3847*0a6a1f1dSLionel Sambuc   }
3848*0a6a1f1dSLionel Sambuc 
3849*0a6a1f1dSLionel Sambuc }
3850*0a6a1f1dSLionel Sambuc 
ObjCIvarBitfieldGroupNo(ObjCIvarDecl * IV)3851*0a6a1f1dSLionel Sambuc unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3852*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3853*0a6a1f1dSLionel Sambuc   if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3854*0a6a1f1dSLionel Sambuc     return IvarGroupNumber[IV];
3855*0a6a1f1dSLionel Sambuc   }
3856*0a6a1f1dSLionel Sambuc   unsigned GroupNo = 0;
3857*0a6a1f1dSLionel Sambuc   SmallVector<const ObjCIvarDecl *, 8> IVars;
3858*0a6a1f1dSLionel Sambuc   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3859*0a6a1f1dSLionel Sambuc        IVD; IVD = IVD->getNextIvar())
3860*0a6a1f1dSLionel Sambuc     IVars.push_back(IVD);
3861*0a6a1f1dSLionel Sambuc 
3862*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3863*0a6a1f1dSLionel Sambuc     if (IVars[i]->isBitField()) {
3864*0a6a1f1dSLionel Sambuc       IvarGroupNumber[IVars[i++]] = ++GroupNo;
3865*0a6a1f1dSLionel Sambuc       while (i < e && IVars[i]->isBitField())
3866*0a6a1f1dSLionel Sambuc         IvarGroupNumber[IVars[i++]] = GroupNo;
3867*0a6a1f1dSLionel Sambuc       if (i < e)
3868*0a6a1f1dSLionel Sambuc         --i;
3869*0a6a1f1dSLionel Sambuc     }
3870*0a6a1f1dSLionel Sambuc 
3871*0a6a1f1dSLionel Sambuc   ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3872*0a6a1f1dSLionel Sambuc   return IvarGroupNumber[IV];
3873*0a6a1f1dSLionel Sambuc }
3874*0a6a1f1dSLionel Sambuc 
SynthesizeBitfieldGroupStructType(ObjCIvarDecl * IV,SmallVectorImpl<ObjCIvarDecl * > & IVars)3875*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3876*0a6a1f1dSLionel Sambuc                               ObjCIvarDecl *IV,
3877*0a6a1f1dSLionel Sambuc                               SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3878*0a6a1f1dSLionel Sambuc   std::string StructTagName;
3879*0a6a1f1dSLionel Sambuc   ObjCIvarBitfieldGroupType(IV, StructTagName);
3880*0a6a1f1dSLionel Sambuc   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3881*0a6a1f1dSLionel Sambuc                                       Context->getTranslationUnitDecl(),
3882*0a6a1f1dSLionel Sambuc                                       SourceLocation(), SourceLocation(),
3883*0a6a1f1dSLionel Sambuc                                       &Context->Idents.get(StructTagName));
3884*0a6a1f1dSLionel Sambuc   for (unsigned i=0, e = IVars.size(); i < e; i++) {
3885*0a6a1f1dSLionel Sambuc     ObjCIvarDecl *Ivar = IVars[i];
3886*0a6a1f1dSLionel Sambuc     RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3887*0a6a1f1dSLionel Sambuc                                   &Context->Idents.get(Ivar->getName()),
3888*0a6a1f1dSLionel Sambuc                                   Ivar->getType(),
3889*0a6a1f1dSLionel Sambuc                                   nullptr, /*Expr *BW */Ivar->getBitWidth(),
3890*0a6a1f1dSLionel Sambuc                                   false, ICIS_NoInit));
3891*0a6a1f1dSLionel Sambuc   }
3892*0a6a1f1dSLionel Sambuc   RD->completeDefinition();
3893*0a6a1f1dSLionel Sambuc   return Context->getTagDeclType(RD);
3894*0a6a1f1dSLionel Sambuc }
3895*0a6a1f1dSLionel Sambuc 
GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * IV)3896*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3897*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3898*0a6a1f1dSLionel Sambuc   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3899*0a6a1f1dSLionel Sambuc   std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3900*0a6a1f1dSLionel Sambuc   if (GroupRecordType.count(tuple))
3901*0a6a1f1dSLionel Sambuc     return GroupRecordType[tuple];
3902*0a6a1f1dSLionel Sambuc 
3903*0a6a1f1dSLionel Sambuc   SmallVector<ObjCIvarDecl *, 8> IVars;
3904*0a6a1f1dSLionel Sambuc   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3905*0a6a1f1dSLionel Sambuc        IVD; IVD = IVD->getNextIvar()) {
3906*0a6a1f1dSLionel Sambuc     if (IVD->isBitField())
3907*0a6a1f1dSLionel Sambuc       IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3908*0a6a1f1dSLionel Sambuc     else {
3909*0a6a1f1dSLionel Sambuc       if (!IVars.empty()) {
3910*0a6a1f1dSLionel Sambuc         unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3911*0a6a1f1dSLionel Sambuc         // Generate the struct type for this group of bitfield ivars.
3912*0a6a1f1dSLionel Sambuc         GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3913*0a6a1f1dSLionel Sambuc           SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3914*0a6a1f1dSLionel Sambuc         IVars.clear();
3915*0a6a1f1dSLionel Sambuc       }
3916*0a6a1f1dSLionel Sambuc     }
3917*0a6a1f1dSLionel Sambuc   }
3918*0a6a1f1dSLionel Sambuc   if (!IVars.empty()) {
3919*0a6a1f1dSLionel Sambuc     // Do the last one.
3920*0a6a1f1dSLionel Sambuc     unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3921*0a6a1f1dSLionel Sambuc     GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3922*0a6a1f1dSLionel Sambuc       SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3923*0a6a1f1dSLionel Sambuc   }
3924*0a6a1f1dSLionel Sambuc   QualType RetQT = GroupRecordType[tuple];
3925*0a6a1f1dSLionel Sambuc   assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3926*0a6a1f1dSLionel Sambuc 
3927*0a6a1f1dSLionel Sambuc   return RetQT;
3928*0a6a1f1dSLionel Sambuc }
3929*0a6a1f1dSLionel Sambuc 
3930*0a6a1f1dSLionel Sambuc /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3931*0a6a1f1dSLionel Sambuc /// Name would be: classname__GRBF_n where n is the group number for this ivar.
ObjCIvarBitfieldGroupDecl(ObjCIvarDecl * IV,std::string & Result)3932*0a6a1f1dSLionel Sambuc void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3933*0a6a1f1dSLionel Sambuc                                                   std::string &Result) {
3934*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3935*0a6a1f1dSLionel Sambuc   Result += CDecl->getName();
3936*0a6a1f1dSLionel Sambuc   Result += "__GRBF_";
3937*0a6a1f1dSLionel Sambuc   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3938*0a6a1f1dSLionel Sambuc   Result += utostr(GroupNo);
3939*0a6a1f1dSLionel Sambuc   return;
3940*0a6a1f1dSLionel Sambuc }
3941*0a6a1f1dSLionel Sambuc 
3942*0a6a1f1dSLionel Sambuc /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3943*0a6a1f1dSLionel Sambuc /// Name of the struct would be: classname__T_n where n is the group number for
3944*0a6a1f1dSLionel Sambuc /// this ivar.
ObjCIvarBitfieldGroupType(ObjCIvarDecl * IV,std::string & Result)3945*0a6a1f1dSLionel Sambuc void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3946*0a6a1f1dSLionel Sambuc                                                   std::string &Result) {
3947*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3948*0a6a1f1dSLionel Sambuc   Result += CDecl->getName();
3949*0a6a1f1dSLionel Sambuc   Result += "__T_";
3950*0a6a1f1dSLionel Sambuc   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3951*0a6a1f1dSLionel Sambuc   Result += utostr(GroupNo);
3952*0a6a1f1dSLionel Sambuc   return;
3953*0a6a1f1dSLionel Sambuc }
3954*0a6a1f1dSLionel Sambuc 
3955*0a6a1f1dSLionel Sambuc /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3956*0a6a1f1dSLionel Sambuc /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3957*0a6a1f1dSLionel Sambuc /// this ivar.
ObjCIvarBitfieldGroupOffset(ObjCIvarDecl * IV,std::string & Result)3958*0a6a1f1dSLionel Sambuc void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3959*0a6a1f1dSLionel Sambuc                                                     std::string &Result) {
3960*0a6a1f1dSLionel Sambuc   Result += "OBJC_IVAR_$_";
3961*0a6a1f1dSLionel Sambuc   ObjCIvarBitfieldGroupDecl(IV, Result);
3962*0a6a1f1dSLionel Sambuc }
3963*0a6a1f1dSLionel Sambuc 
3964*0a6a1f1dSLionel Sambuc #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3965*0a6a1f1dSLionel Sambuc       while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3966*0a6a1f1dSLionel Sambuc         ++IX; \
3967*0a6a1f1dSLionel Sambuc       if (IX < ENDIX) \
3968*0a6a1f1dSLionel Sambuc         --IX; \
3969*0a6a1f1dSLionel Sambuc }
3970*0a6a1f1dSLionel Sambuc 
3971*0a6a1f1dSLionel Sambuc /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3972*0a6a1f1dSLionel Sambuc /// an objective-c class with ivars.
RewriteObjCInternalStruct(ObjCInterfaceDecl * CDecl,std::string & Result)3973*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3974*0a6a1f1dSLionel Sambuc                                                std::string &Result) {
3975*0a6a1f1dSLionel Sambuc   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3976*0a6a1f1dSLionel Sambuc   assert(CDecl->getName() != "" &&
3977*0a6a1f1dSLionel Sambuc          "Name missing in SynthesizeObjCInternalStruct");
3978*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3979*0a6a1f1dSLionel Sambuc   SmallVector<ObjCIvarDecl *, 8> IVars;
3980*0a6a1f1dSLionel Sambuc   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3981*0a6a1f1dSLionel Sambuc        IVD; IVD = IVD->getNextIvar())
3982*0a6a1f1dSLionel Sambuc     IVars.push_back(IVD);
3983*0a6a1f1dSLionel Sambuc 
3984*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CDecl->getLocStart();
3985*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3986*0a6a1f1dSLionel Sambuc 
3987*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
3988*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
3989*0a6a1f1dSLionel Sambuc 
3990*0a6a1f1dSLionel Sambuc   // If no ivars and no root or if its root, directly or indirectly,
3991*0a6a1f1dSLionel Sambuc   // have no ivars (thus not synthesized) then no need to synthesize this class.
3992*0a6a1f1dSLionel Sambuc   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3993*0a6a1f1dSLionel Sambuc       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3994*0a6a1f1dSLionel Sambuc     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3995*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, Result);
3996*0a6a1f1dSLionel Sambuc     return;
3997*0a6a1f1dSLionel Sambuc   }
3998*0a6a1f1dSLionel Sambuc 
3999*0a6a1f1dSLionel Sambuc   // Insert named struct/union definitions inside class to
4000*0a6a1f1dSLionel Sambuc   // outer scope. This follows semantics of locally defined
4001*0a6a1f1dSLionel Sambuc   // struct/unions in objective-c classes.
4002*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = IVars.size(); i < e; i++)
4003*0a6a1f1dSLionel Sambuc     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
4004*0a6a1f1dSLionel Sambuc 
4005*0a6a1f1dSLionel Sambuc   // Insert named structs which are syntheized to group ivar bitfields
4006*0a6a1f1dSLionel Sambuc   // to outer scope as well.
4007*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = IVars.size(); i < e; i++)
4008*0a6a1f1dSLionel Sambuc     if (IVars[i]->isBitField()) {
4009*0a6a1f1dSLionel Sambuc       ObjCIvarDecl *IV = IVars[i];
4010*0a6a1f1dSLionel Sambuc       QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4011*0a6a1f1dSLionel Sambuc       RewriteObjCFieldDeclType(QT, Result);
4012*0a6a1f1dSLionel Sambuc       Result += ";";
4013*0a6a1f1dSLionel Sambuc       // skip over ivar bitfields in this group.
4014*0a6a1f1dSLionel Sambuc       SKIP_BITFIELDS(i , e, IVars);
4015*0a6a1f1dSLionel Sambuc     }
4016*0a6a1f1dSLionel Sambuc 
4017*0a6a1f1dSLionel Sambuc   Result += "\nstruct ";
4018*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
4019*0a6a1f1dSLionel Sambuc   Result += "_IMPL {\n";
4020*0a6a1f1dSLionel Sambuc 
4021*0a6a1f1dSLionel Sambuc   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
4022*0a6a1f1dSLionel Sambuc     Result += "\tstruct "; Result += RCDecl->getNameAsString();
4023*0a6a1f1dSLionel Sambuc     Result += "_IMPL "; Result += RCDecl->getNameAsString();
4024*0a6a1f1dSLionel Sambuc     Result += "_IVARS;\n";
4025*0a6a1f1dSLionel Sambuc   }
4026*0a6a1f1dSLionel Sambuc 
4027*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4028*0a6a1f1dSLionel Sambuc     if (IVars[i]->isBitField()) {
4029*0a6a1f1dSLionel Sambuc       ObjCIvarDecl *IV = IVars[i];
4030*0a6a1f1dSLionel Sambuc       Result += "\tstruct ";
4031*0a6a1f1dSLionel Sambuc       ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4032*0a6a1f1dSLionel Sambuc       ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4033*0a6a1f1dSLionel Sambuc       // skip over ivar bitfields in this group.
4034*0a6a1f1dSLionel Sambuc       SKIP_BITFIELDS(i , e, IVars);
4035*0a6a1f1dSLionel Sambuc     }
4036*0a6a1f1dSLionel Sambuc     else
4037*0a6a1f1dSLionel Sambuc       RewriteObjCFieldDecl(IVars[i], Result);
4038*0a6a1f1dSLionel Sambuc   }
4039*0a6a1f1dSLionel Sambuc 
4040*0a6a1f1dSLionel Sambuc   Result += "};\n";
4041*0a6a1f1dSLionel Sambuc   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4042*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, endBuf-startBuf, Result);
4043*0a6a1f1dSLionel Sambuc   // Mark this struct as having been generated.
4044*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedStructs.insert(CDecl).second)
4045*0a6a1f1dSLionel Sambuc     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
4046*0a6a1f1dSLionel Sambuc }
4047*0a6a1f1dSLionel Sambuc 
4048*0a6a1f1dSLionel Sambuc /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4049*0a6a1f1dSLionel Sambuc /// have been referenced in an ivar access expression.
RewriteIvarOffsetSymbols(ObjCInterfaceDecl * CDecl,std::string & Result)4050*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4051*0a6a1f1dSLionel Sambuc                                                   std::string &Result) {
4052*0a6a1f1dSLionel Sambuc   // write out ivar offset symbols which have been referenced in an ivar
4053*0a6a1f1dSLionel Sambuc   // access expression.
4054*0a6a1f1dSLionel Sambuc   llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4055*0a6a1f1dSLionel Sambuc   if (Ivars.empty())
4056*0a6a1f1dSLionel Sambuc     return;
4057*0a6a1f1dSLionel Sambuc 
4058*0a6a1f1dSLionel Sambuc   llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
4059*0a6a1f1dSLionel Sambuc   for (ObjCIvarDecl *IvarDecl : Ivars) {
4060*0a6a1f1dSLionel Sambuc     const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4061*0a6a1f1dSLionel Sambuc     unsigned GroupNo = 0;
4062*0a6a1f1dSLionel Sambuc     if (IvarDecl->isBitField()) {
4063*0a6a1f1dSLionel Sambuc       GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4064*0a6a1f1dSLionel Sambuc       if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4065*0a6a1f1dSLionel Sambuc         continue;
4066*0a6a1f1dSLionel Sambuc     }
4067*0a6a1f1dSLionel Sambuc     Result += "\n";
4068*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
4069*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
4070*0a6a1f1dSLionel Sambuc     Result += "extern \"C\" ";
4071*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt &&
4072*0a6a1f1dSLionel Sambuc         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
4073*0a6a1f1dSLionel Sambuc         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4074*0a6a1f1dSLionel Sambuc         Result += "__declspec(dllimport) ";
4075*0a6a1f1dSLionel Sambuc 
4076*0a6a1f1dSLionel Sambuc     Result += "unsigned long ";
4077*0a6a1f1dSLionel Sambuc     if (IvarDecl->isBitField()) {
4078*0a6a1f1dSLionel Sambuc       ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4079*0a6a1f1dSLionel Sambuc       GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4080*0a6a1f1dSLionel Sambuc     }
4081*0a6a1f1dSLionel Sambuc     else
4082*0a6a1f1dSLionel Sambuc       WriteInternalIvarName(CDecl, IvarDecl, Result);
4083*0a6a1f1dSLionel Sambuc     Result += ";";
4084*0a6a1f1dSLionel Sambuc   }
4085*0a6a1f1dSLionel Sambuc }
4086*0a6a1f1dSLionel Sambuc 
4087*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
4088*0a6a1f1dSLionel Sambuc // Meta Data Emission
4089*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
4090*0a6a1f1dSLionel Sambuc 
4091*0a6a1f1dSLionel Sambuc 
4092*0a6a1f1dSLionel Sambuc /// RewriteImplementations - This routine rewrites all method implementations
4093*0a6a1f1dSLionel Sambuc /// and emits meta-data.
4094*0a6a1f1dSLionel Sambuc 
RewriteImplementations()4095*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteImplementations() {
4096*0a6a1f1dSLionel Sambuc   int ClsDefCount = ClassImplementation.size();
4097*0a6a1f1dSLionel Sambuc   int CatDefCount = CategoryImplementation.size();
4098*0a6a1f1dSLionel Sambuc 
4099*0a6a1f1dSLionel Sambuc   // Rewrite implemented methods
4100*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++) {
4101*0a6a1f1dSLionel Sambuc     ObjCImplementationDecl *OIMP = ClassImplementation[i];
4102*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4103*0a6a1f1dSLionel Sambuc     if (CDecl->isImplicitInterfaceDecl())
4104*0a6a1f1dSLionel Sambuc       assert(false &&
4105*0a6a1f1dSLionel Sambuc              "Legacy implicit interface rewriting not supported in moder abi");
4106*0a6a1f1dSLionel Sambuc     RewriteImplementationDecl(OIMP);
4107*0a6a1f1dSLionel Sambuc   }
4108*0a6a1f1dSLionel Sambuc 
4109*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++) {
4110*0a6a1f1dSLionel Sambuc     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4111*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4112*0a6a1f1dSLionel Sambuc     if (CDecl->isImplicitInterfaceDecl())
4113*0a6a1f1dSLionel Sambuc       assert(false &&
4114*0a6a1f1dSLionel Sambuc              "Legacy implicit interface rewriting not supported in moder abi");
4115*0a6a1f1dSLionel Sambuc     RewriteImplementationDecl(CIMP);
4116*0a6a1f1dSLionel Sambuc   }
4117*0a6a1f1dSLionel Sambuc }
4118*0a6a1f1dSLionel Sambuc 
RewriteByRefString(std::string & ResultStr,const std::string & Name,ValueDecl * VD,bool def)4119*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4120*0a6a1f1dSLionel Sambuc                                      const std::string &Name,
4121*0a6a1f1dSLionel Sambuc                                      ValueDecl *VD, bool def) {
4122*0a6a1f1dSLionel Sambuc   assert(BlockByRefDeclNo.count(VD) &&
4123*0a6a1f1dSLionel Sambuc          "RewriteByRefString: ByRef decl missing");
4124*0a6a1f1dSLionel Sambuc   if (def)
4125*0a6a1f1dSLionel Sambuc     ResultStr += "struct ";
4126*0a6a1f1dSLionel Sambuc   ResultStr += "__Block_byref_" + Name +
4127*0a6a1f1dSLionel Sambuc     "_" + utostr(BlockByRefDeclNo[VD]) ;
4128*0a6a1f1dSLionel Sambuc }
4129*0a6a1f1dSLionel Sambuc 
HasLocalVariableExternalStorage(ValueDecl * VD)4130*0a6a1f1dSLionel Sambuc static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4131*0a6a1f1dSLionel Sambuc   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4132*0a6a1f1dSLionel Sambuc     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4133*0a6a1f1dSLionel Sambuc   return false;
4134*0a6a1f1dSLionel Sambuc }
4135*0a6a1f1dSLionel Sambuc 
SynthesizeBlockFunc(BlockExpr * CE,int i,StringRef funcName,std::string Tag)4136*0a6a1f1dSLionel Sambuc std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4137*0a6a1f1dSLionel Sambuc                                                    StringRef funcName,
4138*0a6a1f1dSLionel Sambuc                                                    std::string Tag) {
4139*0a6a1f1dSLionel Sambuc   const FunctionType *AFT = CE->getFunctionType();
4140*0a6a1f1dSLionel Sambuc   QualType RT = AFT->getReturnType();
4141*0a6a1f1dSLionel Sambuc   std::string StructRef = "struct " + Tag;
4142*0a6a1f1dSLionel Sambuc   SourceLocation BlockLoc = CE->getExprLoc();
4143*0a6a1f1dSLionel Sambuc   std::string S;
4144*0a6a1f1dSLionel Sambuc   ConvertSourceLocationToLineDirective(BlockLoc, S);
4145*0a6a1f1dSLionel Sambuc 
4146*0a6a1f1dSLionel Sambuc   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4147*0a6a1f1dSLionel Sambuc          funcName.str() + "_block_func_" + utostr(i);
4148*0a6a1f1dSLionel Sambuc 
4149*0a6a1f1dSLionel Sambuc   BlockDecl *BD = CE->getBlockDecl();
4150*0a6a1f1dSLionel Sambuc 
4151*0a6a1f1dSLionel Sambuc   if (isa<FunctionNoProtoType>(AFT)) {
4152*0a6a1f1dSLionel Sambuc     // No user-supplied arguments. Still need to pass in a pointer to the
4153*0a6a1f1dSLionel Sambuc     // block (to reference imported block decl refs).
4154*0a6a1f1dSLionel Sambuc     S += "(" + StructRef + " *__cself)";
4155*0a6a1f1dSLionel Sambuc   } else if (BD->param_empty()) {
4156*0a6a1f1dSLionel Sambuc     S += "(" + StructRef + " *__cself)";
4157*0a6a1f1dSLionel Sambuc   } else {
4158*0a6a1f1dSLionel Sambuc     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4159*0a6a1f1dSLionel Sambuc     assert(FT && "SynthesizeBlockFunc: No function proto");
4160*0a6a1f1dSLionel Sambuc     S += '(';
4161*0a6a1f1dSLionel Sambuc     // first add the implicit argument.
4162*0a6a1f1dSLionel Sambuc     S += StructRef + " *__cself, ";
4163*0a6a1f1dSLionel Sambuc     std::string ParamStr;
4164*0a6a1f1dSLionel Sambuc     for (BlockDecl::param_iterator AI = BD->param_begin(),
4165*0a6a1f1dSLionel Sambuc          E = BD->param_end(); AI != E; ++AI) {
4166*0a6a1f1dSLionel Sambuc       if (AI != BD->param_begin()) S += ", ";
4167*0a6a1f1dSLionel Sambuc       ParamStr = (*AI)->getNameAsString();
4168*0a6a1f1dSLionel Sambuc       QualType QT = (*AI)->getType();
4169*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(QT);
4170*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4171*0a6a1f1dSLionel Sambuc       S += ParamStr;
4172*0a6a1f1dSLionel Sambuc     }
4173*0a6a1f1dSLionel Sambuc     if (FT->isVariadic()) {
4174*0a6a1f1dSLionel Sambuc       if (!BD->param_empty()) S += ", ";
4175*0a6a1f1dSLionel Sambuc       S += "...";
4176*0a6a1f1dSLionel Sambuc     }
4177*0a6a1f1dSLionel Sambuc     S += ')';
4178*0a6a1f1dSLionel Sambuc   }
4179*0a6a1f1dSLionel Sambuc   S += " {\n";
4180*0a6a1f1dSLionel Sambuc 
4181*0a6a1f1dSLionel Sambuc   // Create local declarations to avoid rewriting all closure decl ref exprs.
4182*0a6a1f1dSLionel Sambuc   // First, emit a declaration for all "by ref" decls.
4183*0a6a1f1dSLionel Sambuc   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4184*0a6a1f1dSLionel Sambuc        E = BlockByRefDecls.end(); I != E; ++I) {
4185*0a6a1f1dSLionel Sambuc     S += "  ";
4186*0a6a1f1dSLionel Sambuc     std::string Name = (*I)->getNameAsString();
4187*0a6a1f1dSLionel Sambuc     std::string TypeString;
4188*0a6a1f1dSLionel Sambuc     RewriteByRefString(TypeString, Name, (*I));
4189*0a6a1f1dSLionel Sambuc     TypeString += " *";
4190*0a6a1f1dSLionel Sambuc     Name = TypeString + Name;
4191*0a6a1f1dSLionel Sambuc     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4192*0a6a1f1dSLionel Sambuc   }
4193*0a6a1f1dSLionel Sambuc   // Next, emit a declaration for all "by copy" declarations.
4194*0a6a1f1dSLionel Sambuc   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4195*0a6a1f1dSLionel Sambuc        E = BlockByCopyDecls.end(); I != E; ++I) {
4196*0a6a1f1dSLionel Sambuc     S += "  ";
4197*0a6a1f1dSLionel Sambuc     // Handle nested closure invocation. For example:
4198*0a6a1f1dSLionel Sambuc     //
4199*0a6a1f1dSLionel Sambuc     //   void (^myImportedClosure)(void);
4200*0a6a1f1dSLionel Sambuc     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4201*0a6a1f1dSLionel Sambuc     //
4202*0a6a1f1dSLionel Sambuc     //   void (^anotherClosure)(void);
4203*0a6a1f1dSLionel Sambuc     //   anotherClosure = ^(void) {
4204*0a6a1f1dSLionel Sambuc     //     myImportedClosure(); // import and invoke the closure
4205*0a6a1f1dSLionel Sambuc     //   };
4206*0a6a1f1dSLionel Sambuc     //
4207*0a6a1f1dSLionel Sambuc     if (isTopLevelBlockPointerType((*I)->getType())) {
4208*0a6a1f1dSLionel Sambuc       RewriteBlockPointerTypeVariable(S, (*I));
4209*0a6a1f1dSLionel Sambuc       S += " = (";
4210*0a6a1f1dSLionel Sambuc       RewriteBlockPointerType(S, (*I)->getType());
4211*0a6a1f1dSLionel Sambuc       S += ")";
4212*0a6a1f1dSLionel Sambuc       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4213*0a6a1f1dSLionel Sambuc     }
4214*0a6a1f1dSLionel Sambuc     else {
4215*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
4216*0a6a1f1dSLionel Sambuc       QualType QT = (*I)->getType();
4217*0a6a1f1dSLionel Sambuc       if (HasLocalVariableExternalStorage(*I))
4218*0a6a1f1dSLionel Sambuc         QT = Context->getPointerType(QT);
4219*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4220*0a6a1f1dSLionel Sambuc       S += Name + " = __cself->" +
4221*0a6a1f1dSLionel Sambuc                               (*I)->getNameAsString() + "; // bound by copy\n";
4222*0a6a1f1dSLionel Sambuc     }
4223*0a6a1f1dSLionel Sambuc   }
4224*0a6a1f1dSLionel Sambuc   std::string RewrittenStr = RewrittenBlockExprs[CE];
4225*0a6a1f1dSLionel Sambuc   const char *cstr = RewrittenStr.c_str();
4226*0a6a1f1dSLionel Sambuc   while (*cstr++ != '{') ;
4227*0a6a1f1dSLionel Sambuc   S += cstr;
4228*0a6a1f1dSLionel Sambuc   S += "\n";
4229*0a6a1f1dSLionel Sambuc   return S;
4230*0a6a1f1dSLionel Sambuc }
4231*0a6a1f1dSLionel Sambuc 
SynthesizeBlockHelperFuncs(BlockExpr * CE,int i,StringRef funcName,std::string Tag)4232*0a6a1f1dSLionel Sambuc std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4233*0a6a1f1dSLionel Sambuc                                                    StringRef funcName,
4234*0a6a1f1dSLionel Sambuc                                                    std::string Tag) {
4235*0a6a1f1dSLionel Sambuc   std::string StructRef = "struct " + Tag;
4236*0a6a1f1dSLionel Sambuc   std::string S = "static void __";
4237*0a6a1f1dSLionel Sambuc 
4238*0a6a1f1dSLionel Sambuc   S += funcName;
4239*0a6a1f1dSLionel Sambuc   S += "_block_copy_" + utostr(i);
4240*0a6a1f1dSLionel Sambuc   S += "(" + StructRef;
4241*0a6a1f1dSLionel Sambuc   S += "*dst, " + StructRef;
4242*0a6a1f1dSLionel Sambuc   S += "*src) {";
4243*0a6a1f1dSLionel Sambuc   for (ValueDecl *VD : ImportedBlockDecls) {
4244*0a6a1f1dSLionel Sambuc     S += "_Block_object_assign((void*)&dst->";
4245*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
4246*0a6a1f1dSLionel Sambuc     S += ", (void*)src->";
4247*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
4248*0a6a1f1dSLionel Sambuc     if (BlockByRefDeclsPtrSet.count(VD))
4249*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4250*0a6a1f1dSLionel Sambuc     else if (VD->getType()->isBlockPointerType())
4251*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4252*0a6a1f1dSLionel Sambuc     else
4253*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4254*0a6a1f1dSLionel Sambuc   }
4255*0a6a1f1dSLionel Sambuc   S += "}\n";
4256*0a6a1f1dSLionel Sambuc 
4257*0a6a1f1dSLionel Sambuc   S += "\nstatic void __";
4258*0a6a1f1dSLionel Sambuc   S += funcName;
4259*0a6a1f1dSLionel Sambuc   S += "_block_dispose_" + utostr(i);
4260*0a6a1f1dSLionel Sambuc   S += "(" + StructRef;
4261*0a6a1f1dSLionel Sambuc   S += "*src) {";
4262*0a6a1f1dSLionel Sambuc   for (ValueDecl *VD : ImportedBlockDecls) {
4263*0a6a1f1dSLionel Sambuc     S += "_Block_object_dispose((void*)src->";
4264*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
4265*0a6a1f1dSLionel Sambuc     if (BlockByRefDeclsPtrSet.count(VD))
4266*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4267*0a6a1f1dSLionel Sambuc     else if (VD->getType()->isBlockPointerType())
4268*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4269*0a6a1f1dSLionel Sambuc     else
4270*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4271*0a6a1f1dSLionel Sambuc   }
4272*0a6a1f1dSLionel Sambuc   S += "}\n";
4273*0a6a1f1dSLionel Sambuc   return S;
4274*0a6a1f1dSLionel Sambuc }
4275*0a6a1f1dSLionel Sambuc 
SynthesizeBlockImpl(BlockExpr * CE,std::string Tag,std::string Desc)4276*0a6a1f1dSLionel Sambuc std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4277*0a6a1f1dSLionel Sambuc                                              std::string Desc) {
4278*0a6a1f1dSLionel Sambuc   std::string S = "\nstruct " + Tag;
4279*0a6a1f1dSLionel Sambuc   std::string Constructor = "  " + Tag;
4280*0a6a1f1dSLionel Sambuc 
4281*0a6a1f1dSLionel Sambuc   S += " {\n  struct __block_impl impl;\n";
4282*0a6a1f1dSLionel Sambuc   S += "  struct " + Desc;
4283*0a6a1f1dSLionel Sambuc   S += "* Desc;\n";
4284*0a6a1f1dSLionel Sambuc 
4285*0a6a1f1dSLionel Sambuc   Constructor += "(void *fp, "; // Invoke function pointer.
4286*0a6a1f1dSLionel Sambuc   Constructor += "struct " + Desc; // Descriptor pointer.
4287*0a6a1f1dSLionel Sambuc   Constructor += " *desc";
4288*0a6a1f1dSLionel Sambuc 
4289*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
4290*0a6a1f1dSLionel Sambuc     // Output all "by copy" declarations.
4291*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4292*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
4293*0a6a1f1dSLionel Sambuc       S += "  ";
4294*0a6a1f1dSLionel Sambuc       std::string FieldName = (*I)->getNameAsString();
4295*0a6a1f1dSLionel Sambuc       std::string ArgName = "_" + FieldName;
4296*0a6a1f1dSLionel Sambuc       // Handle nested closure invocation. For example:
4297*0a6a1f1dSLionel Sambuc       //
4298*0a6a1f1dSLionel Sambuc       //   void (^myImportedBlock)(void);
4299*0a6a1f1dSLionel Sambuc       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4300*0a6a1f1dSLionel Sambuc       //
4301*0a6a1f1dSLionel Sambuc       //   void (^anotherBlock)(void);
4302*0a6a1f1dSLionel Sambuc       //   anotherBlock = ^(void) {
4303*0a6a1f1dSLionel Sambuc       //     myImportedBlock(); // import and invoke the closure
4304*0a6a1f1dSLionel Sambuc       //   };
4305*0a6a1f1dSLionel Sambuc       //
4306*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType((*I)->getType())) {
4307*0a6a1f1dSLionel Sambuc         S += "struct __block_impl *";
4308*0a6a1f1dSLionel Sambuc         Constructor += ", void *" + ArgName;
4309*0a6a1f1dSLionel Sambuc       } else {
4310*0a6a1f1dSLionel Sambuc         QualType QT = (*I)->getType();
4311*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I))
4312*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
4313*0a6a1f1dSLionel Sambuc         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4314*0a6a1f1dSLionel Sambuc         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4315*0a6a1f1dSLionel Sambuc         Constructor += ", " + ArgName;
4316*0a6a1f1dSLionel Sambuc       }
4317*0a6a1f1dSLionel Sambuc       S += FieldName + ";\n";
4318*0a6a1f1dSLionel Sambuc     }
4319*0a6a1f1dSLionel Sambuc     // Output all "by ref" declarations.
4320*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4321*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
4322*0a6a1f1dSLionel Sambuc       S += "  ";
4323*0a6a1f1dSLionel Sambuc       std::string FieldName = (*I)->getNameAsString();
4324*0a6a1f1dSLionel Sambuc       std::string ArgName = "_" + FieldName;
4325*0a6a1f1dSLionel Sambuc       {
4326*0a6a1f1dSLionel Sambuc         std::string TypeString;
4327*0a6a1f1dSLionel Sambuc         RewriteByRefString(TypeString, FieldName, (*I));
4328*0a6a1f1dSLionel Sambuc         TypeString += " *";
4329*0a6a1f1dSLionel Sambuc         FieldName = TypeString + FieldName;
4330*0a6a1f1dSLionel Sambuc         ArgName = TypeString + ArgName;
4331*0a6a1f1dSLionel Sambuc         Constructor += ", " + ArgName;
4332*0a6a1f1dSLionel Sambuc       }
4333*0a6a1f1dSLionel Sambuc       S += FieldName + "; // by ref\n";
4334*0a6a1f1dSLionel Sambuc     }
4335*0a6a1f1dSLionel Sambuc     // Finish writing the constructor.
4336*0a6a1f1dSLionel Sambuc     Constructor += ", int flags=0)";
4337*0a6a1f1dSLionel Sambuc     // Initialize all "by copy" arguments.
4338*0a6a1f1dSLionel Sambuc     bool firsTime = true;
4339*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4340*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
4341*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
4342*0a6a1f1dSLionel Sambuc         if (firsTime) {
4343*0a6a1f1dSLionel Sambuc           Constructor += " : ";
4344*0a6a1f1dSLionel Sambuc           firsTime = false;
4345*0a6a1f1dSLionel Sambuc         }
4346*0a6a1f1dSLionel Sambuc         else
4347*0a6a1f1dSLionel Sambuc           Constructor += ", ";
4348*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType((*I)->getType()))
4349*0a6a1f1dSLionel Sambuc           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4350*0a6a1f1dSLionel Sambuc         else
4351*0a6a1f1dSLionel Sambuc           Constructor += Name + "(_" + Name + ")";
4352*0a6a1f1dSLionel Sambuc     }
4353*0a6a1f1dSLionel Sambuc     // Initialize all "by ref" arguments.
4354*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4355*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
4356*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
4357*0a6a1f1dSLionel Sambuc       if (firsTime) {
4358*0a6a1f1dSLionel Sambuc         Constructor += " : ";
4359*0a6a1f1dSLionel Sambuc         firsTime = false;
4360*0a6a1f1dSLionel Sambuc       }
4361*0a6a1f1dSLionel Sambuc       else
4362*0a6a1f1dSLionel Sambuc         Constructor += ", ";
4363*0a6a1f1dSLionel Sambuc       Constructor += Name + "(_" + Name + "->__forwarding)";
4364*0a6a1f1dSLionel Sambuc     }
4365*0a6a1f1dSLionel Sambuc 
4366*0a6a1f1dSLionel Sambuc     Constructor += " {\n";
4367*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl)
4368*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4369*0a6a1f1dSLionel Sambuc     else
4370*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4371*0a6a1f1dSLionel Sambuc     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4372*0a6a1f1dSLionel Sambuc 
4373*0a6a1f1dSLionel Sambuc     Constructor += "    Desc = desc;\n";
4374*0a6a1f1dSLionel Sambuc   } else {
4375*0a6a1f1dSLionel Sambuc     // Finish writing the constructor.
4376*0a6a1f1dSLionel Sambuc     Constructor += ", int flags=0) {\n";
4377*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl)
4378*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4379*0a6a1f1dSLionel Sambuc     else
4380*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4381*0a6a1f1dSLionel Sambuc     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4382*0a6a1f1dSLionel Sambuc     Constructor += "    Desc = desc;\n";
4383*0a6a1f1dSLionel Sambuc   }
4384*0a6a1f1dSLionel Sambuc   Constructor += "  ";
4385*0a6a1f1dSLionel Sambuc   Constructor += "}\n";
4386*0a6a1f1dSLionel Sambuc   S += Constructor;
4387*0a6a1f1dSLionel Sambuc   S += "};\n";
4388*0a6a1f1dSLionel Sambuc   return S;
4389*0a6a1f1dSLionel Sambuc }
4390*0a6a1f1dSLionel Sambuc 
SynthesizeBlockDescriptor(std::string DescTag,std::string ImplTag,int i,StringRef FunName,unsigned hasCopy)4391*0a6a1f1dSLionel Sambuc std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4392*0a6a1f1dSLionel Sambuc                                                    std::string ImplTag, int i,
4393*0a6a1f1dSLionel Sambuc                                                    StringRef FunName,
4394*0a6a1f1dSLionel Sambuc                                                    unsigned hasCopy) {
4395*0a6a1f1dSLionel Sambuc   std::string S = "\nstatic struct " + DescTag;
4396*0a6a1f1dSLionel Sambuc 
4397*0a6a1f1dSLionel Sambuc   S += " {\n  size_t reserved;\n";
4398*0a6a1f1dSLionel Sambuc   S += "  size_t Block_size;\n";
4399*0a6a1f1dSLionel Sambuc   if (hasCopy) {
4400*0a6a1f1dSLionel Sambuc     S += "  void (*copy)(struct ";
4401*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*, struct ";
4402*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*);\n";
4403*0a6a1f1dSLionel Sambuc 
4404*0a6a1f1dSLionel Sambuc     S += "  void (*dispose)(struct ";
4405*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*);\n";
4406*0a6a1f1dSLionel Sambuc   }
4407*0a6a1f1dSLionel Sambuc   S += "} ";
4408*0a6a1f1dSLionel Sambuc 
4409*0a6a1f1dSLionel Sambuc   S += DescTag + "_DATA = { 0, sizeof(struct ";
4410*0a6a1f1dSLionel Sambuc   S += ImplTag + ")";
4411*0a6a1f1dSLionel Sambuc   if (hasCopy) {
4412*0a6a1f1dSLionel Sambuc     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4413*0a6a1f1dSLionel Sambuc     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4414*0a6a1f1dSLionel Sambuc   }
4415*0a6a1f1dSLionel Sambuc   S += "};\n";
4416*0a6a1f1dSLionel Sambuc   return S;
4417*0a6a1f1dSLionel Sambuc }
4418*0a6a1f1dSLionel Sambuc 
SynthesizeBlockLiterals(SourceLocation FunLocStart,StringRef FunName)4419*0a6a1f1dSLionel Sambuc void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4420*0a6a1f1dSLionel Sambuc                                           StringRef FunName) {
4421*0a6a1f1dSLionel Sambuc   bool RewriteSC = (GlobalVarDecl &&
4422*0a6a1f1dSLionel Sambuc                     !Blocks.empty() &&
4423*0a6a1f1dSLionel Sambuc                     GlobalVarDecl->getStorageClass() == SC_Static &&
4424*0a6a1f1dSLionel Sambuc                     GlobalVarDecl->getType().getCVRQualifiers());
4425*0a6a1f1dSLionel Sambuc   if (RewriteSC) {
4426*0a6a1f1dSLionel Sambuc     std::string SC(" void __");
4427*0a6a1f1dSLionel Sambuc     SC += GlobalVarDecl->getNameAsString();
4428*0a6a1f1dSLionel Sambuc     SC += "() {}";
4429*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, SC);
4430*0a6a1f1dSLionel Sambuc   }
4431*0a6a1f1dSLionel Sambuc 
4432*0a6a1f1dSLionel Sambuc   // Insert closures that were part of the function.
4433*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4434*0a6a1f1dSLionel Sambuc     CollectBlockDeclRefInfo(Blocks[i]);
4435*0a6a1f1dSLionel Sambuc     // Need to copy-in the inner copied-in variables not actually used in this
4436*0a6a1f1dSLionel Sambuc     // block.
4437*0a6a1f1dSLionel Sambuc     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4438*0a6a1f1dSLionel Sambuc       DeclRefExpr *Exp = InnerDeclRefs[count++];
4439*0a6a1f1dSLionel Sambuc       ValueDecl *VD = Exp->getDecl();
4440*0a6a1f1dSLionel Sambuc       BlockDeclRefs.push_back(Exp);
4441*0a6a1f1dSLionel Sambuc       if (!VD->hasAttr<BlocksAttr>()) {
4442*0a6a1f1dSLionel Sambuc         if (!BlockByCopyDeclsPtrSet.count(VD)) {
4443*0a6a1f1dSLionel Sambuc           BlockByCopyDeclsPtrSet.insert(VD);
4444*0a6a1f1dSLionel Sambuc           BlockByCopyDecls.push_back(VD);
4445*0a6a1f1dSLionel Sambuc         }
4446*0a6a1f1dSLionel Sambuc         continue;
4447*0a6a1f1dSLionel Sambuc       }
4448*0a6a1f1dSLionel Sambuc 
4449*0a6a1f1dSLionel Sambuc       if (!BlockByRefDeclsPtrSet.count(VD)) {
4450*0a6a1f1dSLionel Sambuc         BlockByRefDeclsPtrSet.insert(VD);
4451*0a6a1f1dSLionel Sambuc         BlockByRefDecls.push_back(VD);
4452*0a6a1f1dSLionel Sambuc       }
4453*0a6a1f1dSLionel Sambuc 
4454*0a6a1f1dSLionel Sambuc       // imported objects in the inner blocks not used in the outer
4455*0a6a1f1dSLionel Sambuc       // blocks must be copied/disposed in the outer block as well.
4456*0a6a1f1dSLionel Sambuc       if (VD->getType()->isObjCObjectPointerType() ||
4457*0a6a1f1dSLionel Sambuc           VD->getType()->isBlockPointerType())
4458*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(VD);
4459*0a6a1f1dSLionel Sambuc     }
4460*0a6a1f1dSLionel Sambuc 
4461*0a6a1f1dSLionel Sambuc     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4462*0a6a1f1dSLionel Sambuc     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4463*0a6a1f1dSLionel Sambuc 
4464*0a6a1f1dSLionel Sambuc     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4465*0a6a1f1dSLionel Sambuc 
4466*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, CI);
4467*0a6a1f1dSLionel Sambuc 
4468*0a6a1f1dSLionel Sambuc     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4469*0a6a1f1dSLionel Sambuc 
4470*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, CF);
4471*0a6a1f1dSLionel Sambuc 
4472*0a6a1f1dSLionel Sambuc     if (ImportedBlockDecls.size()) {
4473*0a6a1f1dSLionel Sambuc       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4474*0a6a1f1dSLionel Sambuc       InsertText(FunLocStart, HF);
4475*0a6a1f1dSLionel Sambuc     }
4476*0a6a1f1dSLionel Sambuc     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4477*0a6a1f1dSLionel Sambuc                                                ImportedBlockDecls.size() > 0);
4478*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, BD);
4479*0a6a1f1dSLionel Sambuc 
4480*0a6a1f1dSLionel Sambuc     BlockDeclRefs.clear();
4481*0a6a1f1dSLionel Sambuc     BlockByRefDecls.clear();
4482*0a6a1f1dSLionel Sambuc     BlockByRefDeclsPtrSet.clear();
4483*0a6a1f1dSLionel Sambuc     BlockByCopyDecls.clear();
4484*0a6a1f1dSLionel Sambuc     BlockByCopyDeclsPtrSet.clear();
4485*0a6a1f1dSLionel Sambuc     ImportedBlockDecls.clear();
4486*0a6a1f1dSLionel Sambuc   }
4487*0a6a1f1dSLionel Sambuc   if (RewriteSC) {
4488*0a6a1f1dSLionel Sambuc     // Must insert any 'const/volatile/static here. Since it has been
4489*0a6a1f1dSLionel Sambuc     // removed as result of rewriting of block literals.
4490*0a6a1f1dSLionel Sambuc     std::string SC;
4491*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getStorageClass() == SC_Static)
4492*0a6a1f1dSLionel Sambuc       SC = "static ";
4493*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isConstQualified())
4494*0a6a1f1dSLionel Sambuc       SC += "const ";
4495*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isVolatileQualified())
4496*0a6a1f1dSLionel Sambuc       SC += "volatile ";
4497*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isRestrictQualified())
4498*0a6a1f1dSLionel Sambuc       SC += "restrict ";
4499*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, SC);
4500*0a6a1f1dSLionel Sambuc   }
4501*0a6a1f1dSLionel Sambuc   if (GlobalConstructionExp) {
4502*0a6a1f1dSLionel Sambuc     // extra fancy dance for global literal expression.
4503*0a6a1f1dSLionel Sambuc 
4504*0a6a1f1dSLionel Sambuc     // Always the latest block expression on the block stack.
4505*0a6a1f1dSLionel Sambuc     std::string Tag = "__";
4506*0a6a1f1dSLionel Sambuc     Tag += FunName;
4507*0a6a1f1dSLionel Sambuc     Tag += "_block_impl_";
4508*0a6a1f1dSLionel Sambuc     Tag += utostr(Blocks.size()-1);
4509*0a6a1f1dSLionel Sambuc     std::string globalBuf = "static ";
4510*0a6a1f1dSLionel Sambuc     globalBuf += Tag; globalBuf += " ";
4511*0a6a1f1dSLionel Sambuc     std::string SStr;
4512*0a6a1f1dSLionel Sambuc 
4513*0a6a1f1dSLionel Sambuc     llvm::raw_string_ostream constructorExprBuf(SStr);
4514*0a6a1f1dSLionel Sambuc     GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4515*0a6a1f1dSLionel Sambuc                                        PrintingPolicy(LangOpts));
4516*0a6a1f1dSLionel Sambuc     globalBuf += constructorExprBuf.str();
4517*0a6a1f1dSLionel Sambuc     globalBuf += ";\n";
4518*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, globalBuf);
4519*0a6a1f1dSLionel Sambuc     GlobalConstructionExp = nullptr;
4520*0a6a1f1dSLionel Sambuc   }
4521*0a6a1f1dSLionel Sambuc 
4522*0a6a1f1dSLionel Sambuc   Blocks.clear();
4523*0a6a1f1dSLionel Sambuc   InnerDeclRefsCount.clear();
4524*0a6a1f1dSLionel Sambuc   InnerDeclRefs.clear();
4525*0a6a1f1dSLionel Sambuc   RewrittenBlockExprs.clear();
4526*0a6a1f1dSLionel Sambuc }
4527*0a6a1f1dSLionel Sambuc 
InsertBlockLiteralsWithinFunction(FunctionDecl * FD)4528*0a6a1f1dSLionel Sambuc void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4529*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart =
4530*0a6a1f1dSLionel Sambuc     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4531*0a6a1f1dSLionel Sambuc                       : FD->getTypeSpecStartLoc();
4532*0a6a1f1dSLionel Sambuc   StringRef FuncName = FD->getName();
4533*0a6a1f1dSLionel Sambuc 
4534*0a6a1f1dSLionel Sambuc   SynthesizeBlockLiterals(FunLocStart, FuncName);
4535*0a6a1f1dSLionel Sambuc }
4536*0a6a1f1dSLionel Sambuc 
BuildUniqueMethodName(std::string & Name,ObjCMethodDecl * MD)4537*0a6a1f1dSLionel Sambuc static void BuildUniqueMethodName(std::string &Name,
4538*0a6a1f1dSLionel Sambuc                                   ObjCMethodDecl *MD) {
4539*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *IFace = MD->getClassInterface();
4540*0a6a1f1dSLionel Sambuc   Name = IFace->getName();
4541*0a6a1f1dSLionel Sambuc   Name += "__" + MD->getSelector().getAsString();
4542*0a6a1f1dSLionel Sambuc   // Convert colons to underscores.
4543*0a6a1f1dSLionel Sambuc   std::string::size_type loc = 0;
4544*0a6a1f1dSLionel Sambuc   while ((loc = Name.find(":", loc)) != std::string::npos)
4545*0a6a1f1dSLionel Sambuc     Name.replace(loc, 1, "_");
4546*0a6a1f1dSLionel Sambuc }
4547*0a6a1f1dSLionel Sambuc 
InsertBlockLiteralsWithinMethod(ObjCMethodDecl * MD)4548*0a6a1f1dSLionel Sambuc void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4549*0a6a1f1dSLionel Sambuc   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4550*0a6a1f1dSLionel Sambuc   //SourceLocation FunLocStart = MD->getLocStart();
4551*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart = MD->getLocStart();
4552*0a6a1f1dSLionel Sambuc   std::string FuncName;
4553*0a6a1f1dSLionel Sambuc   BuildUniqueMethodName(FuncName, MD);
4554*0a6a1f1dSLionel Sambuc   SynthesizeBlockLiterals(FunLocStart, FuncName);
4555*0a6a1f1dSLionel Sambuc }
4556*0a6a1f1dSLionel Sambuc 
GetBlockDeclRefExprs(Stmt * S)4557*0a6a1f1dSLionel Sambuc void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4558*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
4559*0a6a1f1dSLionel Sambuc     if (*CI) {
4560*0a6a1f1dSLionel Sambuc       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4561*0a6a1f1dSLionel Sambuc         GetBlockDeclRefExprs(CBE->getBody());
4562*0a6a1f1dSLionel Sambuc       else
4563*0a6a1f1dSLionel Sambuc         GetBlockDeclRefExprs(*CI);
4564*0a6a1f1dSLionel Sambuc     }
4565*0a6a1f1dSLionel Sambuc   // Handle specific things.
4566*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4567*0a6a1f1dSLionel Sambuc     if (DRE->refersToEnclosingVariableOrCapture() ||
4568*0a6a1f1dSLionel Sambuc         HasLocalVariableExternalStorage(DRE->getDecl()))
4569*0a6a1f1dSLionel Sambuc       // FIXME: Handle enums.
4570*0a6a1f1dSLionel Sambuc       BlockDeclRefs.push_back(DRE);
4571*0a6a1f1dSLionel Sambuc 
4572*0a6a1f1dSLionel Sambuc   return;
4573*0a6a1f1dSLionel Sambuc }
4574*0a6a1f1dSLionel Sambuc 
GetInnerBlockDeclRefExprs(Stmt * S,SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs,llvm::SmallPtrSetImpl<const DeclContext * > & InnerContexts)4575*0a6a1f1dSLionel Sambuc void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4576*0a6a1f1dSLionel Sambuc                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4577*0a6a1f1dSLionel Sambuc                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4578*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
4579*0a6a1f1dSLionel Sambuc     if (*CI) {
4580*0a6a1f1dSLionel Sambuc       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4581*0a6a1f1dSLionel Sambuc         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4582*0a6a1f1dSLionel Sambuc         GetInnerBlockDeclRefExprs(CBE->getBody(),
4583*0a6a1f1dSLionel Sambuc                                   InnerBlockDeclRefs,
4584*0a6a1f1dSLionel Sambuc                                   InnerContexts);
4585*0a6a1f1dSLionel Sambuc       }
4586*0a6a1f1dSLionel Sambuc       else
4587*0a6a1f1dSLionel Sambuc         GetInnerBlockDeclRefExprs(*CI,
4588*0a6a1f1dSLionel Sambuc                                   InnerBlockDeclRefs,
4589*0a6a1f1dSLionel Sambuc                                   InnerContexts);
4590*0a6a1f1dSLionel Sambuc 
4591*0a6a1f1dSLionel Sambuc     }
4592*0a6a1f1dSLionel Sambuc   // Handle specific things.
4593*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4594*0a6a1f1dSLionel Sambuc     if (DRE->refersToEnclosingVariableOrCapture() ||
4595*0a6a1f1dSLionel Sambuc         HasLocalVariableExternalStorage(DRE->getDecl())) {
4596*0a6a1f1dSLionel Sambuc       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4597*0a6a1f1dSLionel Sambuc         InnerBlockDeclRefs.push_back(DRE);
4598*0a6a1f1dSLionel Sambuc       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4599*0a6a1f1dSLionel Sambuc         if (Var->isFunctionOrMethodVarDecl())
4600*0a6a1f1dSLionel Sambuc           ImportedLocalExternalDecls.insert(Var);
4601*0a6a1f1dSLionel Sambuc     }
4602*0a6a1f1dSLionel Sambuc   }
4603*0a6a1f1dSLionel Sambuc 
4604*0a6a1f1dSLionel Sambuc   return;
4605*0a6a1f1dSLionel Sambuc }
4606*0a6a1f1dSLionel Sambuc 
4607*0a6a1f1dSLionel Sambuc /// convertObjCTypeToCStyleType - This routine converts such objc types
4608*0a6a1f1dSLionel Sambuc /// as qualified objects, and blocks to their closest c/c++ types that
4609*0a6a1f1dSLionel Sambuc /// it can. It returns true if input type was modified.
convertObjCTypeToCStyleType(QualType & T)4610*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4611*0a6a1f1dSLionel Sambuc   QualType oldT = T;
4612*0a6a1f1dSLionel Sambuc   convertBlockPointerToFunctionPointer(T);
4613*0a6a1f1dSLionel Sambuc   if (T->isFunctionPointerType()) {
4614*0a6a1f1dSLionel Sambuc     QualType PointeeTy;
4615*0a6a1f1dSLionel Sambuc     if (const PointerType* PT = T->getAs<PointerType>()) {
4616*0a6a1f1dSLionel Sambuc       PointeeTy = PT->getPointeeType();
4617*0a6a1f1dSLionel Sambuc       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4618*0a6a1f1dSLionel Sambuc         T = convertFunctionTypeOfBlocks(FT);
4619*0a6a1f1dSLionel Sambuc         T = Context->getPointerType(T);
4620*0a6a1f1dSLionel Sambuc       }
4621*0a6a1f1dSLionel Sambuc     }
4622*0a6a1f1dSLionel Sambuc   }
4623*0a6a1f1dSLionel Sambuc 
4624*0a6a1f1dSLionel Sambuc   convertToUnqualifiedObjCType(T);
4625*0a6a1f1dSLionel Sambuc   return T != oldT;
4626*0a6a1f1dSLionel Sambuc }
4627*0a6a1f1dSLionel Sambuc 
4628*0a6a1f1dSLionel Sambuc /// convertFunctionTypeOfBlocks - This routine converts a function type
4629*0a6a1f1dSLionel Sambuc /// whose result type may be a block pointer or whose argument type(s)
4630*0a6a1f1dSLionel Sambuc /// might be block pointers to an equivalent function type replacing
4631*0a6a1f1dSLionel Sambuc /// all block pointers to function pointers.
convertFunctionTypeOfBlocks(const FunctionType * FT)4632*0a6a1f1dSLionel Sambuc QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4633*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4634*0a6a1f1dSLionel Sambuc   // FTP will be null for closures that don't take arguments.
4635*0a6a1f1dSLionel Sambuc   // Generate a funky cast.
4636*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
4637*0a6a1f1dSLionel Sambuc   QualType Res = FT->getReturnType();
4638*0a6a1f1dSLionel Sambuc   bool modified = convertObjCTypeToCStyleType(Res);
4639*0a6a1f1dSLionel Sambuc 
4640*0a6a1f1dSLionel Sambuc   if (FTP) {
4641*0a6a1f1dSLionel Sambuc     for (auto &I : FTP->param_types()) {
4642*0a6a1f1dSLionel Sambuc       QualType t = I;
4643*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4644*0a6a1f1dSLionel Sambuc       if (convertObjCTypeToCStyleType(t))
4645*0a6a1f1dSLionel Sambuc         modified = true;
4646*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
4647*0a6a1f1dSLionel Sambuc     }
4648*0a6a1f1dSLionel Sambuc   }
4649*0a6a1f1dSLionel Sambuc   QualType FuncType;
4650*0a6a1f1dSLionel Sambuc   if (modified)
4651*0a6a1f1dSLionel Sambuc     FuncType = getSimpleFunctionType(Res, ArgTypes);
4652*0a6a1f1dSLionel Sambuc   else FuncType = QualType(FT, 0);
4653*0a6a1f1dSLionel Sambuc   return FuncType;
4654*0a6a1f1dSLionel Sambuc }
4655*0a6a1f1dSLionel Sambuc 
SynthesizeBlockCall(CallExpr * Exp,const Expr * BlockExp)4656*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4657*0a6a1f1dSLionel Sambuc   // Navigate to relevant type information.
4658*0a6a1f1dSLionel Sambuc   const BlockPointerType *CPT = nullptr;
4659*0a6a1f1dSLionel Sambuc 
4660*0a6a1f1dSLionel Sambuc   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4661*0a6a1f1dSLionel Sambuc     CPT = DRE->getType()->getAs<BlockPointerType>();
4662*0a6a1f1dSLionel Sambuc   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4663*0a6a1f1dSLionel Sambuc     CPT = MExpr->getType()->getAs<BlockPointerType>();
4664*0a6a1f1dSLionel Sambuc   }
4665*0a6a1f1dSLionel Sambuc   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4666*0a6a1f1dSLionel Sambuc     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4667*0a6a1f1dSLionel Sambuc   }
4668*0a6a1f1dSLionel Sambuc   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4669*0a6a1f1dSLionel Sambuc     CPT = IEXPR->getType()->getAs<BlockPointerType>();
4670*0a6a1f1dSLionel Sambuc   else if (const ConditionalOperator *CEXPR =
4671*0a6a1f1dSLionel Sambuc             dyn_cast<ConditionalOperator>(BlockExp)) {
4672*0a6a1f1dSLionel Sambuc     Expr *LHSExp = CEXPR->getLHS();
4673*0a6a1f1dSLionel Sambuc     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4674*0a6a1f1dSLionel Sambuc     Expr *RHSExp = CEXPR->getRHS();
4675*0a6a1f1dSLionel Sambuc     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4676*0a6a1f1dSLionel Sambuc     Expr *CONDExp = CEXPR->getCond();
4677*0a6a1f1dSLionel Sambuc     ConditionalOperator *CondExpr =
4678*0a6a1f1dSLionel Sambuc       new (Context) ConditionalOperator(CONDExp,
4679*0a6a1f1dSLionel Sambuc                                       SourceLocation(), cast<Expr>(LHSStmt),
4680*0a6a1f1dSLionel Sambuc                                       SourceLocation(), cast<Expr>(RHSStmt),
4681*0a6a1f1dSLionel Sambuc                                       Exp->getType(), VK_RValue, OK_Ordinary);
4682*0a6a1f1dSLionel Sambuc     return CondExpr;
4683*0a6a1f1dSLionel Sambuc   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4684*0a6a1f1dSLionel Sambuc     CPT = IRE->getType()->getAs<BlockPointerType>();
4685*0a6a1f1dSLionel Sambuc   } else if (const PseudoObjectExpr *POE
4686*0a6a1f1dSLionel Sambuc                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4687*0a6a1f1dSLionel Sambuc     CPT = POE->getType()->castAs<BlockPointerType>();
4688*0a6a1f1dSLionel Sambuc   } else {
4689*0a6a1f1dSLionel Sambuc     assert(1 && "RewriteBlockClass: Bad type");
4690*0a6a1f1dSLionel Sambuc   }
4691*0a6a1f1dSLionel Sambuc   assert(CPT && "RewriteBlockClass: Bad type");
4692*0a6a1f1dSLionel Sambuc   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4693*0a6a1f1dSLionel Sambuc   assert(FT && "RewriteBlockClass: Bad type");
4694*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4695*0a6a1f1dSLionel Sambuc   // FTP will be null for closures that don't take arguments.
4696*0a6a1f1dSLionel Sambuc 
4697*0a6a1f1dSLionel Sambuc   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4698*0a6a1f1dSLionel Sambuc                                       SourceLocation(), SourceLocation(),
4699*0a6a1f1dSLionel Sambuc                                       &Context->Idents.get("__block_impl"));
4700*0a6a1f1dSLionel Sambuc   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4701*0a6a1f1dSLionel Sambuc 
4702*0a6a1f1dSLionel Sambuc   // Generate a funky cast.
4703*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
4704*0a6a1f1dSLionel Sambuc 
4705*0a6a1f1dSLionel Sambuc   // Push the block argument type.
4706*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(PtrBlock);
4707*0a6a1f1dSLionel Sambuc   if (FTP) {
4708*0a6a1f1dSLionel Sambuc     for (auto &I : FTP->param_types()) {
4709*0a6a1f1dSLionel Sambuc       QualType t = I;
4710*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4711*0a6a1f1dSLionel Sambuc       if (!convertBlockPointerToFunctionPointer(t))
4712*0a6a1f1dSLionel Sambuc         convertToUnqualifiedObjCType(t);
4713*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
4714*0a6a1f1dSLionel Sambuc     }
4715*0a6a1f1dSLionel Sambuc   }
4716*0a6a1f1dSLionel Sambuc   // Now do the pointer to function cast.
4717*0a6a1f1dSLionel Sambuc   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4718*0a6a1f1dSLionel Sambuc 
4719*0a6a1f1dSLionel Sambuc   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4720*0a6a1f1dSLionel Sambuc 
4721*0a6a1f1dSLionel Sambuc   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4722*0a6a1f1dSLionel Sambuc                                                CK_BitCast,
4723*0a6a1f1dSLionel Sambuc                                                const_cast<Expr*>(BlockExp));
4724*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
4725*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4726*0a6a1f1dSLionel Sambuc                                           BlkCast);
4727*0a6a1f1dSLionel Sambuc   //PE->dump();
4728*0a6a1f1dSLionel Sambuc 
4729*0a6a1f1dSLionel Sambuc   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4730*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
4731*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("FuncPtr"),
4732*0a6a1f1dSLionel Sambuc                                     Context->VoidPtrTy, nullptr,
4733*0a6a1f1dSLionel Sambuc                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4734*0a6a1f1dSLionel Sambuc                                     ICIS_NoInit);
4735*0a6a1f1dSLionel Sambuc   MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4736*0a6a1f1dSLionel Sambuc                                             FD->getType(), VK_LValue,
4737*0a6a1f1dSLionel Sambuc                                             OK_Ordinary);
4738*0a6a1f1dSLionel Sambuc 
4739*0a6a1f1dSLionel Sambuc 
4740*0a6a1f1dSLionel Sambuc   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4741*0a6a1f1dSLionel Sambuc                                                 CK_BitCast, ME);
4742*0a6a1f1dSLionel Sambuc   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4743*0a6a1f1dSLionel Sambuc 
4744*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> BlkExprs;
4745*0a6a1f1dSLionel Sambuc   // Add the implicit argument.
4746*0a6a1f1dSLionel Sambuc   BlkExprs.push_back(BlkCast);
4747*0a6a1f1dSLionel Sambuc   // Add the user arguments.
4748*0a6a1f1dSLionel Sambuc   for (CallExpr::arg_iterator I = Exp->arg_begin(),
4749*0a6a1f1dSLionel Sambuc        E = Exp->arg_end(); I != E; ++I) {
4750*0a6a1f1dSLionel Sambuc     BlkExprs.push_back(*I);
4751*0a6a1f1dSLionel Sambuc   }
4752*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4753*0a6a1f1dSLionel Sambuc                                         Exp->getType(), VK_RValue,
4754*0a6a1f1dSLionel Sambuc                                         SourceLocation());
4755*0a6a1f1dSLionel Sambuc   return CE;
4756*0a6a1f1dSLionel Sambuc }
4757*0a6a1f1dSLionel Sambuc 
4758*0a6a1f1dSLionel Sambuc // We need to return the rewritten expression to handle cases where the
4759*0a6a1f1dSLionel Sambuc // DeclRefExpr is embedded in another expression being rewritten.
4760*0a6a1f1dSLionel Sambuc // For example:
4761*0a6a1f1dSLionel Sambuc //
4762*0a6a1f1dSLionel Sambuc // int main() {
4763*0a6a1f1dSLionel Sambuc //    __block Foo *f;
4764*0a6a1f1dSLionel Sambuc //    __block int i;
4765*0a6a1f1dSLionel Sambuc //
4766*0a6a1f1dSLionel Sambuc //    void (^myblock)() = ^() {
4767*0a6a1f1dSLionel Sambuc //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4768*0a6a1f1dSLionel Sambuc //        i = 77;
4769*0a6a1f1dSLionel Sambuc //    };
4770*0a6a1f1dSLionel Sambuc //}
RewriteBlockDeclRefExpr(DeclRefExpr * DeclRefExp)4771*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4772*0a6a1f1dSLionel Sambuc   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4773*0a6a1f1dSLionel Sambuc   // for each DeclRefExp where BYREFVAR is name of the variable.
4774*0a6a1f1dSLionel Sambuc   ValueDecl *VD = DeclRefExp->getDecl();
4775*0a6a1f1dSLionel Sambuc   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4776*0a6a1f1dSLionel Sambuc                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4777*0a6a1f1dSLionel Sambuc 
4778*0a6a1f1dSLionel Sambuc   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4779*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
4780*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("__forwarding"),
4781*0a6a1f1dSLionel Sambuc                                     Context->VoidPtrTy, nullptr,
4782*0a6a1f1dSLionel Sambuc                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4783*0a6a1f1dSLionel Sambuc                                     ICIS_NoInit);
4784*0a6a1f1dSLionel Sambuc   MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4785*0a6a1f1dSLionel Sambuc                                             FD, SourceLocation(),
4786*0a6a1f1dSLionel Sambuc                                             FD->getType(), VK_LValue,
4787*0a6a1f1dSLionel Sambuc                                             OK_Ordinary);
4788*0a6a1f1dSLionel Sambuc 
4789*0a6a1f1dSLionel Sambuc   StringRef Name = VD->getName();
4790*0a6a1f1dSLionel Sambuc   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4791*0a6a1f1dSLionel Sambuc                          &Context->Idents.get(Name),
4792*0a6a1f1dSLionel Sambuc                          Context->VoidPtrTy, nullptr,
4793*0a6a1f1dSLionel Sambuc                          /*BitWidth=*/nullptr, /*Mutable=*/true,
4794*0a6a1f1dSLionel Sambuc                          ICIS_NoInit);
4795*0a6a1f1dSLionel Sambuc   ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4796*0a6a1f1dSLionel Sambuc                                 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4797*0a6a1f1dSLionel Sambuc 
4798*0a6a1f1dSLionel Sambuc 
4799*0a6a1f1dSLionel Sambuc 
4800*0a6a1f1dSLionel Sambuc   // Need parens to enforce precedence.
4801*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4802*0a6a1f1dSLionel Sambuc                                           DeclRefExp->getExprLoc(),
4803*0a6a1f1dSLionel Sambuc                                           ME);
4804*0a6a1f1dSLionel Sambuc   ReplaceStmt(DeclRefExp, PE);
4805*0a6a1f1dSLionel Sambuc   return PE;
4806*0a6a1f1dSLionel Sambuc }
4807*0a6a1f1dSLionel Sambuc 
4808*0a6a1f1dSLionel Sambuc // Rewrites the imported local variable V with external storage
4809*0a6a1f1dSLionel Sambuc // (static, extern, etc.) as *V
4810*0a6a1f1dSLionel Sambuc //
RewriteLocalVariableExternalStorage(DeclRefExpr * DRE)4811*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4812*0a6a1f1dSLionel Sambuc   ValueDecl *VD = DRE->getDecl();
4813*0a6a1f1dSLionel Sambuc   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4814*0a6a1f1dSLionel Sambuc     if (!ImportedLocalExternalDecls.count(Var))
4815*0a6a1f1dSLionel Sambuc       return DRE;
4816*0a6a1f1dSLionel Sambuc   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4817*0a6a1f1dSLionel Sambuc                                           VK_LValue, OK_Ordinary,
4818*0a6a1f1dSLionel Sambuc                                           DRE->getLocation());
4819*0a6a1f1dSLionel Sambuc   // Need parens to enforce precedence.
4820*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4821*0a6a1f1dSLionel Sambuc                                           Exp);
4822*0a6a1f1dSLionel Sambuc   ReplaceStmt(DRE, PE);
4823*0a6a1f1dSLionel Sambuc   return PE;
4824*0a6a1f1dSLionel Sambuc }
4825*0a6a1f1dSLionel Sambuc 
RewriteCastExpr(CStyleCastExpr * CE)4826*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4827*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CE->getLParenLoc();
4828*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = CE->getRParenLoc();
4829*0a6a1f1dSLionel Sambuc 
4830*0a6a1f1dSLionel Sambuc   // Need to avoid trying to rewrite synthesized casts.
4831*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
4832*0a6a1f1dSLionel Sambuc     return;
4833*0a6a1f1dSLionel Sambuc   // Need to avoid trying to rewrite casts contained in macros.
4834*0a6a1f1dSLionel Sambuc   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4835*0a6a1f1dSLionel Sambuc     return;
4836*0a6a1f1dSLionel Sambuc 
4837*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
4838*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
4839*0a6a1f1dSLionel Sambuc   QualType QT = CE->getType();
4840*0a6a1f1dSLionel Sambuc   const Type* TypePtr = QT->getAs<Type>();
4841*0a6a1f1dSLionel Sambuc   if (isa<TypeOfExprType>(TypePtr)) {
4842*0a6a1f1dSLionel Sambuc     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4843*0a6a1f1dSLionel Sambuc     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4844*0a6a1f1dSLionel Sambuc     std::string TypeAsString = "(";
4845*0a6a1f1dSLionel Sambuc     RewriteBlockPointerType(TypeAsString, QT);
4846*0a6a1f1dSLionel Sambuc     TypeAsString += ")";
4847*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4848*0a6a1f1dSLionel Sambuc     return;
4849*0a6a1f1dSLionel Sambuc   }
4850*0a6a1f1dSLionel Sambuc   // advance the location to startArgList.
4851*0a6a1f1dSLionel Sambuc   const char *argPtr = startBuf;
4852*0a6a1f1dSLionel Sambuc 
4853*0a6a1f1dSLionel Sambuc   while (*argPtr++ && (argPtr < endBuf)) {
4854*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
4855*0a6a1f1dSLionel Sambuc     case '^':
4856*0a6a1f1dSLionel Sambuc       // Replace the '^' with '*'.
4857*0a6a1f1dSLionel Sambuc       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4858*0a6a1f1dSLionel Sambuc       ReplaceText(LocStart, 1, "*");
4859*0a6a1f1dSLionel Sambuc       break;
4860*0a6a1f1dSLionel Sambuc     }
4861*0a6a1f1dSLionel Sambuc   }
4862*0a6a1f1dSLionel Sambuc   return;
4863*0a6a1f1dSLionel Sambuc }
4864*0a6a1f1dSLionel Sambuc 
RewriteImplicitCastObjCExpr(CastExpr * IC)4865*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4866*0a6a1f1dSLionel Sambuc   CastKind CastKind = IC->getCastKind();
4867*0a6a1f1dSLionel Sambuc   if (CastKind != CK_BlockPointerToObjCPointerCast &&
4868*0a6a1f1dSLionel Sambuc       CastKind != CK_AnyPointerToBlockPointerCast)
4869*0a6a1f1dSLionel Sambuc     return;
4870*0a6a1f1dSLionel Sambuc 
4871*0a6a1f1dSLionel Sambuc   QualType QT = IC->getType();
4872*0a6a1f1dSLionel Sambuc   (void)convertBlockPointerToFunctionPointer(QT);
4873*0a6a1f1dSLionel Sambuc   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4874*0a6a1f1dSLionel Sambuc   std::string Str = "(";
4875*0a6a1f1dSLionel Sambuc   Str += TypeString;
4876*0a6a1f1dSLionel Sambuc   Str += ")";
4877*0a6a1f1dSLionel Sambuc   InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4878*0a6a1f1dSLionel Sambuc 
4879*0a6a1f1dSLionel Sambuc   return;
4880*0a6a1f1dSLionel Sambuc }
4881*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerFunctionArgs(FunctionDecl * FD)4882*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4883*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = FD->getLocation();
4884*0a6a1f1dSLionel Sambuc   unsigned parenCount = 0;
4885*0a6a1f1dSLionel Sambuc 
4886*0a6a1f1dSLionel Sambuc   // We have 1 or more arguments that have closure pointers.
4887*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
4888*0a6a1f1dSLionel Sambuc   const char *startArgList = strchr(startBuf, '(');
4889*0a6a1f1dSLionel Sambuc 
4890*0a6a1f1dSLionel Sambuc   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4891*0a6a1f1dSLionel Sambuc 
4892*0a6a1f1dSLionel Sambuc   parenCount++;
4893*0a6a1f1dSLionel Sambuc   // advance the location to startArgList.
4894*0a6a1f1dSLionel Sambuc   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4895*0a6a1f1dSLionel Sambuc   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4896*0a6a1f1dSLionel Sambuc 
4897*0a6a1f1dSLionel Sambuc   const char *argPtr = startArgList;
4898*0a6a1f1dSLionel Sambuc 
4899*0a6a1f1dSLionel Sambuc   while (*argPtr++ && parenCount) {
4900*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
4901*0a6a1f1dSLionel Sambuc     case '^':
4902*0a6a1f1dSLionel Sambuc       // Replace the '^' with '*'.
4903*0a6a1f1dSLionel Sambuc       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4904*0a6a1f1dSLionel Sambuc       ReplaceText(DeclLoc, 1, "*");
4905*0a6a1f1dSLionel Sambuc       break;
4906*0a6a1f1dSLionel Sambuc     case '(':
4907*0a6a1f1dSLionel Sambuc       parenCount++;
4908*0a6a1f1dSLionel Sambuc       break;
4909*0a6a1f1dSLionel Sambuc     case ')':
4910*0a6a1f1dSLionel Sambuc       parenCount--;
4911*0a6a1f1dSLionel Sambuc       break;
4912*0a6a1f1dSLionel Sambuc     }
4913*0a6a1f1dSLionel Sambuc   }
4914*0a6a1f1dSLionel Sambuc   return;
4915*0a6a1f1dSLionel Sambuc }
4916*0a6a1f1dSLionel Sambuc 
PointerTypeTakesAnyBlockArguments(QualType QT)4917*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4918*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP;
4919*0a6a1f1dSLionel Sambuc   const PointerType *PT = QT->getAs<PointerType>();
4920*0a6a1f1dSLionel Sambuc   if (PT) {
4921*0a6a1f1dSLionel Sambuc     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4922*0a6a1f1dSLionel Sambuc   } else {
4923*0a6a1f1dSLionel Sambuc     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4924*0a6a1f1dSLionel Sambuc     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4925*0a6a1f1dSLionel Sambuc     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4926*0a6a1f1dSLionel Sambuc   }
4927*0a6a1f1dSLionel Sambuc   if (FTP) {
4928*0a6a1f1dSLionel Sambuc     for (const auto &I : FTP->param_types())
4929*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(I))
4930*0a6a1f1dSLionel Sambuc         return true;
4931*0a6a1f1dSLionel Sambuc   }
4932*0a6a1f1dSLionel Sambuc   return false;
4933*0a6a1f1dSLionel Sambuc }
4934*0a6a1f1dSLionel Sambuc 
PointerTypeTakesAnyObjCQualifiedType(QualType QT)4935*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4936*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP;
4937*0a6a1f1dSLionel Sambuc   const PointerType *PT = QT->getAs<PointerType>();
4938*0a6a1f1dSLionel Sambuc   if (PT) {
4939*0a6a1f1dSLionel Sambuc     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4940*0a6a1f1dSLionel Sambuc   } else {
4941*0a6a1f1dSLionel Sambuc     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4942*0a6a1f1dSLionel Sambuc     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4943*0a6a1f1dSLionel Sambuc     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4944*0a6a1f1dSLionel Sambuc   }
4945*0a6a1f1dSLionel Sambuc   if (FTP) {
4946*0a6a1f1dSLionel Sambuc     for (const auto &I : FTP->param_types()) {
4947*0a6a1f1dSLionel Sambuc       if (I->isObjCQualifiedIdType())
4948*0a6a1f1dSLionel Sambuc         return true;
4949*0a6a1f1dSLionel Sambuc       if (I->isObjCObjectPointerType() &&
4950*0a6a1f1dSLionel Sambuc           I->getPointeeType()->isObjCQualifiedInterfaceType())
4951*0a6a1f1dSLionel Sambuc         return true;
4952*0a6a1f1dSLionel Sambuc     }
4953*0a6a1f1dSLionel Sambuc 
4954*0a6a1f1dSLionel Sambuc   }
4955*0a6a1f1dSLionel Sambuc   return false;
4956*0a6a1f1dSLionel Sambuc }
4957*0a6a1f1dSLionel Sambuc 
GetExtentOfArgList(const char * Name,const char * & LParen,const char * & RParen)4958*0a6a1f1dSLionel Sambuc void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4959*0a6a1f1dSLionel Sambuc                                      const char *&RParen) {
4960*0a6a1f1dSLionel Sambuc   const char *argPtr = strchr(Name, '(');
4961*0a6a1f1dSLionel Sambuc   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4962*0a6a1f1dSLionel Sambuc 
4963*0a6a1f1dSLionel Sambuc   LParen = argPtr; // output the start.
4964*0a6a1f1dSLionel Sambuc   argPtr++; // skip past the left paren.
4965*0a6a1f1dSLionel Sambuc   unsigned parenCount = 1;
4966*0a6a1f1dSLionel Sambuc 
4967*0a6a1f1dSLionel Sambuc   while (*argPtr && parenCount) {
4968*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
4969*0a6a1f1dSLionel Sambuc     case '(': parenCount++; break;
4970*0a6a1f1dSLionel Sambuc     case ')': parenCount--; break;
4971*0a6a1f1dSLionel Sambuc     default: break;
4972*0a6a1f1dSLionel Sambuc     }
4973*0a6a1f1dSLionel Sambuc     if (parenCount) argPtr++;
4974*0a6a1f1dSLionel Sambuc   }
4975*0a6a1f1dSLionel Sambuc   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4976*0a6a1f1dSLionel Sambuc   RParen = argPtr; // output the end
4977*0a6a1f1dSLionel Sambuc }
4978*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerDecl(NamedDecl * ND)4979*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4980*0a6a1f1dSLionel Sambuc   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4981*0a6a1f1dSLionel Sambuc     RewriteBlockPointerFunctionArgs(FD);
4982*0a6a1f1dSLionel Sambuc     return;
4983*0a6a1f1dSLionel Sambuc   }
4984*0a6a1f1dSLionel Sambuc   // Handle Variables and Typedefs.
4985*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getLocation();
4986*0a6a1f1dSLionel Sambuc   QualType DeclT;
4987*0a6a1f1dSLionel Sambuc   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4988*0a6a1f1dSLionel Sambuc     DeclT = VD->getType();
4989*0a6a1f1dSLionel Sambuc   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4990*0a6a1f1dSLionel Sambuc     DeclT = TDD->getUnderlyingType();
4991*0a6a1f1dSLionel Sambuc   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4992*0a6a1f1dSLionel Sambuc     DeclT = FD->getType();
4993*0a6a1f1dSLionel Sambuc   else
4994*0a6a1f1dSLionel Sambuc     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4995*0a6a1f1dSLionel Sambuc 
4996*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
4997*0a6a1f1dSLionel Sambuc   const char *endBuf = startBuf;
4998*0a6a1f1dSLionel Sambuc   // scan backward (from the decl location) for the end of the previous decl.
4999*0a6a1f1dSLionel Sambuc   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5000*0a6a1f1dSLionel Sambuc     startBuf--;
5001*0a6a1f1dSLionel Sambuc   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5002*0a6a1f1dSLionel Sambuc   std::string buf;
5003*0a6a1f1dSLionel Sambuc   unsigned OrigLength=0;
5004*0a6a1f1dSLionel Sambuc   // *startBuf != '^' if we are dealing with a pointer to function that
5005*0a6a1f1dSLionel Sambuc   // may take block argument types (which will be handled below).
5006*0a6a1f1dSLionel Sambuc   if (*startBuf == '^') {
5007*0a6a1f1dSLionel Sambuc     // Replace the '^' with '*', computing a negative offset.
5008*0a6a1f1dSLionel Sambuc     buf = '*';
5009*0a6a1f1dSLionel Sambuc     startBuf++;
5010*0a6a1f1dSLionel Sambuc     OrigLength++;
5011*0a6a1f1dSLionel Sambuc   }
5012*0a6a1f1dSLionel Sambuc   while (*startBuf != ')') {
5013*0a6a1f1dSLionel Sambuc     buf += *startBuf;
5014*0a6a1f1dSLionel Sambuc     startBuf++;
5015*0a6a1f1dSLionel Sambuc     OrigLength++;
5016*0a6a1f1dSLionel Sambuc   }
5017*0a6a1f1dSLionel Sambuc   buf += ')';
5018*0a6a1f1dSLionel Sambuc   OrigLength++;
5019*0a6a1f1dSLionel Sambuc 
5020*0a6a1f1dSLionel Sambuc   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5021*0a6a1f1dSLionel Sambuc       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5022*0a6a1f1dSLionel Sambuc     // Replace the '^' with '*' for arguments.
5023*0a6a1f1dSLionel Sambuc     // Replace id<P> with id/*<>*/
5024*0a6a1f1dSLionel Sambuc     DeclLoc = ND->getLocation();
5025*0a6a1f1dSLionel Sambuc     startBuf = SM->getCharacterData(DeclLoc);
5026*0a6a1f1dSLionel Sambuc     const char *argListBegin, *argListEnd;
5027*0a6a1f1dSLionel Sambuc     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5028*0a6a1f1dSLionel Sambuc     while (argListBegin < argListEnd) {
5029*0a6a1f1dSLionel Sambuc       if (*argListBegin == '^')
5030*0a6a1f1dSLionel Sambuc         buf += '*';
5031*0a6a1f1dSLionel Sambuc       else if (*argListBegin ==  '<') {
5032*0a6a1f1dSLionel Sambuc         buf += "/*";
5033*0a6a1f1dSLionel Sambuc         buf += *argListBegin++;
5034*0a6a1f1dSLionel Sambuc         OrigLength++;
5035*0a6a1f1dSLionel Sambuc         while (*argListBegin != '>') {
5036*0a6a1f1dSLionel Sambuc           buf += *argListBegin++;
5037*0a6a1f1dSLionel Sambuc           OrigLength++;
5038*0a6a1f1dSLionel Sambuc         }
5039*0a6a1f1dSLionel Sambuc         buf += *argListBegin;
5040*0a6a1f1dSLionel Sambuc         buf += "*/";
5041*0a6a1f1dSLionel Sambuc       }
5042*0a6a1f1dSLionel Sambuc       else
5043*0a6a1f1dSLionel Sambuc         buf += *argListBegin;
5044*0a6a1f1dSLionel Sambuc       argListBegin++;
5045*0a6a1f1dSLionel Sambuc       OrigLength++;
5046*0a6a1f1dSLionel Sambuc     }
5047*0a6a1f1dSLionel Sambuc     buf += ')';
5048*0a6a1f1dSLionel Sambuc     OrigLength++;
5049*0a6a1f1dSLionel Sambuc   }
5050*0a6a1f1dSLionel Sambuc   ReplaceText(Start, OrigLength, buf);
5051*0a6a1f1dSLionel Sambuc 
5052*0a6a1f1dSLionel Sambuc   return;
5053*0a6a1f1dSLionel Sambuc }
5054*0a6a1f1dSLionel Sambuc 
5055*0a6a1f1dSLionel Sambuc 
5056*0a6a1f1dSLionel Sambuc /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5057*0a6a1f1dSLionel Sambuc /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5058*0a6a1f1dSLionel Sambuc ///                    struct Block_byref_id_object *src) {
5059*0a6a1f1dSLionel Sambuc ///  _Block_object_assign (&_dest->object, _src->object,
5060*0a6a1f1dSLionel Sambuc ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5061*0a6a1f1dSLionel Sambuc ///                        [|BLOCK_FIELD_IS_WEAK]) // object
5062*0a6a1f1dSLionel Sambuc ///  _Block_object_assign(&_dest->object, _src->object,
5063*0a6a1f1dSLionel Sambuc ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5064*0a6a1f1dSLionel Sambuc ///                       [|BLOCK_FIELD_IS_WEAK]) // block
5065*0a6a1f1dSLionel Sambuc /// }
5066*0a6a1f1dSLionel Sambuc /// And:
5067*0a6a1f1dSLionel Sambuc /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5068*0a6a1f1dSLionel Sambuc ///  _Block_object_dispose(_src->object,
5069*0a6a1f1dSLionel Sambuc ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5070*0a6a1f1dSLionel Sambuc ///                        [|BLOCK_FIELD_IS_WEAK]) // object
5071*0a6a1f1dSLionel Sambuc ///  _Block_object_dispose(_src->object,
5072*0a6a1f1dSLionel Sambuc ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5073*0a6a1f1dSLionel Sambuc ///                         [|BLOCK_FIELD_IS_WEAK]) // block
5074*0a6a1f1dSLionel Sambuc /// }
5075*0a6a1f1dSLionel Sambuc 
SynthesizeByrefCopyDestroyHelper(VarDecl * VD,int flag)5076*0a6a1f1dSLionel Sambuc std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5077*0a6a1f1dSLionel Sambuc                                                           int flag) {
5078*0a6a1f1dSLionel Sambuc   std::string S;
5079*0a6a1f1dSLionel Sambuc   if (CopyDestroyCache.count(flag))
5080*0a6a1f1dSLionel Sambuc     return S;
5081*0a6a1f1dSLionel Sambuc   CopyDestroyCache.insert(flag);
5082*0a6a1f1dSLionel Sambuc   S = "static void __Block_byref_id_object_copy_";
5083*0a6a1f1dSLionel Sambuc   S += utostr(flag);
5084*0a6a1f1dSLionel Sambuc   S += "(void *dst, void *src) {\n";
5085*0a6a1f1dSLionel Sambuc 
5086*0a6a1f1dSLionel Sambuc   // offset into the object pointer is computed as:
5087*0a6a1f1dSLionel Sambuc   // void * + void* + int + int + void* + void *
5088*0a6a1f1dSLionel Sambuc   unsigned IntSize =
5089*0a6a1f1dSLionel Sambuc   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5090*0a6a1f1dSLionel Sambuc   unsigned VoidPtrSize =
5091*0a6a1f1dSLionel Sambuc   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5092*0a6a1f1dSLionel Sambuc 
5093*0a6a1f1dSLionel Sambuc   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5094*0a6a1f1dSLionel Sambuc   S += " _Block_object_assign((char*)dst + ";
5095*0a6a1f1dSLionel Sambuc   S += utostr(offset);
5096*0a6a1f1dSLionel Sambuc   S += ", *(void * *) ((char*)src + ";
5097*0a6a1f1dSLionel Sambuc   S += utostr(offset);
5098*0a6a1f1dSLionel Sambuc   S += "), ";
5099*0a6a1f1dSLionel Sambuc   S += utostr(flag);
5100*0a6a1f1dSLionel Sambuc   S += ");\n}\n";
5101*0a6a1f1dSLionel Sambuc 
5102*0a6a1f1dSLionel Sambuc   S += "static void __Block_byref_id_object_dispose_";
5103*0a6a1f1dSLionel Sambuc   S += utostr(flag);
5104*0a6a1f1dSLionel Sambuc   S += "(void *src) {\n";
5105*0a6a1f1dSLionel Sambuc   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5106*0a6a1f1dSLionel Sambuc   S += utostr(offset);
5107*0a6a1f1dSLionel Sambuc   S += "), ";
5108*0a6a1f1dSLionel Sambuc   S += utostr(flag);
5109*0a6a1f1dSLionel Sambuc   S += ");\n}\n";
5110*0a6a1f1dSLionel Sambuc   return S;
5111*0a6a1f1dSLionel Sambuc }
5112*0a6a1f1dSLionel Sambuc 
5113*0a6a1f1dSLionel Sambuc /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5114*0a6a1f1dSLionel Sambuc /// the declaration into:
5115*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND {
5116*0a6a1f1dSLionel Sambuc /// void *__isa;                  // NULL for everything except __weak pointers
5117*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND *__forwarding;
5118*0a6a1f1dSLionel Sambuc /// int32_t __flags;
5119*0a6a1f1dSLionel Sambuc /// int32_t __size;
5120*0a6a1f1dSLionel Sambuc /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5121*0a6a1f1dSLionel Sambuc /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5122*0a6a1f1dSLionel Sambuc /// typex ND;
5123*0a6a1f1dSLionel Sambuc /// };
5124*0a6a1f1dSLionel Sambuc ///
5125*0a6a1f1dSLionel Sambuc /// It then replaces declaration of ND variable with:
5126*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5127*0a6a1f1dSLionel Sambuc ///                               __size=sizeof(struct __Block_byref_ND),
5128*0a6a1f1dSLionel Sambuc ///                               ND=initializer-if-any};
5129*0a6a1f1dSLionel Sambuc ///
5130*0a6a1f1dSLionel Sambuc ///
RewriteByRefVar(VarDecl * ND,bool firstDecl,bool lastDecl)5131*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5132*0a6a1f1dSLionel Sambuc                                         bool lastDecl) {
5133*0a6a1f1dSLionel Sambuc   int flag = 0;
5134*0a6a1f1dSLionel Sambuc   int isa = 0;
5135*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5136*0a6a1f1dSLionel Sambuc   if (DeclLoc.isInvalid())
5137*0a6a1f1dSLionel Sambuc     // If type location is missing, it is because of missing type (a warning).
5138*0a6a1f1dSLionel Sambuc     // Use variable's location which is good for this case.
5139*0a6a1f1dSLionel Sambuc     DeclLoc = ND->getLocation();
5140*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
5141*0a6a1f1dSLionel Sambuc   SourceLocation X = ND->getLocEnd();
5142*0a6a1f1dSLionel Sambuc   X = SM->getExpansionLoc(X);
5143*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(X);
5144*0a6a1f1dSLionel Sambuc   std::string Name(ND->getNameAsString());
5145*0a6a1f1dSLionel Sambuc   std::string ByrefType;
5146*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND, true);
5147*0a6a1f1dSLionel Sambuc   ByrefType += " {\n";
5148*0a6a1f1dSLionel Sambuc   ByrefType += "  void *__isa;\n";
5149*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND);
5150*0a6a1f1dSLionel Sambuc   ByrefType += " *__forwarding;\n";
5151*0a6a1f1dSLionel Sambuc   ByrefType += " int __flags;\n";
5152*0a6a1f1dSLionel Sambuc   ByrefType += " int __size;\n";
5153*0a6a1f1dSLionel Sambuc   // Add void *__Block_byref_id_object_copy;
5154*0a6a1f1dSLionel Sambuc   // void *__Block_byref_id_object_dispose; if needed.
5155*0a6a1f1dSLionel Sambuc   QualType Ty = ND->getType();
5156*0a6a1f1dSLionel Sambuc   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5157*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose) {
5158*0a6a1f1dSLionel Sambuc     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5159*0a6a1f1dSLionel Sambuc     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5160*0a6a1f1dSLionel Sambuc   }
5161*0a6a1f1dSLionel Sambuc 
5162*0a6a1f1dSLionel Sambuc   QualType T = Ty;
5163*0a6a1f1dSLionel Sambuc   (void)convertBlockPointerToFunctionPointer(T);
5164*0a6a1f1dSLionel Sambuc   T.getAsStringInternal(Name, Context->getPrintingPolicy());
5165*0a6a1f1dSLionel Sambuc 
5166*0a6a1f1dSLionel Sambuc   ByrefType += " " + Name + ";\n";
5167*0a6a1f1dSLionel Sambuc   ByrefType += "};\n";
5168*0a6a1f1dSLionel Sambuc   // Insert this type in global scope. It is needed by helper function.
5169*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart;
5170*0a6a1f1dSLionel Sambuc   if (CurFunctionDef)
5171*0a6a1f1dSLionel Sambuc      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5172*0a6a1f1dSLionel Sambuc   else {
5173*0a6a1f1dSLionel Sambuc     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5174*0a6a1f1dSLionel Sambuc     FunLocStart = CurMethodDef->getLocStart();
5175*0a6a1f1dSLionel Sambuc   }
5176*0a6a1f1dSLionel Sambuc   InsertText(FunLocStart, ByrefType);
5177*0a6a1f1dSLionel Sambuc 
5178*0a6a1f1dSLionel Sambuc   if (Ty.isObjCGCWeak()) {
5179*0a6a1f1dSLionel Sambuc     flag |= BLOCK_FIELD_IS_WEAK;
5180*0a6a1f1dSLionel Sambuc     isa = 1;
5181*0a6a1f1dSLionel Sambuc   }
5182*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose) {
5183*0a6a1f1dSLionel Sambuc     flag = BLOCK_BYREF_CALLER;
5184*0a6a1f1dSLionel Sambuc     QualType Ty = ND->getType();
5185*0a6a1f1dSLionel Sambuc     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5186*0a6a1f1dSLionel Sambuc     if (Ty->isBlockPointerType())
5187*0a6a1f1dSLionel Sambuc       flag |= BLOCK_FIELD_IS_BLOCK;
5188*0a6a1f1dSLionel Sambuc     else
5189*0a6a1f1dSLionel Sambuc       flag |= BLOCK_FIELD_IS_OBJECT;
5190*0a6a1f1dSLionel Sambuc     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5191*0a6a1f1dSLionel Sambuc     if (!HF.empty())
5192*0a6a1f1dSLionel Sambuc       Preamble += HF;
5193*0a6a1f1dSLionel Sambuc   }
5194*0a6a1f1dSLionel Sambuc 
5195*0a6a1f1dSLionel Sambuc   // struct __Block_byref_ND ND =
5196*0a6a1f1dSLionel Sambuc   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5197*0a6a1f1dSLionel Sambuc   //  initializer-if-any};
5198*0a6a1f1dSLionel Sambuc   bool hasInit = (ND->getInit() != nullptr);
5199*0a6a1f1dSLionel Sambuc   // FIXME. rewriter does not support __block c++ objects which
5200*0a6a1f1dSLionel Sambuc   // require construction.
5201*0a6a1f1dSLionel Sambuc   if (hasInit)
5202*0a6a1f1dSLionel Sambuc     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5203*0a6a1f1dSLionel Sambuc       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5204*0a6a1f1dSLionel Sambuc       if (CXXDecl && CXXDecl->isDefaultConstructor())
5205*0a6a1f1dSLionel Sambuc         hasInit = false;
5206*0a6a1f1dSLionel Sambuc     }
5207*0a6a1f1dSLionel Sambuc 
5208*0a6a1f1dSLionel Sambuc   unsigned flags = 0;
5209*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose)
5210*0a6a1f1dSLionel Sambuc     flags |= BLOCK_HAS_COPY_DISPOSE;
5211*0a6a1f1dSLionel Sambuc   Name = ND->getNameAsString();
5212*0a6a1f1dSLionel Sambuc   ByrefType.clear();
5213*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND);
5214*0a6a1f1dSLionel Sambuc   std::string ForwardingCastType("(");
5215*0a6a1f1dSLionel Sambuc   ForwardingCastType += ByrefType + " *)";
5216*0a6a1f1dSLionel Sambuc   ByrefType += " " + Name + " = {(void*)";
5217*0a6a1f1dSLionel Sambuc   ByrefType += utostr(isa);
5218*0a6a1f1dSLionel Sambuc   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5219*0a6a1f1dSLionel Sambuc   ByrefType += utostr(flags);
5220*0a6a1f1dSLionel Sambuc   ByrefType += ", ";
5221*0a6a1f1dSLionel Sambuc   ByrefType += "sizeof(";
5222*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND);
5223*0a6a1f1dSLionel Sambuc   ByrefType += ")";
5224*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose) {
5225*0a6a1f1dSLionel Sambuc     ByrefType += ", __Block_byref_id_object_copy_";
5226*0a6a1f1dSLionel Sambuc     ByrefType += utostr(flag);
5227*0a6a1f1dSLionel Sambuc     ByrefType += ", __Block_byref_id_object_dispose_";
5228*0a6a1f1dSLionel Sambuc     ByrefType += utostr(flag);
5229*0a6a1f1dSLionel Sambuc   }
5230*0a6a1f1dSLionel Sambuc 
5231*0a6a1f1dSLionel Sambuc   if (!firstDecl) {
5232*0a6a1f1dSLionel Sambuc     // In multiple __block declarations, and for all but 1st declaration,
5233*0a6a1f1dSLionel Sambuc     // find location of the separating comma. This would be start location
5234*0a6a1f1dSLionel Sambuc     // where new text is to be inserted.
5235*0a6a1f1dSLionel Sambuc     DeclLoc = ND->getLocation();
5236*0a6a1f1dSLionel Sambuc     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5237*0a6a1f1dSLionel Sambuc     const char *commaBuf = startDeclBuf;
5238*0a6a1f1dSLionel Sambuc     while (*commaBuf != ',')
5239*0a6a1f1dSLionel Sambuc       commaBuf--;
5240*0a6a1f1dSLionel Sambuc     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5241*0a6a1f1dSLionel Sambuc     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5242*0a6a1f1dSLionel Sambuc     startBuf = commaBuf;
5243*0a6a1f1dSLionel Sambuc   }
5244*0a6a1f1dSLionel Sambuc 
5245*0a6a1f1dSLionel Sambuc   if (!hasInit) {
5246*0a6a1f1dSLionel Sambuc     ByrefType += "};\n";
5247*0a6a1f1dSLionel Sambuc     unsigned nameSize = Name.size();
5248*0a6a1f1dSLionel Sambuc     // for block or function pointer declaration. Name is aleady
5249*0a6a1f1dSLionel Sambuc     // part of the declaration.
5250*0a6a1f1dSLionel Sambuc     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5251*0a6a1f1dSLionel Sambuc       nameSize = 1;
5252*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5253*0a6a1f1dSLionel Sambuc   }
5254*0a6a1f1dSLionel Sambuc   else {
5255*0a6a1f1dSLionel Sambuc     ByrefType += ", ";
5256*0a6a1f1dSLionel Sambuc     SourceLocation startLoc;
5257*0a6a1f1dSLionel Sambuc     Expr *E = ND->getInit();
5258*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5259*0a6a1f1dSLionel Sambuc       startLoc = ECE->getLParenLoc();
5260*0a6a1f1dSLionel Sambuc     else
5261*0a6a1f1dSLionel Sambuc       startLoc = E->getLocStart();
5262*0a6a1f1dSLionel Sambuc     startLoc = SM->getExpansionLoc(startLoc);
5263*0a6a1f1dSLionel Sambuc     endBuf = SM->getCharacterData(startLoc);
5264*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5265*0a6a1f1dSLionel Sambuc 
5266*0a6a1f1dSLionel Sambuc     const char separator = lastDecl ? ';' : ',';
5267*0a6a1f1dSLionel Sambuc     const char *startInitializerBuf = SM->getCharacterData(startLoc);
5268*0a6a1f1dSLionel Sambuc     const char *separatorBuf = strchr(startInitializerBuf, separator);
5269*0a6a1f1dSLionel Sambuc     assert((*separatorBuf == separator) &&
5270*0a6a1f1dSLionel Sambuc            "RewriteByRefVar: can't find ';' or ','");
5271*0a6a1f1dSLionel Sambuc     SourceLocation separatorLoc =
5272*0a6a1f1dSLionel Sambuc       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5273*0a6a1f1dSLionel Sambuc 
5274*0a6a1f1dSLionel Sambuc     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5275*0a6a1f1dSLionel Sambuc   }
5276*0a6a1f1dSLionel Sambuc   return;
5277*0a6a1f1dSLionel Sambuc }
5278*0a6a1f1dSLionel Sambuc 
CollectBlockDeclRefInfo(BlockExpr * Exp)5279*0a6a1f1dSLionel Sambuc void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5280*0a6a1f1dSLionel Sambuc   // Add initializers for any closure decl refs.
5281*0a6a1f1dSLionel Sambuc   GetBlockDeclRefExprs(Exp->getBody());
5282*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
5283*0a6a1f1dSLionel Sambuc     // Unique all "by copy" declarations.
5284*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5285*0a6a1f1dSLionel Sambuc       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5286*0a6a1f1dSLionel Sambuc         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5287*0a6a1f1dSLionel Sambuc           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5288*0a6a1f1dSLionel Sambuc           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5289*0a6a1f1dSLionel Sambuc         }
5290*0a6a1f1dSLionel Sambuc       }
5291*0a6a1f1dSLionel Sambuc     // Unique all "by ref" declarations.
5292*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5293*0a6a1f1dSLionel Sambuc       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5294*0a6a1f1dSLionel Sambuc         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5295*0a6a1f1dSLionel Sambuc           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5296*0a6a1f1dSLionel Sambuc           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5297*0a6a1f1dSLionel Sambuc         }
5298*0a6a1f1dSLionel Sambuc       }
5299*0a6a1f1dSLionel Sambuc     // Find any imported blocks...they will need special attention.
5300*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5301*0a6a1f1dSLionel Sambuc       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5302*0a6a1f1dSLionel Sambuc           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5303*0a6a1f1dSLionel Sambuc           BlockDeclRefs[i]->getType()->isBlockPointerType())
5304*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5305*0a6a1f1dSLionel Sambuc   }
5306*0a6a1f1dSLionel Sambuc }
5307*0a6a1f1dSLionel Sambuc 
SynthBlockInitFunctionDecl(StringRef name)5308*0a6a1f1dSLionel Sambuc FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5309*0a6a1f1dSLionel Sambuc   IdentifierInfo *ID = &Context->Idents.get(name);
5310*0a6a1f1dSLionel Sambuc   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5311*0a6a1f1dSLionel Sambuc   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5312*0a6a1f1dSLionel Sambuc                               SourceLocation(), ID, FType, nullptr, SC_Extern,
5313*0a6a1f1dSLionel Sambuc                               false, false);
5314*0a6a1f1dSLionel Sambuc }
5315*0a6a1f1dSLionel Sambuc 
SynthBlockInitExpr(BlockExpr * Exp,const SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs)5316*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5317*0a6a1f1dSLionel Sambuc                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5318*0a6a1f1dSLionel Sambuc 
5319*0a6a1f1dSLionel Sambuc   const BlockDecl *block = Exp->getBlockDecl();
5320*0a6a1f1dSLionel Sambuc 
5321*0a6a1f1dSLionel Sambuc   Blocks.push_back(Exp);
5322*0a6a1f1dSLionel Sambuc 
5323*0a6a1f1dSLionel Sambuc   CollectBlockDeclRefInfo(Exp);
5324*0a6a1f1dSLionel Sambuc 
5325*0a6a1f1dSLionel Sambuc   // Add inner imported variables now used in current block.
5326*0a6a1f1dSLionel Sambuc  int countOfInnerDecls = 0;
5327*0a6a1f1dSLionel Sambuc   if (!InnerBlockDeclRefs.empty()) {
5328*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5329*0a6a1f1dSLionel Sambuc       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5330*0a6a1f1dSLionel Sambuc       ValueDecl *VD = Exp->getDecl();
5331*0a6a1f1dSLionel Sambuc       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5332*0a6a1f1dSLionel Sambuc       // We need to save the copied-in variables in nested
5333*0a6a1f1dSLionel Sambuc       // blocks because it is needed at the end for some of the API generations.
5334*0a6a1f1dSLionel Sambuc       // See SynthesizeBlockLiterals routine.
5335*0a6a1f1dSLionel Sambuc         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5336*0a6a1f1dSLionel Sambuc         BlockDeclRefs.push_back(Exp);
5337*0a6a1f1dSLionel Sambuc         BlockByCopyDeclsPtrSet.insert(VD);
5338*0a6a1f1dSLionel Sambuc         BlockByCopyDecls.push_back(VD);
5339*0a6a1f1dSLionel Sambuc       }
5340*0a6a1f1dSLionel Sambuc       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5341*0a6a1f1dSLionel Sambuc         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5342*0a6a1f1dSLionel Sambuc         BlockDeclRefs.push_back(Exp);
5343*0a6a1f1dSLionel Sambuc         BlockByRefDeclsPtrSet.insert(VD);
5344*0a6a1f1dSLionel Sambuc         BlockByRefDecls.push_back(VD);
5345*0a6a1f1dSLionel Sambuc       }
5346*0a6a1f1dSLionel Sambuc     }
5347*0a6a1f1dSLionel Sambuc     // Find any imported blocks...they will need special attention.
5348*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5349*0a6a1f1dSLionel Sambuc       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5350*0a6a1f1dSLionel Sambuc           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5351*0a6a1f1dSLionel Sambuc           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5352*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5353*0a6a1f1dSLionel Sambuc   }
5354*0a6a1f1dSLionel Sambuc   InnerDeclRefsCount.push_back(countOfInnerDecls);
5355*0a6a1f1dSLionel Sambuc 
5356*0a6a1f1dSLionel Sambuc   std::string FuncName;
5357*0a6a1f1dSLionel Sambuc 
5358*0a6a1f1dSLionel Sambuc   if (CurFunctionDef)
5359*0a6a1f1dSLionel Sambuc     FuncName = CurFunctionDef->getNameAsString();
5360*0a6a1f1dSLionel Sambuc   else if (CurMethodDef)
5361*0a6a1f1dSLionel Sambuc     BuildUniqueMethodName(FuncName, CurMethodDef);
5362*0a6a1f1dSLionel Sambuc   else if (GlobalVarDecl)
5363*0a6a1f1dSLionel Sambuc     FuncName = std::string(GlobalVarDecl->getNameAsString());
5364*0a6a1f1dSLionel Sambuc 
5365*0a6a1f1dSLionel Sambuc   bool GlobalBlockExpr =
5366*0a6a1f1dSLionel Sambuc     block->getDeclContext()->getRedeclContext()->isFileContext();
5367*0a6a1f1dSLionel Sambuc 
5368*0a6a1f1dSLionel Sambuc   if (GlobalBlockExpr && !GlobalVarDecl) {
5369*0a6a1f1dSLionel Sambuc     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5370*0a6a1f1dSLionel Sambuc     GlobalBlockExpr = false;
5371*0a6a1f1dSLionel Sambuc   }
5372*0a6a1f1dSLionel Sambuc 
5373*0a6a1f1dSLionel Sambuc   std::string BlockNumber = utostr(Blocks.size()-1);
5374*0a6a1f1dSLionel Sambuc 
5375*0a6a1f1dSLionel Sambuc   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5376*0a6a1f1dSLionel Sambuc 
5377*0a6a1f1dSLionel Sambuc   // Get a pointer to the function type so we can cast appropriately.
5378*0a6a1f1dSLionel Sambuc   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5379*0a6a1f1dSLionel Sambuc   QualType FType = Context->getPointerType(BFT);
5380*0a6a1f1dSLionel Sambuc 
5381*0a6a1f1dSLionel Sambuc   FunctionDecl *FD;
5382*0a6a1f1dSLionel Sambuc   Expr *NewRep;
5383*0a6a1f1dSLionel Sambuc 
5384*0a6a1f1dSLionel Sambuc   // Simulate a constructor call...
5385*0a6a1f1dSLionel Sambuc   std::string Tag;
5386*0a6a1f1dSLionel Sambuc 
5387*0a6a1f1dSLionel Sambuc   if (GlobalBlockExpr)
5388*0a6a1f1dSLionel Sambuc     Tag = "__global_";
5389*0a6a1f1dSLionel Sambuc   else
5390*0a6a1f1dSLionel Sambuc     Tag = "__";
5391*0a6a1f1dSLionel Sambuc   Tag += FuncName + "_block_impl_" + BlockNumber;
5392*0a6a1f1dSLionel Sambuc 
5393*0a6a1f1dSLionel Sambuc   FD = SynthBlockInitFunctionDecl(Tag);
5394*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5395*0a6a1f1dSLionel Sambuc                                                SourceLocation());
5396*0a6a1f1dSLionel Sambuc 
5397*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> InitExprs;
5398*0a6a1f1dSLionel Sambuc 
5399*0a6a1f1dSLionel Sambuc   // Initialize the block function.
5400*0a6a1f1dSLionel Sambuc   FD = SynthBlockInitFunctionDecl(Func);
5401*0a6a1f1dSLionel Sambuc   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5402*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
5403*0a6a1f1dSLionel Sambuc   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5404*0a6a1f1dSLionel Sambuc                                                 CK_BitCast, Arg);
5405*0a6a1f1dSLionel Sambuc   InitExprs.push_back(castExpr);
5406*0a6a1f1dSLionel Sambuc 
5407*0a6a1f1dSLionel Sambuc   // Initialize the block descriptor.
5408*0a6a1f1dSLionel Sambuc   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5409*0a6a1f1dSLionel Sambuc 
5410*0a6a1f1dSLionel Sambuc   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5411*0a6a1f1dSLionel Sambuc                                    SourceLocation(), SourceLocation(),
5412*0a6a1f1dSLionel Sambuc                                    &Context->Idents.get(DescData.c_str()),
5413*0a6a1f1dSLionel Sambuc                                    Context->VoidPtrTy, nullptr,
5414*0a6a1f1dSLionel Sambuc                                    SC_Static);
5415*0a6a1f1dSLionel Sambuc   UnaryOperator *DescRefExpr =
5416*0a6a1f1dSLionel Sambuc     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5417*0a6a1f1dSLionel Sambuc                                                           Context->VoidPtrTy,
5418*0a6a1f1dSLionel Sambuc                                                           VK_LValue,
5419*0a6a1f1dSLionel Sambuc                                                           SourceLocation()),
5420*0a6a1f1dSLionel Sambuc                                 UO_AddrOf,
5421*0a6a1f1dSLionel Sambuc                                 Context->getPointerType(Context->VoidPtrTy),
5422*0a6a1f1dSLionel Sambuc                                 VK_RValue, OK_Ordinary,
5423*0a6a1f1dSLionel Sambuc                                 SourceLocation());
5424*0a6a1f1dSLionel Sambuc   InitExprs.push_back(DescRefExpr);
5425*0a6a1f1dSLionel Sambuc 
5426*0a6a1f1dSLionel Sambuc   // Add initializers for any closure decl refs.
5427*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
5428*0a6a1f1dSLionel Sambuc     Expr *Exp;
5429*0a6a1f1dSLionel Sambuc     // Output all "by copy" declarations.
5430*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5431*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
5432*0a6a1f1dSLionel Sambuc       if (isObjCType((*I)->getType())) {
5433*0a6a1f1dSLionel Sambuc         // FIXME: Conform to ABI ([[obj retain] autorelease]).
5434*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
5435*0a6a1f1dSLionel Sambuc         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5436*0a6a1f1dSLionel Sambuc                                         VK_LValue, SourceLocation());
5437*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I)) {
5438*0a6a1f1dSLionel Sambuc           QualType QT = (*I)->getType();
5439*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
5440*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5441*0a6a1f1dSLionel Sambuc                                             OK_Ordinary, SourceLocation());
5442*0a6a1f1dSLionel Sambuc         }
5443*0a6a1f1dSLionel Sambuc       } else if (isTopLevelBlockPointerType((*I)->getType())) {
5444*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
5445*0a6a1f1dSLionel Sambuc         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5446*0a6a1f1dSLionel Sambuc                                         VK_LValue, SourceLocation());
5447*0a6a1f1dSLionel Sambuc         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5448*0a6a1f1dSLionel Sambuc                                        CK_BitCast, Arg);
5449*0a6a1f1dSLionel Sambuc       } else {
5450*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
5451*0a6a1f1dSLionel Sambuc         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5452*0a6a1f1dSLionel Sambuc                                         VK_LValue, SourceLocation());
5453*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I)) {
5454*0a6a1f1dSLionel Sambuc           QualType QT = (*I)->getType();
5455*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
5456*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5457*0a6a1f1dSLionel Sambuc                                             OK_Ordinary, SourceLocation());
5458*0a6a1f1dSLionel Sambuc         }
5459*0a6a1f1dSLionel Sambuc 
5460*0a6a1f1dSLionel Sambuc       }
5461*0a6a1f1dSLionel Sambuc       InitExprs.push_back(Exp);
5462*0a6a1f1dSLionel Sambuc     }
5463*0a6a1f1dSLionel Sambuc     // Output all "by ref" declarations.
5464*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5465*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
5466*0a6a1f1dSLionel Sambuc       ValueDecl *ND = (*I);
5467*0a6a1f1dSLionel Sambuc       std::string Name(ND->getNameAsString());
5468*0a6a1f1dSLionel Sambuc       std::string RecName;
5469*0a6a1f1dSLionel Sambuc       RewriteByRefString(RecName, Name, ND, true);
5470*0a6a1f1dSLionel Sambuc       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5471*0a6a1f1dSLionel Sambuc                                                 + sizeof("struct"));
5472*0a6a1f1dSLionel Sambuc       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5473*0a6a1f1dSLionel Sambuc                                           SourceLocation(), SourceLocation(),
5474*0a6a1f1dSLionel Sambuc                                           II);
5475*0a6a1f1dSLionel Sambuc       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5476*0a6a1f1dSLionel Sambuc       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5477*0a6a1f1dSLionel Sambuc 
5478*0a6a1f1dSLionel Sambuc       FD = SynthBlockInitFunctionDecl((*I)->getName());
5479*0a6a1f1dSLionel Sambuc       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5480*0a6a1f1dSLionel Sambuc                                       SourceLocation());
5481*0a6a1f1dSLionel Sambuc       bool isNestedCapturedVar = false;
5482*0a6a1f1dSLionel Sambuc       if (block)
5483*0a6a1f1dSLionel Sambuc         for (const auto &CI : block->captures()) {
5484*0a6a1f1dSLionel Sambuc           const VarDecl *variable = CI.getVariable();
5485*0a6a1f1dSLionel Sambuc           if (variable == ND && CI.isNested()) {
5486*0a6a1f1dSLionel Sambuc             assert (CI.isByRef() &&
5487*0a6a1f1dSLionel Sambuc                     "SynthBlockInitExpr - captured block variable is not byref");
5488*0a6a1f1dSLionel Sambuc             isNestedCapturedVar = true;
5489*0a6a1f1dSLionel Sambuc             break;
5490*0a6a1f1dSLionel Sambuc           }
5491*0a6a1f1dSLionel Sambuc         }
5492*0a6a1f1dSLionel Sambuc       // captured nested byref variable has its address passed. Do not take
5493*0a6a1f1dSLionel Sambuc       // its address again.
5494*0a6a1f1dSLionel Sambuc       if (!isNestedCapturedVar)
5495*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5496*0a6a1f1dSLionel Sambuc                                      Context->getPointerType(Exp->getType()),
5497*0a6a1f1dSLionel Sambuc                                      VK_RValue, OK_Ordinary, SourceLocation());
5498*0a6a1f1dSLionel Sambuc       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5499*0a6a1f1dSLionel Sambuc       InitExprs.push_back(Exp);
5500*0a6a1f1dSLionel Sambuc     }
5501*0a6a1f1dSLionel Sambuc   }
5502*0a6a1f1dSLionel Sambuc   if (ImportedBlockDecls.size()) {
5503*0a6a1f1dSLionel Sambuc     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5504*0a6a1f1dSLionel Sambuc     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5505*0a6a1f1dSLionel Sambuc     unsigned IntSize =
5506*0a6a1f1dSLionel Sambuc       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5507*0a6a1f1dSLionel Sambuc     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5508*0a6a1f1dSLionel Sambuc                                            Context->IntTy, SourceLocation());
5509*0a6a1f1dSLionel Sambuc     InitExprs.push_back(FlagExp);
5510*0a6a1f1dSLionel Sambuc   }
5511*0a6a1f1dSLionel Sambuc   NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5512*0a6a1f1dSLionel Sambuc                                   FType, VK_LValue, SourceLocation());
5513*0a6a1f1dSLionel Sambuc 
5514*0a6a1f1dSLionel Sambuc   if (GlobalBlockExpr) {
5515*0a6a1f1dSLionel Sambuc     assert (!GlobalConstructionExp &&
5516*0a6a1f1dSLionel Sambuc             "SynthBlockInitExpr - GlobalConstructionExp must be null");
5517*0a6a1f1dSLionel Sambuc     GlobalConstructionExp = NewRep;
5518*0a6a1f1dSLionel Sambuc     NewRep = DRE;
5519*0a6a1f1dSLionel Sambuc   }
5520*0a6a1f1dSLionel Sambuc 
5521*0a6a1f1dSLionel Sambuc   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5522*0a6a1f1dSLionel Sambuc                              Context->getPointerType(NewRep->getType()),
5523*0a6a1f1dSLionel Sambuc                              VK_RValue, OK_Ordinary, SourceLocation());
5524*0a6a1f1dSLionel Sambuc   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5525*0a6a1f1dSLionel Sambuc                                     NewRep);
5526*0a6a1f1dSLionel Sambuc   // Put Paren around the call.
5527*0a6a1f1dSLionel Sambuc   NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5528*0a6a1f1dSLionel Sambuc                                    NewRep);
5529*0a6a1f1dSLionel Sambuc 
5530*0a6a1f1dSLionel Sambuc   BlockDeclRefs.clear();
5531*0a6a1f1dSLionel Sambuc   BlockByRefDecls.clear();
5532*0a6a1f1dSLionel Sambuc   BlockByRefDeclsPtrSet.clear();
5533*0a6a1f1dSLionel Sambuc   BlockByCopyDecls.clear();
5534*0a6a1f1dSLionel Sambuc   BlockByCopyDeclsPtrSet.clear();
5535*0a6a1f1dSLionel Sambuc   ImportedBlockDecls.clear();
5536*0a6a1f1dSLionel Sambuc   return NewRep;
5537*0a6a1f1dSLionel Sambuc }
5538*0a6a1f1dSLionel Sambuc 
IsDeclStmtInForeachHeader(DeclStmt * DS)5539*0a6a1f1dSLionel Sambuc bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5540*0a6a1f1dSLionel Sambuc   if (const ObjCForCollectionStmt * CS =
5541*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5542*0a6a1f1dSLionel Sambuc         return CS->getElement() == DS;
5543*0a6a1f1dSLionel Sambuc   return false;
5544*0a6a1f1dSLionel Sambuc }
5545*0a6a1f1dSLionel Sambuc 
5546*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
5547*0a6a1f1dSLionel Sambuc // Function Body / Expression rewriting
5548*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
5549*0a6a1f1dSLionel Sambuc 
RewriteFunctionBodyOrGlobalInitializer(Stmt * S)5550*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5551*0a6a1f1dSLionel Sambuc   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5552*0a6a1f1dSLionel Sambuc       isa<DoStmt>(S) || isa<ForStmt>(S))
5553*0a6a1f1dSLionel Sambuc     Stmts.push_back(S);
5554*0a6a1f1dSLionel Sambuc   else if (isa<ObjCForCollectionStmt>(S)) {
5555*0a6a1f1dSLionel Sambuc     Stmts.push_back(S);
5556*0a6a1f1dSLionel Sambuc     ObjCBcLabelNo.push_back(++BcLabelCount);
5557*0a6a1f1dSLionel Sambuc   }
5558*0a6a1f1dSLionel Sambuc 
5559*0a6a1f1dSLionel Sambuc   // Pseudo-object operations and ivar references need special
5560*0a6a1f1dSLionel Sambuc   // treatment because we're going to recursively rewrite them.
5561*0a6a1f1dSLionel Sambuc   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5562*0a6a1f1dSLionel Sambuc     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5563*0a6a1f1dSLionel Sambuc       return RewritePropertyOrImplicitSetter(PseudoOp);
5564*0a6a1f1dSLionel Sambuc     } else {
5565*0a6a1f1dSLionel Sambuc       return RewritePropertyOrImplicitGetter(PseudoOp);
5566*0a6a1f1dSLionel Sambuc     }
5567*0a6a1f1dSLionel Sambuc   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5568*0a6a1f1dSLionel Sambuc     return RewriteObjCIvarRefExpr(IvarRefExpr);
5569*0a6a1f1dSLionel Sambuc   }
5570*0a6a1f1dSLionel Sambuc   else if (isa<OpaqueValueExpr>(S))
5571*0a6a1f1dSLionel Sambuc     S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5572*0a6a1f1dSLionel Sambuc 
5573*0a6a1f1dSLionel Sambuc   SourceRange OrigStmtRange = S->getSourceRange();
5574*0a6a1f1dSLionel Sambuc 
5575*0a6a1f1dSLionel Sambuc   // Perform a bottom up rewrite of all children.
5576*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
5577*0a6a1f1dSLionel Sambuc     if (*CI) {
5578*0a6a1f1dSLionel Sambuc       Stmt *childStmt = (*CI);
5579*0a6a1f1dSLionel Sambuc       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5580*0a6a1f1dSLionel Sambuc       if (newStmt) {
5581*0a6a1f1dSLionel Sambuc         *CI = newStmt;
5582*0a6a1f1dSLionel Sambuc       }
5583*0a6a1f1dSLionel Sambuc     }
5584*0a6a1f1dSLionel Sambuc 
5585*0a6a1f1dSLionel Sambuc   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5586*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5587*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5588*0a6a1f1dSLionel Sambuc     InnerContexts.insert(BE->getBlockDecl());
5589*0a6a1f1dSLionel Sambuc     ImportedLocalExternalDecls.clear();
5590*0a6a1f1dSLionel Sambuc     GetInnerBlockDeclRefExprs(BE->getBody(),
5591*0a6a1f1dSLionel Sambuc                               InnerBlockDeclRefs, InnerContexts);
5592*0a6a1f1dSLionel Sambuc     // Rewrite the block body in place.
5593*0a6a1f1dSLionel Sambuc     Stmt *SaveCurrentBody = CurrentBody;
5594*0a6a1f1dSLionel Sambuc     CurrentBody = BE->getBody();
5595*0a6a1f1dSLionel Sambuc     PropParentMap = nullptr;
5596*0a6a1f1dSLionel Sambuc     // block literal on rhs of a property-dot-sytax assignment
5597*0a6a1f1dSLionel Sambuc     // must be replaced by its synthesize ast so getRewrittenText
5598*0a6a1f1dSLionel Sambuc     // works as expected. In this case, what actually ends up on RHS
5599*0a6a1f1dSLionel Sambuc     // is the blockTranscribed which is the helper function for the
5600*0a6a1f1dSLionel Sambuc     // block literal; as in: self.c = ^() {[ace ARR];};
5601*0a6a1f1dSLionel Sambuc     bool saveDisableReplaceStmt = DisableReplaceStmt;
5602*0a6a1f1dSLionel Sambuc     DisableReplaceStmt = false;
5603*0a6a1f1dSLionel Sambuc     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5604*0a6a1f1dSLionel Sambuc     DisableReplaceStmt = saveDisableReplaceStmt;
5605*0a6a1f1dSLionel Sambuc     CurrentBody = SaveCurrentBody;
5606*0a6a1f1dSLionel Sambuc     PropParentMap = nullptr;
5607*0a6a1f1dSLionel Sambuc     ImportedLocalExternalDecls.clear();
5608*0a6a1f1dSLionel Sambuc     // Now we snarf the rewritten text and stash it away for later use.
5609*0a6a1f1dSLionel Sambuc     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5610*0a6a1f1dSLionel Sambuc     RewrittenBlockExprs[BE] = Str;
5611*0a6a1f1dSLionel Sambuc 
5612*0a6a1f1dSLionel Sambuc     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5613*0a6a1f1dSLionel Sambuc 
5614*0a6a1f1dSLionel Sambuc     //blockTranscribed->dump();
5615*0a6a1f1dSLionel Sambuc     ReplaceStmt(S, blockTranscribed);
5616*0a6a1f1dSLionel Sambuc     return blockTranscribed;
5617*0a6a1f1dSLionel Sambuc   }
5618*0a6a1f1dSLionel Sambuc   // Handle specific things.
5619*0a6a1f1dSLionel Sambuc   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5620*0a6a1f1dSLionel Sambuc     return RewriteAtEncode(AtEncode);
5621*0a6a1f1dSLionel Sambuc 
5622*0a6a1f1dSLionel Sambuc   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5623*0a6a1f1dSLionel Sambuc     return RewriteAtSelector(AtSelector);
5624*0a6a1f1dSLionel Sambuc 
5625*0a6a1f1dSLionel Sambuc   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5626*0a6a1f1dSLionel Sambuc     return RewriteObjCStringLiteral(AtString);
5627*0a6a1f1dSLionel Sambuc 
5628*0a6a1f1dSLionel Sambuc   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5629*0a6a1f1dSLionel Sambuc     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5630*0a6a1f1dSLionel Sambuc 
5631*0a6a1f1dSLionel Sambuc   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5632*0a6a1f1dSLionel Sambuc     return RewriteObjCBoxedExpr(BoxedExpr);
5633*0a6a1f1dSLionel Sambuc 
5634*0a6a1f1dSLionel Sambuc   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5635*0a6a1f1dSLionel Sambuc     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5636*0a6a1f1dSLionel Sambuc 
5637*0a6a1f1dSLionel Sambuc   if (ObjCDictionaryLiteral *DictionaryLitExpr =
5638*0a6a1f1dSLionel Sambuc         dyn_cast<ObjCDictionaryLiteral>(S))
5639*0a6a1f1dSLionel Sambuc     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5640*0a6a1f1dSLionel Sambuc 
5641*0a6a1f1dSLionel Sambuc   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5642*0a6a1f1dSLionel Sambuc #if 0
5643*0a6a1f1dSLionel Sambuc     // Before we rewrite it, put the original message expression in a comment.
5644*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = MessExpr->getLocStart();
5645*0a6a1f1dSLionel Sambuc     SourceLocation endLoc = MessExpr->getLocEnd();
5646*0a6a1f1dSLionel Sambuc 
5647*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
5648*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(endLoc);
5649*0a6a1f1dSLionel Sambuc 
5650*0a6a1f1dSLionel Sambuc     std::string messString;
5651*0a6a1f1dSLionel Sambuc     messString += "// ";
5652*0a6a1f1dSLionel Sambuc     messString.append(startBuf, endBuf-startBuf+1);
5653*0a6a1f1dSLionel Sambuc     messString += "\n";
5654*0a6a1f1dSLionel Sambuc 
5655*0a6a1f1dSLionel Sambuc     // FIXME: Missing definition of
5656*0a6a1f1dSLionel Sambuc     // InsertText(clang::SourceLocation, char const*, unsigned int).
5657*0a6a1f1dSLionel Sambuc     // InsertText(startLoc, messString.c_str(), messString.size());
5658*0a6a1f1dSLionel Sambuc     // Tried this, but it didn't work either...
5659*0a6a1f1dSLionel Sambuc     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5660*0a6a1f1dSLionel Sambuc #endif
5661*0a6a1f1dSLionel Sambuc     return RewriteMessageExpr(MessExpr);
5662*0a6a1f1dSLionel Sambuc   }
5663*0a6a1f1dSLionel Sambuc 
5664*0a6a1f1dSLionel Sambuc   if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5665*0a6a1f1dSLionel Sambuc         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5666*0a6a1f1dSLionel Sambuc     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5667*0a6a1f1dSLionel Sambuc   }
5668*0a6a1f1dSLionel Sambuc 
5669*0a6a1f1dSLionel Sambuc   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5670*0a6a1f1dSLionel Sambuc     return RewriteObjCTryStmt(StmtTry);
5671*0a6a1f1dSLionel Sambuc 
5672*0a6a1f1dSLionel Sambuc   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5673*0a6a1f1dSLionel Sambuc     return RewriteObjCSynchronizedStmt(StmtTry);
5674*0a6a1f1dSLionel Sambuc 
5675*0a6a1f1dSLionel Sambuc   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5676*0a6a1f1dSLionel Sambuc     return RewriteObjCThrowStmt(StmtThrow);
5677*0a6a1f1dSLionel Sambuc 
5678*0a6a1f1dSLionel Sambuc   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5679*0a6a1f1dSLionel Sambuc     return RewriteObjCProtocolExpr(ProtocolExp);
5680*0a6a1f1dSLionel Sambuc 
5681*0a6a1f1dSLionel Sambuc   if (ObjCForCollectionStmt *StmtForCollection =
5682*0a6a1f1dSLionel Sambuc         dyn_cast<ObjCForCollectionStmt>(S))
5683*0a6a1f1dSLionel Sambuc     return RewriteObjCForCollectionStmt(StmtForCollection,
5684*0a6a1f1dSLionel Sambuc                                         OrigStmtRange.getEnd());
5685*0a6a1f1dSLionel Sambuc   if (BreakStmt *StmtBreakStmt =
5686*0a6a1f1dSLionel Sambuc       dyn_cast<BreakStmt>(S))
5687*0a6a1f1dSLionel Sambuc     return RewriteBreakStmt(StmtBreakStmt);
5688*0a6a1f1dSLionel Sambuc   if (ContinueStmt *StmtContinueStmt =
5689*0a6a1f1dSLionel Sambuc       dyn_cast<ContinueStmt>(S))
5690*0a6a1f1dSLionel Sambuc     return RewriteContinueStmt(StmtContinueStmt);
5691*0a6a1f1dSLionel Sambuc 
5692*0a6a1f1dSLionel Sambuc   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5693*0a6a1f1dSLionel Sambuc   // and cast exprs.
5694*0a6a1f1dSLionel Sambuc   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5695*0a6a1f1dSLionel Sambuc     // FIXME: What we're doing here is modifying the type-specifier that
5696*0a6a1f1dSLionel Sambuc     // precedes the first Decl.  In the future the DeclGroup should have
5697*0a6a1f1dSLionel Sambuc     // a separate type-specifier that we can rewrite.
5698*0a6a1f1dSLionel Sambuc     // NOTE: We need to avoid rewriting the DeclStmt if it is within
5699*0a6a1f1dSLionel Sambuc     // the context of an ObjCForCollectionStmt. For example:
5700*0a6a1f1dSLionel Sambuc     //   NSArray *someArray;
5701*0a6a1f1dSLionel Sambuc     //   for (id <FooProtocol> index in someArray) ;
5702*0a6a1f1dSLionel Sambuc     // This is because RewriteObjCForCollectionStmt() does textual rewriting
5703*0a6a1f1dSLionel Sambuc     // and it depends on the original text locations/positions.
5704*0a6a1f1dSLionel Sambuc     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5705*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5706*0a6a1f1dSLionel Sambuc 
5707*0a6a1f1dSLionel Sambuc     // Blocks rewrite rules.
5708*0a6a1f1dSLionel Sambuc     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5709*0a6a1f1dSLionel Sambuc          DI != DE; ++DI) {
5710*0a6a1f1dSLionel Sambuc       Decl *SD = *DI;
5711*0a6a1f1dSLionel Sambuc       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5712*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(ND->getType()))
5713*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(ND);
5714*0a6a1f1dSLionel Sambuc         else if (ND->getType()->isFunctionPointerType())
5715*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(ND->getType(), ND);
5716*0a6a1f1dSLionel Sambuc         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5717*0a6a1f1dSLionel Sambuc           if (VD->hasAttr<BlocksAttr>()) {
5718*0a6a1f1dSLionel Sambuc             static unsigned uniqueByrefDeclCount = 0;
5719*0a6a1f1dSLionel Sambuc             assert(!BlockByRefDeclNo.count(ND) &&
5720*0a6a1f1dSLionel Sambuc               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5721*0a6a1f1dSLionel Sambuc             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5722*0a6a1f1dSLionel Sambuc             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5723*0a6a1f1dSLionel Sambuc           }
5724*0a6a1f1dSLionel Sambuc           else
5725*0a6a1f1dSLionel Sambuc             RewriteTypeOfDecl(VD);
5726*0a6a1f1dSLionel Sambuc         }
5727*0a6a1f1dSLionel Sambuc       }
5728*0a6a1f1dSLionel Sambuc       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5729*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5730*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(TD);
5731*0a6a1f1dSLionel Sambuc         else if (TD->getUnderlyingType()->isFunctionPointerType())
5732*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5733*0a6a1f1dSLionel Sambuc       }
5734*0a6a1f1dSLionel Sambuc     }
5735*0a6a1f1dSLionel Sambuc   }
5736*0a6a1f1dSLionel Sambuc 
5737*0a6a1f1dSLionel Sambuc   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5738*0a6a1f1dSLionel Sambuc     RewriteObjCQualifiedInterfaceTypes(CE);
5739*0a6a1f1dSLionel Sambuc 
5740*0a6a1f1dSLionel Sambuc   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5741*0a6a1f1dSLionel Sambuc       isa<DoStmt>(S) || isa<ForStmt>(S)) {
5742*0a6a1f1dSLionel Sambuc     assert(!Stmts.empty() && "Statement stack is empty");
5743*0a6a1f1dSLionel Sambuc     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5744*0a6a1f1dSLionel Sambuc              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5745*0a6a1f1dSLionel Sambuc             && "Statement stack mismatch");
5746*0a6a1f1dSLionel Sambuc     Stmts.pop_back();
5747*0a6a1f1dSLionel Sambuc   }
5748*0a6a1f1dSLionel Sambuc   // Handle blocks rewriting.
5749*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5750*0a6a1f1dSLionel Sambuc     ValueDecl *VD = DRE->getDecl();
5751*0a6a1f1dSLionel Sambuc     if (VD->hasAttr<BlocksAttr>())
5752*0a6a1f1dSLionel Sambuc       return RewriteBlockDeclRefExpr(DRE);
5753*0a6a1f1dSLionel Sambuc     if (HasLocalVariableExternalStorage(VD))
5754*0a6a1f1dSLionel Sambuc       return RewriteLocalVariableExternalStorage(DRE);
5755*0a6a1f1dSLionel Sambuc   }
5756*0a6a1f1dSLionel Sambuc 
5757*0a6a1f1dSLionel Sambuc   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5758*0a6a1f1dSLionel Sambuc     if (CE->getCallee()->getType()->isBlockPointerType()) {
5759*0a6a1f1dSLionel Sambuc       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5760*0a6a1f1dSLionel Sambuc       ReplaceStmt(S, BlockCall);
5761*0a6a1f1dSLionel Sambuc       return BlockCall;
5762*0a6a1f1dSLionel Sambuc     }
5763*0a6a1f1dSLionel Sambuc   }
5764*0a6a1f1dSLionel Sambuc   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5765*0a6a1f1dSLionel Sambuc     RewriteCastExpr(CE);
5766*0a6a1f1dSLionel Sambuc   }
5767*0a6a1f1dSLionel Sambuc   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5768*0a6a1f1dSLionel Sambuc     RewriteImplicitCastObjCExpr(ICE);
5769*0a6a1f1dSLionel Sambuc   }
5770*0a6a1f1dSLionel Sambuc #if 0
5771*0a6a1f1dSLionel Sambuc 
5772*0a6a1f1dSLionel Sambuc   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5773*0a6a1f1dSLionel Sambuc     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5774*0a6a1f1dSLionel Sambuc                                                    ICE->getSubExpr(),
5775*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
5776*0a6a1f1dSLionel Sambuc     // Get the new text.
5777*0a6a1f1dSLionel Sambuc     std::string SStr;
5778*0a6a1f1dSLionel Sambuc     llvm::raw_string_ostream Buf(SStr);
5779*0a6a1f1dSLionel Sambuc     Replacement->printPretty(Buf);
5780*0a6a1f1dSLionel Sambuc     const std::string &Str = Buf.str();
5781*0a6a1f1dSLionel Sambuc 
5782*0a6a1f1dSLionel Sambuc     printf("CAST = %s\n", &Str[0]);
5783*0a6a1f1dSLionel Sambuc     InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5784*0a6a1f1dSLionel Sambuc     delete S;
5785*0a6a1f1dSLionel Sambuc     return Replacement;
5786*0a6a1f1dSLionel Sambuc   }
5787*0a6a1f1dSLionel Sambuc #endif
5788*0a6a1f1dSLionel Sambuc   // Return this stmt unmodified.
5789*0a6a1f1dSLionel Sambuc   return S;
5790*0a6a1f1dSLionel Sambuc }
5791*0a6a1f1dSLionel Sambuc 
RewriteRecordBody(RecordDecl * RD)5792*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5793*0a6a1f1dSLionel Sambuc   for (auto *FD : RD->fields()) {
5794*0a6a1f1dSLionel Sambuc     if (isTopLevelBlockPointerType(FD->getType()))
5795*0a6a1f1dSLionel Sambuc       RewriteBlockPointerDecl(FD);
5796*0a6a1f1dSLionel Sambuc     if (FD->getType()->isObjCQualifiedIdType() ||
5797*0a6a1f1dSLionel Sambuc         FD->getType()->isObjCQualifiedInterfaceType())
5798*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(FD);
5799*0a6a1f1dSLionel Sambuc   }
5800*0a6a1f1dSLionel Sambuc }
5801*0a6a1f1dSLionel Sambuc 
5802*0a6a1f1dSLionel Sambuc /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5803*0a6a1f1dSLionel Sambuc /// main file of the input.
HandleDeclInMainFile(Decl * D)5804*0a6a1f1dSLionel Sambuc void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5805*0a6a1f1dSLionel Sambuc   switch (D->getKind()) {
5806*0a6a1f1dSLionel Sambuc     case Decl::Function: {
5807*0a6a1f1dSLionel Sambuc       FunctionDecl *FD = cast<FunctionDecl>(D);
5808*0a6a1f1dSLionel Sambuc       if (FD->isOverloadedOperator())
5809*0a6a1f1dSLionel Sambuc         return;
5810*0a6a1f1dSLionel Sambuc 
5811*0a6a1f1dSLionel Sambuc       // Since function prototypes don't have ParmDecl's, we check the function
5812*0a6a1f1dSLionel Sambuc       // prototype. This enables us to rewrite function declarations and
5813*0a6a1f1dSLionel Sambuc       // definitions using the same code.
5814*0a6a1f1dSLionel Sambuc       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5815*0a6a1f1dSLionel Sambuc 
5816*0a6a1f1dSLionel Sambuc       if (!FD->isThisDeclarationADefinition())
5817*0a6a1f1dSLionel Sambuc         break;
5818*0a6a1f1dSLionel Sambuc 
5819*0a6a1f1dSLionel Sambuc       // FIXME: If this should support Obj-C++, support CXXTryStmt
5820*0a6a1f1dSLionel Sambuc       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5821*0a6a1f1dSLionel Sambuc         CurFunctionDef = FD;
5822*0a6a1f1dSLionel Sambuc         CurrentBody = Body;
5823*0a6a1f1dSLionel Sambuc         Body =
5824*0a6a1f1dSLionel Sambuc         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5825*0a6a1f1dSLionel Sambuc         FD->setBody(Body);
5826*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
5827*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
5828*0a6a1f1dSLionel Sambuc           delete PropParentMap;
5829*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
5830*0a6a1f1dSLionel Sambuc         }
5831*0a6a1f1dSLionel Sambuc         // This synthesizes and inserts the block "impl" struct, invoke function,
5832*0a6a1f1dSLionel Sambuc         // and any copy/dispose helper functions.
5833*0a6a1f1dSLionel Sambuc         InsertBlockLiteralsWithinFunction(FD);
5834*0a6a1f1dSLionel Sambuc         RewriteLineDirective(D);
5835*0a6a1f1dSLionel Sambuc         CurFunctionDef = nullptr;
5836*0a6a1f1dSLionel Sambuc       }
5837*0a6a1f1dSLionel Sambuc       break;
5838*0a6a1f1dSLionel Sambuc     }
5839*0a6a1f1dSLionel Sambuc     case Decl::ObjCMethod: {
5840*0a6a1f1dSLionel Sambuc       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5841*0a6a1f1dSLionel Sambuc       if (CompoundStmt *Body = MD->getCompoundBody()) {
5842*0a6a1f1dSLionel Sambuc         CurMethodDef = MD;
5843*0a6a1f1dSLionel Sambuc         CurrentBody = Body;
5844*0a6a1f1dSLionel Sambuc         Body =
5845*0a6a1f1dSLionel Sambuc           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5846*0a6a1f1dSLionel Sambuc         MD->setBody(Body);
5847*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
5848*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
5849*0a6a1f1dSLionel Sambuc           delete PropParentMap;
5850*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
5851*0a6a1f1dSLionel Sambuc         }
5852*0a6a1f1dSLionel Sambuc         InsertBlockLiteralsWithinMethod(MD);
5853*0a6a1f1dSLionel Sambuc         RewriteLineDirective(D);
5854*0a6a1f1dSLionel Sambuc         CurMethodDef = nullptr;
5855*0a6a1f1dSLionel Sambuc       }
5856*0a6a1f1dSLionel Sambuc       break;
5857*0a6a1f1dSLionel Sambuc     }
5858*0a6a1f1dSLionel Sambuc     case Decl::ObjCImplementation: {
5859*0a6a1f1dSLionel Sambuc       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5860*0a6a1f1dSLionel Sambuc       ClassImplementation.push_back(CI);
5861*0a6a1f1dSLionel Sambuc       break;
5862*0a6a1f1dSLionel Sambuc     }
5863*0a6a1f1dSLionel Sambuc     case Decl::ObjCCategoryImpl: {
5864*0a6a1f1dSLionel Sambuc       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5865*0a6a1f1dSLionel Sambuc       CategoryImplementation.push_back(CI);
5866*0a6a1f1dSLionel Sambuc       break;
5867*0a6a1f1dSLionel Sambuc     }
5868*0a6a1f1dSLionel Sambuc     case Decl::Var: {
5869*0a6a1f1dSLionel Sambuc       VarDecl *VD = cast<VarDecl>(D);
5870*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(VD);
5871*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(VD->getType()))
5872*0a6a1f1dSLionel Sambuc         RewriteBlockPointerDecl(VD);
5873*0a6a1f1dSLionel Sambuc       else if (VD->getType()->isFunctionPointerType()) {
5874*0a6a1f1dSLionel Sambuc         CheckFunctionPointerDecl(VD->getType(), VD);
5875*0a6a1f1dSLionel Sambuc         if (VD->getInit()) {
5876*0a6a1f1dSLionel Sambuc           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5877*0a6a1f1dSLionel Sambuc             RewriteCastExpr(CE);
5878*0a6a1f1dSLionel Sambuc           }
5879*0a6a1f1dSLionel Sambuc         }
5880*0a6a1f1dSLionel Sambuc       } else if (VD->getType()->isRecordType()) {
5881*0a6a1f1dSLionel Sambuc         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5882*0a6a1f1dSLionel Sambuc         if (RD->isCompleteDefinition())
5883*0a6a1f1dSLionel Sambuc           RewriteRecordBody(RD);
5884*0a6a1f1dSLionel Sambuc       }
5885*0a6a1f1dSLionel Sambuc       if (VD->getInit()) {
5886*0a6a1f1dSLionel Sambuc         GlobalVarDecl = VD;
5887*0a6a1f1dSLionel Sambuc         CurrentBody = VD->getInit();
5888*0a6a1f1dSLionel Sambuc         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5889*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
5890*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
5891*0a6a1f1dSLionel Sambuc           delete PropParentMap;
5892*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
5893*0a6a1f1dSLionel Sambuc         }
5894*0a6a1f1dSLionel Sambuc         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5895*0a6a1f1dSLionel Sambuc         GlobalVarDecl = nullptr;
5896*0a6a1f1dSLionel Sambuc 
5897*0a6a1f1dSLionel Sambuc         // This is needed for blocks.
5898*0a6a1f1dSLionel Sambuc         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5899*0a6a1f1dSLionel Sambuc             RewriteCastExpr(CE);
5900*0a6a1f1dSLionel Sambuc         }
5901*0a6a1f1dSLionel Sambuc       }
5902*0a6a1f1dSLionel Sambuc       break;
5903*0a6a1f1dSLionel Sambuc     }
5904*0a6a1f1dSLionel Sambuc     case Decl::TypeAlias:
5905*0a6a1f1dSLionel Sambuc     case Decl::Typedef: {
5906*0a6a1f1dSLionel Sambuc       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5907*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5908*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(TD);
5909*0a6a1f1dSLionel Sambuc         else if (TD->getUnderlyingType()->isFunctionPointerType())
5910*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5911*0a6a1f1dSLionel Sambuc         else
5912*0a6a1f1dSLionel Sambuc           RewriteObjCQualifiedInterfaceTypes(TD);
5913*0a6a1f1dSLionel Sambuc       }
5914*0a6a1f1dSLionel Sambuc       break;
5915*0a6a1f1dSLionel Sambuc     }
5916*0a6a1f1dSLionel Sambuc     case Decl::CXXRecord:
5917*0a6a1f1dSLionel Sambuc     case Decl::Record: {
5918*0a6a1f1dSLionel Sambuc       RecordDecl *RD = cast<RecordDecl>(D);
5919*0a6a1f1dSLionel Sambuc       if (RD->isCompleteDefinition())
5920*0a6a1f1dSLionel Sambuc         RewriteRecordBody(RD);
5921*0a6a1f1dSLionel Sambuc       break;
5922*0a6a1f1dSLionel Sambuc     }
5923*0a6a1f1dSLionel Sambuc     default:
5924*0a6a1f1dSLionel Sambuc       break;
5925*0a6a1f1dSLionel Sambuc   }
5926*0a6a1f1dSLionel Sambuc   // Nothing yet.
5927*0a6a1f1dSLionel Sambuc }
5928*0a6a1f1dSLionel Sambuc 
5929*0a6a1f1dSLionel Sambuc /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5930*0a6a1f1dSLionel Sambuc /// protocol reference symbols in the for of:
5931*0a6a1f1dSLionel Sambuc /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Write_ProtocolExprReferencedMetadata(ASTContext * Context,ObjCProtocolDecl * PDecl,std::string & Result)5932*0a6a1f1dSLionel Sambuc static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5933*0a6a1f1dSLionel Sambuc                                                  ObjCProtocolDecl *PDecl,
5934*0a6a1f1dSLionel Sambuc                                                  std::string &Result) {
5935*0a6a1f1dSLionel Sambuc   // Also output .objc_protorefs$B section and its meta-data.
5936*0a6a1f1dSLionel Sambuc   if (Context->getLangOpts().MicrosoftExt)
5937*0a6a1f1dSLionel Sambuc     Result += "static ";
5938*0a6a1f1dSLionel Sambuc   Result += "struct _protocol_t *";
5939*0a6a1f1dSLionel Sambuc   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5940*0a6a1f1dSLionel Sambuc   Result += PDecl->getNameAsString();
5941*0a6a1f1dSLionel Sambuc   Result += " = &";
5942*0a6a1f1dSLionel Sambuc   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5943*0a6a1f1dSLionel Sambuc   Result += ";\n";
5944*0a6a1f1dSLionel Sambuc }
5945*0a6a1f1dSLionel Sambuc 
HandleTranslationUnit(ASTContext & C)5946*0a6a1f1dSLionel Sambuc void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5947*0a6a1f1dSLionel Sambuc   if (Diags.hasErrorOccurred())
5948*0a6a1f1dSLionel Sambuc     return;
5949*0a6a1f1dSLionel Sambuc 
5950*0a6a1f1dSLionel Sambuc   RewriteInclude();
5951*0a6a1f1dSLionel Sambuc 
5952*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5953*0a6a1f1dSLionel Sambuc     // translation of function bodies were postponed until all class and
5954*0a6a1f1dSLionel Sambuc     // their extensions and implementations are seen. This is because, we
5955*0a6a1f1dSLionel Sambuc     // cannot build grouping structs for bitfields until they are all seen.
5956*0a6a1f1dSLionel Sambuc     FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5957*0a6a1f1dSLionel Sambuc     HandleTopLevelSingleDecl(FDecl);
5958*0a6a1f1dSLionel Sambuc   }
5959*0a6a1f1dSLionel Sambuc 
5960*0a6a1f1dSLionel Sambuc   // Here's a great place to add any extra declarations that may be needed.
5961*0a6a1f1dSLionel Sambuc   // Write out meta data for each @protocol(<expr>).
5962*0a6a1f1dSLionel Sambuc   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5963*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5964*0a6a1f1dSLionel Sambuc     Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5965*0a6a1f1dSLionel Sambuc   }
5966*0a6a1f1dSLionel Sambuc 
5967*0a6a1f1dSLionel Sambuc   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5968*0a6a1f1dSLionel Sambuc 
5969*0a6a1f1dSLionel Sambuc   if (ClassImplementation.size() || CategoryImplementation.size())
5970*0a6a1f1dSLionel Sambuc     RewriteImplementations();
5971*0a6a1f1dSLionel Sambuc 
5972*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5973*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5974*0a6a1f1dSLionel Sambuc     // Write struct declaration for the class matching its ivar declarations.
5975*0a6a1f1dSLionel Sambuc     // Note that for modern abi, this is postponed until the end of TU
5976*0a6a1f1dSLionel Sambuc     // because class extensions and the implementation might declare their own
5977*0a6a1f1dSLionel Sambuc     // private ivars.
5978*0a6a1f1dSLionel Sambuc     RewriteInterfaceDecl(CDecl);
5979*0a6a1f1dSLionel Sambuc   }
5980*0a6a1f1dSLionel Sambuc 
5981*0a6a1f1dSLionel Sambuc   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5982*0a6a1f1dSLionel Sambuc   // we are done.
5983*0a6a1f1dSLionel Sambuc   if (const RewriteBuffer *RewriteBuf =
5984*0a6a1f1dSLionel Sambuc       Rewrite.getRewriteBufferFor(MainFileID)) {
5985*0a6a1f1dSLionel Sambuc     //printf("Changed:\n");
5986*0a6a1f1dSLionel Sambuc     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5987*0a6a1f1dSLionel Sambuc   } else {
5988*0a6a1f1dSLionel Sambuc     llvm::errs() << "No changes\n";
5989*0a6a1f1dSLionel Sambuc   }
5990*0a6a1f1dSLionel Sambuc 
5991*0a6a1f1dSLionel Sambuc   if (ClassImplementation.size() || CategoryImplementation.size() ||
5992*0a6a1f1dSLionel Sambuc       ProtocolExprDecls.size()) {
5993*0a6a1f1dSLionel Sambuc     // Rewrite Objective-c meta data*
5994*0a6a1f1dSLionel Sambuc     std::string ResultStr;
5995*0a6a1f1dSLionel Sambuc     RewriteMetaDataIntoBuffer(ResultStr);
5996*0a6a1f1dSLionel Sambuc     // Emit metadata.
5997*0a6a1f1dSLionel Sambuc     *OutFile << ResultStr;
5998*0a6a1f1dSLionel Sambuc   }
5999*0a6a1f1dSLionel Sambuc   // Emit ImageInfo;
6000*0a6a1f1dSLionel Sambuc   {
6001*0a6a1f1dSLionel Sambuc     std::string ResultStr;
6002*0a6a1f1dSLionel Sambuc     WriteImageInfo(ResultStr);
6003*0a6a1f1dSLionel Sambuc     *OutFile << ResultStr;
6004*0a6a1f1dSLionel Sambuc   }
6005*0a6a1f1dSLionel Sambuc   OutFile->flush();
6006*0a6a1f1dSLionel Sambuc }
6007*0a6a1f1dSLionel Sambuc 
Initialize(ASTContext & context)6008*0a6a1f1dSLionel Sambuc void RewriteModernObjC::Initialize(ASTContext &context) {
6009*0a6a1f1dSLionel Sambuc   InitializeCommon(context);
6010*0a6a1f1dSLionel Sambuc 
6011*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef __OBJC2__\n";
6012*0a6a1f1dSLionel Sambuc   Preamble += "#define __OBJC2__\n";
6013*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6014*0a6a1f1dSLionel Sambuc 
6015*0a6a1f1dSLionel Sambuc   // declaring objc_selector outside the parameter list removes a silly
6016*0a6a1f1dSLionel Sambuc   // scope related warning...
6017*0a6a1f1dSLionel Sambuc   if (IsHeader)
6018*0a6a1f1dSLionel Sambuc     Preamble = "#pragma once\n";
6019*0a6a1f1dSLionel Sambuc   Preamble += "struct objc_selector; struct objc_class;\n";
6020*0a6a1f1dSLionel Sambuc   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6021*0a6a1f1dSLionel Sambuc   Preamble += "\n\tstruct objc_object *superClass; ";
6022*0a6a1f1dSLionel Sambuc   // Add a constructor for creating temporary objects.
6023*0a6a1f1dSLionel Sambuc   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6024*0a6a1f1dSLionel Sambuc   Preamble += ": object(o), superClass(s) {} ";
6025*0a6a1f1dSLionel Sambuc   Preamble += "\n};\n";
6026*0a6a1f1dSLionel Sambuc 
6027*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
6028*0a6a1f1dSLionel Sambuc     // Define all sections using syntax that makes sense.
6029*0a6a1f1dSLionel Sambuc     // These are currently generated.
6030*0a6a1f1dSLionel Sambuc     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
6031*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
6032*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
6033*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6034*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
6035*0a6a1f1dSLionel Sambuc     // These are generated but not necessary for functionality.
6036*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
6037*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6038*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
6039*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
6040*0a6a1f1dSLionel Sambuc 
6041*0a6a1f1dSLionel Sambuc     // These need be generated for performance. Currently they are not,
6042*0a6a1f1dSLionel Sambuc     // using API calls instead.
6043*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6044*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6045*0a6a1f1dSLionel Sambuc     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6046*0a6a1f1dSLionel Sambuc 
6047*0a6a1f1dSLionel Sambuc   }
6048*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6049*0a6a1f1dSLionel Sambuc   Preamble += "typedef struct objc_object Protocol;\n";
6050*0a6a1f1dSLionel Sambuc   Preamble += "#define _REWRITER_typedef_Protocol\n";
6051*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6052*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
6053*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6054*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
6055*0a6a1f1dSLionel Sambuc   }
6056*0a6a1f1dSLionel Sambuc   else
6057*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
6058*0a6a1f1dSLionel Sambuc 
6059*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6060*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6061*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6062*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6063*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6064*0a6a1f1dSLionel Sambuc 
6065*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
6066*0a6a1f1dSLionel Sambuc   Preamble += "(const char *);\n";
6067*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6068*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_class *);\n";
6069*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
6070*0a6a1f1dSLionel Sambuc   Preamble += "(const char *);\n";
6071*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
6072*0a6a1f1dSLionel Sambuc   // @synchronized hooks.
6073*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6074*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
6075*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6076*0a6a1f1dSLionel Sambuc   Preamble += "#ifdef _WIN64\n";
6077*0a6a1f1dSLionel Sambuc   Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
6078*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
6079*0a6a1f1dSLionel Sambuc   Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6080*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6081*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6082*0a6a1f1dSLionel Sambuc   Preamble += "struct __objcFastEnumerationState {\n\t";
6083*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long state;\n\t";
6084*0a6a1f1dSLionel Sambuc   Preamble += "void **itemsPtr;\n\t";
6085*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long *mutationsPtr;\n\t";
6086*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long extra[5];\n};\n";
6087*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6088*0a6a1f1dSLionel Sambuc   Preamble += "#define __FASTENUMERATIONSTATE\n";
6089*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6090*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6091*0a6a1f1dSLionel Sambuc   Preamble += "struct __NSConstantStringImpl {\n";
6092*0a6a1f1dSLionel Sambuc   Preamble += "  int *isa;\n";
6093*0a6a1f1dSLionel Sambuc   Preamble += "  int flags;\n";
6094*0a6a1f1dSLionel Sambuc   Preamble += "  char *str;\n";
6095*0a6a1f1dSLionel Sambuc   Preamble += "#if _WIN64\n";
6096*0a6a1f1dSLionel Sambuc   Preamble += "  long long length;\n";
6097*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
6098*0a6a1f1dSLionel Sambuc   Preamble += "  long length;\n";
6099*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6100*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
6101*0a6a1f1dSLionel Sambuc   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6102*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6103*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
6104*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6105*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6106*0a6a1f1dSLionel Sambuc   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6107*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6108*0a6a1f1dSLionel Sambuc   // Blocks preamble.
6109*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef BLOCK_IMPL\n";
6110*0a6a1f1dSLionel Sambuc   Preamble += "#define BLOCK_IMPL\n";
6111*0a6a1f1dSLionel Sambuc   Preamble += "struct __block_impl {\n";
6112*0a6a1f1dSLionel Sambuc   Preamble += "  void *isa;\n";
6113*0a6a1f1dSLionel Sambuc   Preamble += "  int Flags;\n";
6114*0a6a1f1dSLionel Sambuc   Preamble += "  int Reserved;\n";
6115*0a6a1f1dSLionel Sambuc   Preamble += "  void *FuncPtr;\n";
6116*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
6117*0a6a1f1dSLionel Sambuc   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6118*0a6a1f1dSLionel Sambuc   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6119*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) "
6120*0a6a1f1dSLionel Sambuc   "void _Block_object_assign(void *, const void *, const int);\n";
6121*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6122*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6123*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6124*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
6125*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6126*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6127*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6128*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6129*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6130*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
6131*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
6132*0a6a1f1dSLionel Sambuc     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6133*0a6a1f1dSLionel Sambuc     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6134*0a6a1f1dSLionel Sambuc     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
6135*0a6a1f1dSLionel Sambuc     Preamble += "#define __attribute__(X)\n";
6136*0a6a1f1dSLionel Sambuc     Preamble += "#endif\n";
6137*0a6a1f1dSLionel Sambuc     Preamble += "#ifndef __weak\n";
6138*0a6a1f1dSLionel Sambuc     Preamble += "#define __weak\n";
6139*0a6a1f1dSLionel Sambuc     Preamble += "#endif\n";
6140*0a6a1f1dSLionel Sambuc     Preamble += "#ifndef __block\n";
6141*0a6a1f1dSLionel Sambuc     Preamble += "#define __block\n";
6142*0a6a1f1dSLionel Sambuc     Preamble += "#endif\n";
6143*0a6a1f1dSLionel Sambuc   }
6144*0a6a1f1dSLionel Sambuc   else {
6145*0a6a1f1dSLionel Sambuc     Preamble += "#define __block\n";
6146*0a6a1f1dSLionel Sambuc     Preamble += "#define __weak\n";
6147*0a6a1f1dSLionel Sambuc   }
6148*0a6a1f1dSLionel Sambuc 
6149*0a6a1f1dSLionel Sambuc   // Declarations required for modern objective-c array and dictionary literals.
6150*0a6a1f1dSLionel Sambuc   Preamble += "\n#include <stdarg.h>\n";
6151*0a6a1f1dSLionel Sambuc   Preamble += "struct __NSContainer_literal {\n";
6152*0a6a1f1dSLionel Sambuc   Preamble += "  void * *arr;\n";
6153*0a6a1f1dSLionel Sambuc   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
6154*0a6a1f1dSLionel Sambuc   Preamble += "\tva_list marker;\n";
6155*0a6a1f1dSLionel Sambuc   Preamble += "\tva_start(marker, count);\n";
6156*0a6a1f1dSLionel Sambuc   Preamble += "\tarr = new void *[count];\n";
6157*0a6a1f1dSLionel Sambuc   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6158*0a6a1f1dSLionel Sambuc   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6159*0a6a1f1dSLionel Sambuc   Preamble += "\tva_end( marker );\n";
6160*0a6a1f1dSLionel Sambuc   Preamble += "  };\n";
6161*0a6a1f1dSLionel Sambuc   Preamble += "  ~__NSContainer_literal() {\n";
6162*0a6a1f1dSLionel Sambuc   Preamble += "\tdelete[] arr;\n";
6163*0a6a1f1dSLionel Sambuc   Preamble += "  }\n";
6164*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
6165*0a6a1f1dSLionel Sambuc 
6166*0a6a1f1dSLionel Sambuc   // Declaration required for implementation of @autoreleasepool statement.
6167*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6168*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6169*0a6a1f1dSLionel Sambuc   Preamble += "struct __AtAutoreleasePool {\n";
6170*0a6a1f1dSLionel Sambuc   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6171*0a6a1f1dSLionel Sambuc   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6172*0a6a1f1dSLionel Sambuc   Preamble += "  void * atautoreleasepoolobj;\n";
6173*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
6174*0a6a1f1dSLionel Sambuc 
6175*0a6a1f1dSLionel Sambuc   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6176*0a6a1f1dSLionel Sambuc   // as this avoids warning in any 64bit/32bit compilation model.
6177*0a6a1f1dSLionel Sambuc   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6178*0a6a1f1dSLionel Sambuc }
6179*0a6a1f1dSLionel Sambuc 
6180*0a6a1f1dSLionel Sambuc /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6181*0a6a1f1dSLionel Sambuc /// ivar offset.
RewriteIvarOffsetComputation(ObjCIvarDecl * ivar,std::string & Result)6182*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6183*0a6a1f1dSLionel Sambuc                                                          std::string &Result) {
6184*0a6a1f1dSLionel Sambuc   Result += "__OFFSETOFIVAR__(struct ";
6185*0a6a1f1dSLionel Sambuc   Result += ivar->getContainingInterface()->getNameAsString();
6186*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
6187*0a6a1f1dSLionel Sambuc     Result += "_IMPL";
6188*0a6a1f1dSLionel Sambuc   Result += ", ";
6189*0a6a1f1dSLionel Sambuc   if (ivar->isBitField())
6190*0a6a1f1dSLionel Sambuc     ObjCIvarBitfieldGroupDecl(ivar, Result);
6191*0a6a1f1dSLionel Sambuc   else
6192*0a6a1f1dSLionel Sambuc     Result += ivar->getNameAsString();
6193*0a6a1f1dSLionel Sambuc   Result += ")";
6194*0a6a1f1dSLionel Sambuc }
6195*0a6a1f1dSLionel Sambuc 
6196*0a6a1f1dSLionel Sambuc /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6197*0a6a1f1dSLionel Sambuc /// struct _prop_t {
6198*0a6a1f1dSLionel Sambuc ///   const char *name;
6199*0a6a1f1dSLionel Sambuc ///   char *attributes;
6200*0a6a1f1dSLionel Sambuc /// }
6201*0a6a1f1dSLionel Sambuc 
6202*0a6a1f1dSLionel Sambuc /// struct _prop_list_t {
6203*0a6a1f1dSLionel Sambuc ///   uint32_t entsize;      // sizeof(struct _prop_t)
6204*0a6a1f1dSLionel Sambuc ///   uint32_t count_of_properties;
6205*0a6a1f1dSLionel Sambuc ///   struct _prop_t prop_list[count_of_properties];
6206*0a6a1f1dSLionel Sambuc /// }
6207*0a6a1f1dSLionel Sambuc 
6208*0a6a1f1dSLionel Sambuc /// struct _protocol_t;
6209*0a6a1f1dSLionel Sambuc 
6210*0a6a1f1dSLionel Sambuc /// struct _protocol_list_t {
6211*0a6a1f1dSLionel Sambuc ///   long protocol_count;   // Note, this is 32/64 bit
6212*0a6a1f1dSLionel Sambuc ///   struct _protocol_t * protocol_list[protocol_count];
6213*0a6a1f1dSLionel Sambuc /// }
6214*0a6a1f1dSLionel Sambuc 
6215*0a6a1f1dSLionel Sambuc /// struct _objc_method {
6216*0a6a1f1dSLionel Sambuc ///   SEL _cmd;
6217*0a6a1f1dSLionel Sambuc ///   const char *method_type;
6218*0a6a1f1dSLionel Sambuc ///   char *_imp;
6219*0a6a1f1dSLionel Sambuc /// }
6220*0a6a1f1dSLionel Sambuc 
6221*0a6a1f1dSLionel Sambuc /// struct _method_list_t {
6222*0a6a1f1dSLionel Sambuc ///   uint32_t entsize;  // sizeof(struct _objc_method)
6223*0a6a1f1dSLionel Sambuc ///   uint32_t method_count;
6224*0a6a1f1dSLionel Sambuc ///   struct _objc_method method_list[method_count];
6225*0a6a1f1dSLionel Sambuc /// }
6226*0a6a1f1dSLionel Sambuc 
6227*0a6a1f1dSLionel Sambuc /// struct _protocol_t {
6228*0a6a1f1dSLionel Sambuc ///   id isa;  // NULL
6229*0a6a1f1dSLionel Sambuc ///   const char *protocol_name;
6230*0a6a1f1dSLionel Sambuc ///   const struct _protocol_list_t * protocol_list; // super protocols
6231*0a6a1f1dSLionel Sambuc ///   const struct method_list_t *instance_methods;
6232*0a6a1f1dSLionel Sambuc ///   const struct method_list_t *class_methods;
6233*0a6a1f1dSLionel Sambuc ///   const struct method_list_t *optionalInstanceMethods;
6234*0a6a1f1dSLionel Sambuc ///   const struct method_list_t *optionalClassMethods;
6235*0a6a1f1dSLionel Sambuc ///   const struct _prop_list_t * properties;
6236*0a6a1f1dSLionel Sambuc ///   const uint32_t size;  // sizeof(struct _protocol_t)
6237*0a6a1f1dSLionel Sambuc ///   const uint32_t flags;  // = 0
6238*0a6a1f1dSLionel Sambuc ///   const char ** extendedMethodTypes;
6239*0a6a1f1dSLionel Sambuc /// }
6240*0a6a1f1dSLionel Sambuc 
6241*0a6a1f1dSLionel Sambuc /// struct _ivar_t {
6242*0a6a1f1dSLionel Sambuc ///   unsigned long int *offset;  // pointer to ivar offset location
6243*0a6a1f1dSLionel Sambuc ///   const char *name;
6244*0a6a1f1dSLionel Sambuc ///   const char *type;
6245*0a6a1f1dSLionel Sambuc ///   uint32_t alignment;
6246*0a6a1f1dSLionel Sambuc ///   uint32_t size;
6247*0a6a1f1dSLionel Sambuc /// }
6248*0a6a1f1dSLionel Sambuc 
6249*0a6a1f1dSLionel Sambuc /// struct _ivar_list_t {
6250*0a6a1f1dSLionel Sambuc ///   uint32 entsize;  // sizeof(struct _ivar_t)
6251*0a6a1f1dSLionel Sambuc ///   uint32 count;
6252*0a6a1f1dSLionel Sambuc ///   struct _ivar_t list[count];
6253*0a6a1f1dSLionel Sambuc /// }
6254*0a6a1f1dSLionel Sambuc 
6255*0a6a1f1dSLionel Sambuc /// struct _class_ro_t {
6256*0a6a1f1dSLionel Sambuc ///   uint32_t flags;
6257*0a6a1f1dSLionel Sambuc ///   uint32_t instanceStart;
6258*0a6a1f1dSLionel Sambuc ///   uint32_t instanceSize;
6259*0a6a1f1dSLionel Sambuc ///   uint32_t reserved;  // only when building for 64bit targets
6260*0a6a1f1dSLionel Sambuc ///   const uint8_t *ivarLayout;
6261*0a6a1f1dSLionel Sambuc ///   const char *name;
6262*0a6a1f1dSLionel Sambuc ///   const struct _method_list_t *baseMethods;
6263*0a6a1f1dSLionel Sambuc ///   const struct _protocol_list_t *baseProtocols;
6264*0a6a1f1dSLionel Sambuc ///   const struct _ivar_list_t *ivars;
6265*0a6a1f1dSLionel Sambuc ///   const uint8_t *weakIvarLayout;
6266*0a6a1f1dSLionel Sambuc ///   const struct _prop_list_t *properties;
6267*0a6a1f1dSLionel Sambuc /// }
6268*0a6a1f1dSLionel Sambuc 
6269*0a6a1f1dSLionel Sambuc /// struct _class_t {
6270*0a6a1f1dSLionel Sambuc ///   struct _class_t *isa;
6271*0a6a1f1dSLionel Sambuc ///   struct _class_t *superclass;
6272*0a6a1f1dSLionel Sambuc ///   void *cache;
6273*0a6a1f1dSLionel Sambuc ///   IMP *vtable;
6274*0a6a1f1dSLionel Sambuc ///   struct _class_ro_t *ro;
6275*0a6a1f1dSLionel Sambuc /// }
6276*0a6a1f1dSLionel Sambuc 
6277*0a6a1f1dSLionel Sambuc /// struct _category_t {
6278*0a6a1f1dSLionel Sambuc ///   const char *name;
6279*0a6a1f1dSLionel Sambuc ///   struct _class_t *cls;
6280*0a6a1f1dSLionel Sambuc ///   const struct _method_list_t *instance_methods;
6281*0a6a1f1dSLionel Sambuc ///   const struct _method_list_t *class_methods;
6282*0a6a1f1dSLionel Sambuc ///   const struct _protocol_list_t *protocols;
6283*0a6a1f1dSLionel Sambuc ///   const struct _prop_list_t *properties;
6284*0a6a1f1dSLionel Sambuc /// }
6285*0a6a1f1dSLionel Sambuc 
6286*0a6a1f1dSLionel Sambuc /// MessageRefTy - LLVM for:
6287*0a6a1f1dSLionel Sambuc /// struct _message_ref_t {
6288*0a6a1f1dSLionel Sambuc ///   IMP messenger;
6289*0a6a1f1dSLionel Sambuc ///   SEL name;
6290*0a6a1f1dSLionel Sambuc /// };
6291*0a6a1f1dSLionel Sambuc 
6292*0a6a1f1dSLionel Sambuc /// SuperMessageRefTy - LLVM for:
6293*0a6a1f1dSLionel Sambuc /// struct _super_message_ref_t {
6294*0a6a1f1dSLionel Sambuc ///   SUPER_IMP messenger;
6295*0a6a1f1dSLionel Sambuc ///   SEL name;
6296*0a6a1f1dSLionel Sambuc /// };
6297*0a6a1f1dSLionel Sambuc 
WriteModernMetadataDeclarations(ASTContext * Context,std::string & Result)6298*0a6a1f1dSLionel Sambuc static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6299*0a6a1f1dSLionel Sambuc   static bool meta_data_declared = false;
6300*0a6a1f1dSLionel Sambuc   if (meta_data_declared)
6301*0a6a1f1dSLionel Sambuc     return;
6302*0a6a1f1dSLionel Sambuc 
6303*0a6a1f1dSLionel Sambuc   Result += "\nstruct _prop_t {\n";
6304*0a6a1f1dSLionel Sambuc   Result += "\tconst char *name;\n";
6305*0a6a1f1dSLionel Sambuc   Result += "\tconst char *attributes;\n";
6306*0a6a1f1dSLionel Sambuc   Result += "};\n";
6307*0a6a1f1dSLionel Sambuc 
6308*0a6a1f1dSLionel Sambuc   Result += "\nstruct _protocol_t;\n";
6309*0a6a1f1dSLionel Sambuc 
6310*0a6a1f1dSLionel Sambuc   Result += "\nstruct _objc_method {\n";
6311*0a6a1f1dSLionel Sambuc   Result += "\tstruct objc_selector * _cmd;\n";
6312*0a6a1f1dSLionel Sambuc   Result += "\tconst char *method_type;\n";
6313*0a6a1f1dSLionel Sambuc   Result += "\tvoid  *_imp;\n";
6314*0a6a1f1dSLionel Sambuc   Result += "};\n";
6315*0a6a1f1dSLionel Sambuc 
6316*0a6a1f1dSLionel Sambuc   Result += "\nstruct _protocol_t {\n";
6317*0a6a1f1dSLionel Sambuc   Result += "\tvoid * isa;  // NULL\n";
6318*0a6a1f1dSLionel Sambuc   Result += "\tconst char *protocol_name;\n";
6319*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6320*0a6a1f1dSLionel Sambuc   Result += "\tconst struct method_list_t *instance_methods;\n";
6321*0a6a1f1dSLionel Sambuc   Result += "\tconst struct method_list_t *class_methods;\n";
6322*0a6a1f1dSLionel Sambuc   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6323*0a6a1f1dSLionel Sambuc   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6324*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _prop_list_t * properties;\n";
6325*0a6a1f1dSLionel Sambuc   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6326*0a6a1f1dSLionel Sambuc   Result += "\tconst unsigned int flags;  // = 0\n";
6327*0a6a1f1dSLionel Sambuc   Result += "\tconst char ** extendedMethodTypes;\n";
6328*0a6a1f1dSLionel Sambuc   Result += "};\n";
6329*0a6a1f1dSLionel Sambuc 
6330*0a6a1f1dSLionel Sambuc   Result += "\nstruct _ivar_t {\n";
6331*0a6a1f1dSLionel Sambuc   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6332*0a6a1f1dSLionel Sambuc   Result += "\tconst char *name;\n";
6333*0a6a1f1dSLionel Sambuc   Result += "\tconst char *type;\n";
6334*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int alignment;\n";
6335*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int  size;\n";
6336*0a6a1f1dSLionel Sambuc   Result += "};\n";
6337*0a6a1f1dSLionel Sambuc 
6338*0a6a1f1dSLionel Sambuc   Result += "\nstruct _class_ro_t {\n";
6339*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int flags;\n";
6340*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int instanceStart;\n";
6341*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int instanceSize;\n";
6342*0a6a1f1dSLionel Sambuc   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6343*0a6a1f1dSLionel Sambuc   if (Triple.getArch() == llvm::Triple::x86_64)
6344*0a6a1f1dSLionel Sambuc     Result += "\tunsigned int reserved;\n";
6345*0a6a1f1dSLionel Sambuc   Result += "\tconst unsigned char *ivarLayout;\n";
6346*0a6a1f1dSLionel Sambuc   Result += "\tconst char *name;\n";
6347*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _method_list_t *baseMethods;\n";
6348*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6349*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _ivar_list_t *ivars;\n";
6350*0a6a1f1dSLionel Sambuc   Result += "\tconst unsigned char *weakIvarLayout;\n";
6351*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _prop_list_t *properties;\n";
6352*0a6a1f1dSLionel Sambuc   Result += "};\n";
6353*0a6a1f1dSLionel Sambuc 
6354*0a6a1f1dSLionel Sambuc   Result += "\nstruct _class_t {\n";
6355*0a6a1f1dSLionel Sambuc   Result += "\tstruct _class_t *isa;\n";
6356*0a6a1f1dSLionel Sambuc   Result += "\tstruct _class_t *superclass;\n";
6357*0a6a1f1dSLionel Sambuc   Result += "\tvoid *cache;\n";
6358*0a6a1f1dSLionel Sambuc   Result += "\tvoid *vtable;\n";
6359*0a6a1f1dSLionel Sambuc   Result += "\tstruct _class_ro_t *ro;\n";
6360*0a6a1f1dSLionel Sambuc   Result += "};\n";
6361*0a6a1f1dSLionel Sambuc 
6362*0a6a1f1dSLionel Sambuc   Result += "\nstruct _category_t {\n";
6363*0a6a1f1dSLionel Sambuc   Result += "\tconst char *name;\n";
6364*0a6a1f1dSLionel Sambuc   Result += "\tstruct _class_t *cls;\n";
6365*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _method_list_t *instance_methods;\n";
6366*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _method_list_t *class_methods;\n";
6367*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _protocol_list_t *protocols;\n";
6368*0a6a1f1dSLionel Sambuc   Result += "\tconst struct _prop_list_t *properties;\n";
6369*0a6a1f1dSLionel Sambuc   Result += "};\n";
6370*0a6a1f1dSLionel Sambuc 
6371*0a6a1f1dSLionel Sambuc   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6372*0a6a1f1dSLionel Sambuc   Result += "#pragma warning(disable:4273)\n";
6373*0a6a1f1dSLionel Sambuc   meta_data_declared = true;
6374*0a6a1f1dSLionel Sambuc }
6375*0a6a1f1dSLionel Sambuc 
Write_protocol_list_t_TypeDecl(std::string & Result,long super_protocol_count)6376*0a6a1f1dSLionel Sambuc static void Write_protocol_list_t_TypeDecl(std::string &Result,
6377*0a6a1f1dSLionel Sambuc                                            long super_protocol_count) {
6378*0a6a1f1dSLionel Sambuc   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6379*0a6a1f1dSLionel Sambuc   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6380*0a6a1f1dSLionel Sambuc   Result += "\tstruct _protocol_t *super_protocols[";
6381*0a6a1f1dSLionel Sambuc   Result += utostr(super_protocol_count); Result += "];\n";
6382*0a6a1f1dSLionel Sambuc   Result += "}";
6383*0a6a1f1dSLionel Sambuc }
6384*0a6a1f1dSLionel Sambuc 
Write_method_list_t_TypeDecl(std::string & Result,unsigned int method_count)6385*0a6a1f1dSLionel Sambuc static void Write_method_list_t_TypeDecl(std::string &Result,
6386*0a6a1f1dSLionel Sambuc                                          unsigned int method_count) {
6387*0a6a1f1dSLionel Sambuc   Result += "struct /*_method_list_t*/"; Result += " {\n";
6388*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6389*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int method_count;\n";
6390*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_method method_list[";
6391*0a6a1f1dSLionel Sambuc   Result += utostr(method_count); Result += "];\n";
6392*0a6a1f1dSLionel Sambuc   Result += "}";
6393*0a6a1f1dSLionel Sambuc }
6394*0a6a1f1dSLionel Sambuc 
Write__prop_list_t_TypeDecl(std::string & Result,unsigned int property_count)6395*0a6a1f1dSLionel Sambuc static void Write__prop_list_t_TypeDecl(std::string &Result,
6396*0a6a1f1dSLionel Sambuc                                         unsigned int property_count) {
6397*0a6a1f1dSLionel Sambuc   Result += "struct /*_prop_list_t*/"; Result += " {\n";
6398*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6399*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int count_of_properties;\n";
6400*0a6a1f1dSLionel Sambuc   Result += "\tstruct _prop_t prop_list[";
6401*0a6a1f1dSLionel Sambuc   Result += utostr(property_count); Result += "];\n";
6402*0a6a1f1dSLionel Sambuc   Result += "}";
6403*0a6a1f1dSLionel Sambuc }
6404*0a6a1f1dSLionel Sambuc 
Write__ivar_list_t_TypeDecl(std::string & Result,unsigned int ivar_count)6405*0a6a1f1dSLionel Sambuc static void Write__ivar_list_t_TypeDecl(std::string &Result,
6406*0a6a1f1dSLionel Sambuc                                         unsigned int ivar_count) {
6407*0a6a1f1dSLionel Sambuc   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6408*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6409*0a6a1f1dSLionel Sambuc   Result += "\tunsigned int count;\n";
6410*0a6a1f1dSLionel Sambuc   Result += "\tstruct _ivar_t ivar_list[";
6411*0a6a1f1dSLionel Sambuc   Result += utostr(ivar_count); Result += "];\n";
6412*0a6a1f1dSLionel Sambuc   Result += "}";
6413*0a6a1f1dSLionel Sambuc }
6414*0a6a1f1dSLionel Sambuc 
Write_protocol_list_initializer(ASTContext * Context,std::string & Result,ArrayRef<ObjCProtocolDecl * > SuperProtocols,StringRef VarName,StringRef ProtocolName)6415*0a6a1f1dSLionel Sambuc static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6416*0a6a1f1dSLionel Sambuc                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6417*0a6a1f1dSLionel Sambuc                                             StringRef VarName,
6418*0a6a1f1dSLionel Sambuc                                             StringRef ProtocolName) {
6419*0a6a1f1dSLionel Sambuc   if (SuperProtocols.size() > 0) {
6420*0a6a1f1dSLionel Sambuc     Result += "\nstatic ";
6421*0a6a1f1dSLionel Sambuc     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6422*0a6a1f1dSLionel Sambuc     Result += " "; Result += VarName;
6423*0a6a1f1dSLionel Sambuc     Result += ProtocolName;
6424*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6425*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6426*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6427*0a6a1f1dSLionel Sambuc       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6428*0a6a1f1dSLionel Sambuc       Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6429*0a6a1f1dSLionel Sambuc       Result += SuperPD->getNameAsString();
6430*0a6a1f1dSLionel Sambuc       if (i == e-1)
6431*0a6a1f1dSLionel Sambuc         Result += "\n};\n";
6432*0a6a1f1dSLionel Sambuc       else
6433*0a6a1f1dSLionel Sambuc         Result += ",\n";
6434*0a6a1f1dSLionel Sambuc     }
6435*0a6a1f1dSLionel Sambuc   }
6436*0a6a1f1dSLionel Sambuc }
6437*0a6a1f1dSLionel Sambuc 
Write_method_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCMethodDecl * > Methods,StringRef VarName,StringRef TopLevelDeclName,bool MethodImpl)6438*0a6a1f1dSLionel Sambuc static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6439*0a6a1f1dSLionel Sambuc                                             ASTContext *Context, std::string &Result,
6440*0a6a1f1dSLionel Sambuc                                             ArrayRef<ObjCMethodDecl *> Methods,
6441*0a6a1f1dSLionel Sambuc                                             StringRef VarName,
6442*0a6a1f1dSLionel Sambuc                                             StringRef TopLevelDeclName,
6443*0a6a1f1dSLionel Sambuc                                             bool MethodImpl) {
6444*0a6a1f1dSLionel Sambuc   if (Methods.size() > 0) {
6445*0a6a1f1dSLionel Sambuc     Result += "\nstatic ";
6446*0a6a1f1dSLionel Sambuc     Write_method_list_t_TypeDecl(Result, Methods.size());
6447*0a6a1f1dSLionel Sambuc     Result += " "; Result += VarName;
6448*0a6a1f1dSLionel Sambuc     Result += TopLevelDeclName;
6449*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6450*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6451*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6452*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6453*0a6a1f1dSLionel Sambuc       ObjCMethodDecl *MD = Methods[i];
6454*0a6a1f1dSLionel Sambuc       if (i == 0)
6455*0a6a1f1dSLionel Sambuc         Result += "\t{{(struct objc_selector *)\"";
6456*0a6a1f1dSLionel Sambuc       else
6457*0a6a1f1dSLionel Sambuc         Result += "\t{(struct objc_selector *)\"";
6458*0a6a1f1dSLionel Sambuc       Result += (MD)->getSelector().getAsString(); Result += "\"";
6459*0a6a1f1dSLionel Sambuc       Result += ", ";
6460*0a6a1f1dSLionel Sambuc       std::string MethodTypeString;
6461*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6462*0a6a1f1dSLionel Sambuc       Result += "\""; Result += MethodTypeString; Result += "\"";
6463*0a6a1f1dSLionel Sambuc       Result += ", ";
6464*0a6a1f1dSLionel Sambuc       if (!MethodImpl)
6465*0a6a1f1dSLionel Sambuc         Result += "0";
6466*0a6a1f1dSLionel Sambuc       else {
6467*0a6a1f1dSLionel Sambuc         Result += "(void *)";
6468*0a6a1f1dSLionel Sambuc         Result += RewriteObj.MethodInternalNames[MD];
6469*0a6a1f1dSLionel Sambuc       }
6470*0a6a1f1dSLionel Sambuc       if (i  == e-1)
6471*0a6a1f1dSLionel Sambuc         Result += "}}\n";
6472*0a6a1f1dSLionel Sambuc       else
6473*0a6a1f1dSLionel Sambuc         Result += "},\n";
6474*0a6a1f1dSLionel Sambuc     }
6475*0a6a1f1dSLionel Sambuc     Result += "};\n";
6476*0a6a1f1dSLionel Sambuc   }
6477*0a6a1f1dSLionel Sambuc }
6478*0a6a1f1dSLionel Sambuc 
Write_prop_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCPropertyDecl * > Properties,const Decl * Container,StringRef VarName,StringRef ProtocolName)6479*0a6a1f1dSLionel Sambuc static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6480*0a6a1f1dSLionel Sambuc                                            ASTContext *Context, std::string &Result,
6481*0a6a1f1dSLionel Sambuc                                            ArrayRef<ObjCPropertyDecl *> Properties,
6482*0a6a1f1dSLionel Sambuc                                            const Decl *Container,
6483*0a6a1f1dSLionel Sambuc                                            StringRef VarName,
6484*0a6a1f1dSLionel Sambuc                                            StringRef ProtocolName) {
6485*0a6a1f1dSLionel Sambuc   if (Properties.size() > 0) {
6486*0a6a1f1dSLionel Sambuc     Result += "\nstatic ";
6487*0a6a1f1dSLionel Sambuc     Write__prop_list_t_TypeDecl(Result, Properties.size());
6488*0a6a1f1dSLionel Sambuc     Result += " "; Result += VarName;
6489*0a6a1f1dSLionel Sambuc     Result += ProtocolName;
6490*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6491*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6492*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6493*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6494*0a6a1f1dSLionel Sambuc       ObjCPropertyDecl *PropDecl = Properties[i];
6495*0a6a1f1dSLionel Sambuc       if (i == 0)
6496*0a6a1f1dSLionel Sambuc         Result += "\t{{\"";
6497*0a6a1f1dSLionel Sambuc       else
6498*0a6a1f1dSLionel Sambuc         Result += "\t{\"";
6499*0a6a1f1dSLionel Sambuc       Result += PropDecl->getName(); Result += "\",";
6500*0a6a1f1dSLionel Sambuc       std::string PropertyTypeString, QuotePropertyTypeString;
6501*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6502*0a6a1f1dSLionel Sambuc       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6503*0a6a1f1dSLionel Sambuc       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6504*0a6a1f1dSLionel Sambuc       if (i  == e-1)
6505*0a6a1f1dSLionel Sambuc         Result += "}}\n";
6506*0a6a1f1dSLionel Sambuc       else
6507*0a6a1f1dSLionel Sambuc         Result += "},\n";
6508*0a6a1f1dSLionel Sambuc     }
6509*0a6a1f1dSLionel Sambuc     Result += "};\n";
6510*0a6a1f1dSLionel Sambuc   }
6511*0a6a1f1dSLionel Sambuc }
6512*0a6a1f1dSLionel Sambuc 
6513*0a6a1f1dSLionel Sambuc // Metadata flags
6514*0a6a1f1dSLionel Sambuc enum MetaDataDlags {
6515*0a6a1f1dSLionel Sambuc   CLS = 0x0,
6516*0a6a1f1dSLionel Sambuc   CLS_META = 0x1,
6517*0a6a1f1dSLionel Sambuc   CLS_ROOT = 0x2,
6518*0a6a1f1dSLionel Sambuc   OBJC2_CLS_HIDDEN = 0x10,
6519*0a6a1f1dSLionel Sambuc   CLS_EXCEPTION = 0x20,
6520*0a6a1f1dSLionel Sambuc 
6521*0a6a1f1dSLionel Sambuc   /// (Obsolete) ARC-specific: this class has a .release_ivars method
6522*0a6a1f1dSLionel Sambuc   CLS_HAS_IVAR_RELEASER = 0x40,
6523*0a6a1f1dSLionel Sambuc   /// class was compiled with -fobjc-arr
6524*0a6a1f1dSLionel Sambuc   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6525*0a6a1f1dSLionel Sambuc };
6526*0a6a1f1dSLionel Sambuc 
Write__class_ro_t_initializer(ASTContext * Context,std::string & Result,unsigned int flags,const std::string & InstanceStart,const std::string & InstanceSize,ArrayRef<ObjCMethodDecl * > baseMethods,ArrayRef<ObjCProtocolDecl * > baseProtocols,ArrayRef<ObjCIvarDecl * > ivars,ArrayRef<ObjCPropertyDecl * > Properties,StringRef VarName,StringRef ClassName)6527*0a6a1f1dSLionel Sambuc static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6528*0a6a1f1dSLionel Sambuc                                           unsigned int flags,
6529*0a6a1f1dSLionel Sambuc                                           const std::string &InstanceStart,
6530*0a6a1f1dSLionel Sambuc                                           const std::string &InstanceSize,
6531*0a6a1f1dSLionel Sambuc                                           ArrayRef<ObjCMethodDecl *>baseMethods,
6532*0a6a1f1dSLionel Sambuc                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
6533*0a6a1f1dSLionel Sambuc                                           ArrayRef<ObjCIvarDecl *>ivars,
6534*0a6a1f1dSLionel Sambuc                                           ArrayRef<ObjCPropertyDecl *>Properties,
6535*0a6a1f1dSLionel Sambuc                                           StringRef VarName,
6536*0a6a1f1dSLionel Sambuc                                           StringRef ClassName) {
6537*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _class_ro_t ";
6538*0a6a1f1dSLionel Sambuc   Result += VarName; Result += ClassName;
6539*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6540*0a6a1f1dSLionel Sambuc   Result += "\t";
6541*0a6a1f1dSLionel Sambuc   Result += llvm::utostr(flags); Result += ", ";
6542*0a6a1f1dSLionel Sambuc   Result += InstanceStart; Result += ", ";
6543*0a6a1f1dSLionel Sambuc   Result += InstanceSize; Result += ", \n";
6544*0a6a1f1dSLionel Sambuc   Result += "\t";
6545*0a6a1f1dSLionel Sambuc   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6546*0a6a1f1dSLionel Sambuc   if (Triple.getArch() == llvm::Triple::x86_64)
6547*0a6a1f1dSLionel Sambuc     // uint32_t const reserved; // only when building for 64bit targets
6548*0a6a1f1dSLionel Sambuc     Result += "(unsigned int)0, \n\t";
6549*0a6a1f1dSLionel Sambuc   // const uint8_t * const ivarLayout;
6550*0a6a1f1dSLionel Sambuc   Result += "0, \n\t";
6551*0a6a1f1dSLionel Sambuc   Result += "\""; Result += ClassName; Result += "\",\n\t";
6552*0a6a1f1dSLionel Sambuc   bool metaclass = ((flags & CLS_META) != 0);
6553*0a6a1f1dSLionel Sambuc   if (baseMethods.size() > 0) {
6554*0a6a1f1dSLionel Sambuc     Result += "(const struct _method_list_t *)&";
6555*0a6a1f1dSLionel Sambuc     if (metaclass)
6556*0a6a1f1dSLionel Sambuc       Result += "_OBJC_$_CLASS_METHODS_";
6557*0a6a1f1dSLionel Sambuc     else
6558*0a6a1f1dSLionel Sambuc       Result += "_OBJC_$_INSTANCE_METHODS_";
6559*0a6a1f1dSLionel Sambuc     Result += ClassName;
6560*0a6a1f1dSLionel Sambuc     Result += ",\n\t";
6561*0a6a1f1dSLionel Sambuc   }
6562*0a6a1f1dSLionel Sambuc   else
6563*0a6a1f1dSLionel Sambuc     Result += "0, \n\t";
6564*0a6a1f1dSLionel Sambuc 
6565*0a6a1f1dSLionel Sambuc   if (!metaclass && baseProtocols.size() > 0) {
6566*0a6a1f1dSLionel Sambuc     Result += "(const struct _objc_protocol_list *)&";
6567*0a6a1f1dSLionel Sambuc     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6568*0a6a1f1dSLionel Sambuc     Result += ",\n\t";
6569*0a6a1f1dSLionel Sambuc   }
6570*0a6a1f1dSLionel Sambuc   else
6571*0a6a1f1dSLionel Sambuc     Result += "0, \n\t";
6572*0a6a1f1dSLionel Sambuc 
6573*0a6a1f1dSLionel Sambuc   if (!metaclass && ivars.size() > 0) {
6574*0a6a1f1dSLionel Sambuc     Result += "(const struct _ivar_list_t *)&";
6575*0a6a1f1dSLionel Sambuc     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6576*0a6a1f1dSLionel Sambuc     Result += ",\n\t";
6577*0a6a1f1dSLionel Sambuc   }
6578*0a6a1f1dSLionel Sambuc   else
6579*0a6a1f1dSLionel Sambuc     Result += "0, \n\t";
6580*0a6a1f1dSLionel Sambuc 
6581*0a6a1f1dSLionel Sambuc   // weakIvarLayout
6582*0a6a1f1dSLionel Sambuc   Result += "0, \n\t";
6583*0a6a1f1dSLionel Sambuc   if (!metaclass && Properties.size() > 0) {
6584*0a6a1f1dSLionel Sambuc     Result += "(const struct _prop_list_t *)&";
6585*0a6a1f1dSLionel Sambuc     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6586*0a6a1f1dSLionel Sambuc     Result += ",\n";
6587*0a6a1f1dSLionel Sambuc   }
6588*0a6a1f1dSLionel Sambuc   else
6589*0a6a1f1dSLionel Sambuc     Result += "0, \n";
6590*0a6a1f1dSLionel Sambuc 
6591*0a6a1f1dSLionel Sambuc   Result += "};\n";
6592*0a6a1f1dSLionel Sambuc }
6593*0a6a1f1dSLionel Sambuc 
Write_class_t(ASTContext * Context,std::string & Result,StringRef VarName,const ObjCInterfaceDecl * CDecl,bool metaclass)6594*0a6a1f1dSLionel Sambuc static void Write_class_t(ASTContext *Context, std::string &Result,
6595*0a6a1f1dSLionel Sambuc                           StringRef VarName,
6596*0a6a1f1dSLionel Sambuc                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
6597*0a6a1f1dSLionel Sambuc   bool rootClass = (!CDecl->getSuperClass());
6598*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *RootClass = CDecl;
6599*0a6a1f1dSLionel Sambuc 
6600*0a6a1f1dSLionel Sambuc   if (!rootClass) {
6601*0a6a1f1dSLionel Sambuc     // Find the Root class
6602*0a6a1f1dSLionel Sambuc     RootClass = CDecl->getSuperClass();
6603*0a6a1f1dSLionel Sambuc     while (RootClass->getSuperClass()) {
6604*0a6a1f1dSLionel Sambuc       RootClass = RootClass->getSuperClass();
6605*0a6a1f1dSLionel Sambuc     }
6606*0a6a1f1dSLionel Sambuc   }
6607*0a6a1f1dSLionel Sambuc 
6608*0a6a1f1dSLionel Sambuc   if (metaclass && rootClass) {
6609*0a6a1f1dSLionel Sambuc     // Need to handle a case of use of forward declaration.
6610*0a6a1f1dSLionel Sambuc     Result += "\n";
6611*0a6a1f1dSLionel Sambuc     Result += "extern \"C\" ";
6612*0a6a1f1dSLionel Sambuc     if (CDecl->getImplementation())
6613*0a6a1f1dSLionel Sambuc       Result += "__declspec(dllexport) ";
6614*0a6a1f1dSLionel Sambuc     else
6615*0a6a1f1dSLionel Sambuc       Result += "__declspec(dllimport) ";
6616*0a6a1f1dSLionel Sambuc 
6617*0a6a1f1dSLionel Sambuc     Result += "struct _class_t OBJC_CLASS_$_";
6618*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
6619*0a6a1f1dSLionel Sambuc     Result += ";\n";
6620*0a6a1f1dSLionel Sambuc   }
6621*0a6a1f1dSLionel Sambuc   // Also, for possibility of 'super' metadata class not having been defined yet.
6622*0a6a1f1dSLionel Sambuc   if (!rootClass) {
6623*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6624*0a6a1f1dSLionel Sambuc     Result += "\n";
6625*0a6a1f1dSLionel Sambuc     Result += "extern \"C\" ";
6626*0a6a1f1dSLionel Sambuc     if (SuperClass->getImplementation())
6627*0a6a1f1dSLionel Sambuc       Result += "__declspec(dllexport) ";
6628*0a6a1f1dSLionel Sambuc     else
6629*0a6a1f1dSLionel Sambuc       Result += "__declspec(dllimport) ";
6630*0a6a1f1dSLionel Sambuc 
6631*0a6a1f1dSLionel Sambuc     Result += "struct _class_t ";
6632*0a6a1f1dSLionel Sambuc     Result += VarName;
6633*0a6a1f1dSLionel Sambuc     Result += SuperClass->getNameAsString();
6634*0a6a1f1dSLionel Sambuc     Result += ";\n";
6635*0a6a1f1dSLionel Sambuc 
6636*0a6a1f1dSLionel Sambuc     if (metaclass && RootClass != SuperClass) {
6637*0a6a1f1dSLionel Sambuc       Result += "extern \"C\" ";
6638*0a6a1f1dSLionel Sambuc       if (RootClass->getImplementation())
6639*0a6a1f1dSLionel Sambuc         Result += "__declspec(dllexport) ";
6640*0a6a1f1dSLionel Sambuc       else
6641*0a6a1f1dSLionel Sambuc         Result += "__declspec(dllimport) ";
6642*0a6a1f1dSLionel Sambuc 
6643*0a6a1f1dSLionel Sambuc       Result += "struct _class_t ";
6644*0a6a1f1dSLionel Sambuc       Result += VarName;
6645*0a6a1f1dSLionel Sambuc       Result += RootClass->getNameAsString();
6646*0a6a1f1dSLionel Sambuc       Result += ";\n";
6647*0a6a1f1dSLionel Sambuc     }
6648*0a6a1f1dSLionel Sambuc   }
6649*0a6a1f1dSLionel Sambuc 
6650*0a6a1f1dSLionel Sambuc   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6651*0a6a1f1dSLionel Sambuc   Result += VarName; Result += CDecl->getNameAsString();
6652*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6653*0a6a1f1dSLionel Sambuc   Result += "\t";
6654*0a6a1f1dSLionel Sambuc   if (metaclass) {
6655*0a6a1f1dSLionel Sambuc     if (!rootClass) {
6656*0a6a1f1dSLionel Sambuc       Result += "0, // &"; Result += VarName;
6657*0a6a1f1dSLionel Sambuc       Result += RootClass->getNameAsString();
6658*0a6a1f1dSLionel Sambuc       Result += ",\n\t";
6659*0a6a1f1dSLionel Sambuc       Result += "0, // &"; Result += VarName;
6660*0a6a1f1dSLionel Sambuc       Result += CDecl->getSuperClass()->getNameAsString();
6661*0a6a1f1dSLionel Sambuc       Result += ",\n\t";
6662*0a6a1f1dSLionel Sambuc     }
6663*0a6a1f1dSLionel Sambuc     else {
6664*0a6a1f1dSLionel Sambuc       Result += "0, // &"; Result += VarName;
6665*0a6a1f1dSLionel Sambuc       Result += CDecl->getNameAsString();
6666*0a6a1f1dSLionel Sambuc       Result += ",\n\t";
6667*0a6a1f1dSLionel Sambuc       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6668*0a6a1f1dSLionel Sambuc       Result += ",\n\t";
6669*0a6a1f1dSLionel Sambuc     }
6670*0a6a1f1dSLionel Sambuc   }
6671*0a6a1f1dSLionel Sambuc   else {
6672*0a6a1f1dSLionel Sambuc     Result += "0, // &OBJC_METACLASS_$_";
6673*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
6674*0a6a1f1dSLionel Sambuc     Result += ",\n\t";
6675*0a6a1f1dSLionel Sambuc     if (!rootClass) {
6676*0a6a1f1dSLionel Sambuc       Result += "0, // &"; Result += VarName;
6677*0a6a1f1dSLionel Sambuc       Result += CDecl->getSuperClass()->getNameAsString();
6678*0a6a1f1dSLionel Sambuc       Result += ",\n\t";
6679*0a6a1f1dSLionel Sambuc     }
6680*0a6a1f1dSLionel Sambuc     else
6681*0a6a1f1dSLionel Sambuc       Result += "0,\n\t";
6682*0a6a1f1dSLionel Sambuc   }
6683*0a6a1f1dSLionel Sambuc   Result += "0, // (void *)&_objc_empty_cache,\n\t";
6684*0a6a1f1dSLionel Sambuc   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6685*0a6a1f1dSLionel Sambuc   if (metaclass)
6686*0a6a1f1dSLionel Sambuc     Result += "&_OBJC_METACLASS_RO_$_";
6687*0a6a1f1dSLionel Sambuc   else
6688*0a6a1f1dSLionel Sambuc     Result += "&_OBJC_CLASS_RO_$_";
6689*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
6690*0a6a1f1dSLionel Sambuc   Result += ",\n};\n";
6691*0a6a1f1dSLionel Sambuc 
6692*0a6a1f1dSLionel Sambuc   // Add static function to initialize some of the meta-data fields.
6693*0a6a1f1dSLionel Sambuc   // avoid doing it twice.
6694*0a6a1f1dSLionel Sambuc   if (metaclass)
6695*0a6a1f1dSLionel Sambuc     return;
6696*0a6a1f1dSLionel Sambuc 
6697*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *SuperClass =
6698*0a6a1f1dSLionel Sambuc     rootClass ? CDecl : CDecl->getSuperClass();
6699*0a6a1f1dSLionel Sambuc 
6700*0a6a1f1dSLionel Sambuc   Result += "static void OBJC_CLASS_SETUP_$_";
6701*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
6702*0a6a1f1dSLionel Sambuc   Result += "(void ) {\n";
6703*0a6a1f1dSLionel Sambuc   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6704*0a6a1f1dSLionel Sambuc   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6705*0a6a1f1dSLionel Sambuc   Result += RootClass->getNameAsString(); Result += ";\n";
6706*0a6a1f1dSLionel Sambuc 
6707*0a6a1f1dSLionel Sambuc   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6708*0a6a1f1dSLionel Sambuc   Result += ".superclass = ";
6709*0a6a1f1dSLionel Sambuc   if (rootClass)
6710*0a6a1f1dSLionel Sambuc     Result += "&OBJC_CLASS_$_";
6711*0a6a1f1dSLionel Sambuc   else
6712*0a6a1f1dSLionel Sambuc      Result += "&OBJC_METACLASS_$_";
6713*0a6a1f1dSLionel Sambuc 
6714*0a6a1f1dSLionel Sambuc   Result += SuperClass->getNameAsString(); Result += ";\n";
6715*0a6a1f1dSLionel Sambuc 
6716*0a6a1f1dSLionel Sambuc   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6717*0a6a1f1dSLionel Sambuc   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6718*0a6a1f1dSLionel Sambuc 
6719*0a6a1f1dSLionel Sambuc   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6720*0a6a1f1dSLionel Sambuc   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6721*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString(); Result += ";\n";
6722*0a6a1f1dSLionel Sambuc 
6723*0a6a1f1dSLionel Sambuc   if (!rootClass) {
6724*0a6a1f1dSLionel Sambuc     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6725*0a6a1f1dSLionel Sambuc     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6726*0a6a1f1dSLionel Sambuc     Result += SuperClass->getNameAsString(); Result += ";\n";
6727*0a6a1f1dSLionel Sambuc   }
6728*0a6a1f1dSLionel Sambuc 
6729*0a6a1f1dSLionel Sambuc   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6730*0a6a1f1dSLionel Sambuc   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6731*0a6a1f1dSLionel Sambuc   Result += "}\n";
6732*0a6a1f1dSLionel Sambuc }
6733*0a6a1f1dSLionel Sambuc 
Write_category_t(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ObjCCategoryDecl * CatDecl,ObjCInterfaceDecl * ClassDecl,ArrayRef<ObjCMethodDecl * > InstanceMethods,ArrayRef<ObjCMethodDecl * > ClassMethods,ArrayRef<ObjCProtocolDecl * > RefedProtocols,ArrayRef<ObjCPropertyDecl * > ClassProperties)6734*0a6a1f1dSLionel Sambuc static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6735*0a6a1f1dSLionel Sambuc                              std::string &Result,
6736*0a6a1f1dSLionel Sambuc                              ObjCCategoryDecl *CatDecl,
6737*0a6a1f1dSLionel Sambuc                              ObjCInterfaceDecl *ClassDecl,
6738*0a6a1f1dSLionel Sambuc                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
6739*0a6a1f1dSLionel Sambuc                              ArrayRef<ObjCMethodDecl *> ClassMethods,
6740*0a6a1f1dSLionel Sambuc                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6741*0a6a1f1dSLionel Sambuc                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6742*0a6a1f1dSLionel Sambuc   StringRef CatName = CatDecl->getName();
6743*0a6a1f1dSLionel Sambuc   StringRef ClassName = ClassDecl->getName();
6744*0a6a1f1dSLionel Sambuc   // must declare an extern class object in case this class is not implemented
6745*0a6a1f1dSLionel Sambuc   // in this TU.
6746*0a6a1f1dSLionel Sambuc   Result += "\n";
6747*0a6a1f1dSLionel Sambuc   Result += "extern \"C\" ";
6748*0a6a1f1dSLionel Sambuc   if (ClassDecl->getImplementation())
6749*0a6a1f1dSLionel Sambuc     Result += "__declspec(dllexport) ";
6750*0a6a1f1dSLionel Sambuc   else
6751*0a6a1f1dSLionel Sambuc     Result += "__declspec(dllimport) ";
6752*0a6a1f1dSLionel Sambuc 
6753*0a6a1f1dSLionel Sambuc   Result += "struct _class_t ";
6754*0a6a1f1dSLionel Sambuc   Result += "OBJC_CLASS_$_"; Result += ClassName;
6755*0a6a1f1dSLionel Sambuc   Result += ";\n";
6756*0a6a1f1dSLionel Sambuc 
6757*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _category_t ";
6758*0a6a1f1dSLionel Sambuc   Result += "_OBJC_$_CATEGORY_";
6759*0a6a1f1dSLionel Sambuc   Result += ClassName; Result += "_$_"; Result += CatName;
6760*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6761*0a6a1f1dSLionel Sambuc   Result += "{\n";
6762*0a6a1f1dSLionel Sambuc   Result += "\t\""; Result += ClassName; Result += "\",\n";
6763*0a6a1f1dSLionel Sambuc   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6764*0a6a1f1dSLionel Sambuc   Result += ",\n";
6765*0a6a1f1dSLionel Sambuc   if (InstanceMethods.size() > 0) {
6766*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _method_list_t *)&";
6767*0a6a1f1dSLionel Sambuc     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6768*0a6a1f1dSLionel Sambuc     Result += ClassName; Result += "_$_"; Result += CatName;
6769*0a6a1f1dSLionel Sambuc     Result += ",\n";
6770*0a6a1f1dSLionel Sambuc   }
6771*0a6a1f1dSLionel Sambuc   else
6772*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
6773*0a6a1f1dSLionel Sambuc 
6774*0a6a1f1dSLionel Sambuc   if (ClassMethods.size() > 0) {
6775*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _method_list_t *)&";
6776*0a6a1f1dSLionel Sambuc     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6777*0a6a1f1dSLionel Sambuc     Result += ClassName; Result += "_$_"; Result += CatName;
6778*0a6a1f1dSLionel Sambuc     Result += ",\n";
6779*0a6a1f1dSLionel Sambuc   }
6780*0a6a1f1dSLionel Sambuc   else
6781*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
6782*0a6a1f1dSLionel Sambuc 
6783*0a6a1f1dSLionel Sambuc   if (RefedProtocols.size() > 0) {
6784*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _protocol_list_t *)&";
6785*0a6a1f1dSLionel Sambuc     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6786*0a6a1f1dSLionel Sambuc     Result += ClassName; Result += "_$_"; Result += CatName;
6787*0a6a1f1dSLionel Sambuc     Result += ",\n";
6788*0a6a1f1dSLionel Sambuc   }
6789*0a6a1f1dSLionel Sambuc   else
6790*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
6791*0a6a1f1dSLionel Sambuc 
6792*0a6a1f1dSLionel Sambuc   if (ClassProperties.size() > 0) {
6793*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6794*0a6a1f1dSLionel Sambuc     Result += ClassName; Result += "_$_"; Result += CatName;
6795*0a6a1f1dSLionel Sambuc     Result += ",\n";
6796*0a6a1f1dSLionel Sambuc   }
6797*0a6a1f1dSLionel Sambuc   else
6798*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
6799*0a6a1f1dSLionel Sambuc 
6800*0a6a1f1dSLionel Sambuc   Result += "};\n";
6801*0a6a1f1dSLionel Sambuc 
6802*0a6a1f1dSLionel Sambuc   // Add static function to initialize the class pointer in the category structure.
6803*0a6a1f1dSLionel Sambuc   Result += "static void OBJC_CATEGORY_SETUP_$_";
6804*0a6a1f1dSLionel Sambuc   Result += ClassDecl->getNameAsString();
6805*0a6a1f1dSLionel Sambuc   Result += "_$_";
6806*0a6a1f1dSLionel Sambuc   Result += CatName;
6807*0a6a1f1dSLionel Sambuc   Result += "(void ) {\n";
6808*0a6a1f1dSLionel Sambuc   Result += "\t_OBJC_$_CATEGORY_";
6809*0a6a1f1dSLionel Sambuc   Result += ClassDecl->getNameAsString();
6810*0a6a1f1dSLionel Sambuc   Result += "_$_";
6811*0a6a1f1dSLionel Sambuc   Result += CatName;
6812*0a6a1f1dSLionel Sambuc   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6813*0a6a1f1dSLionel Sambuc   Result += ";\n}\n";
6814*0a6a1f1dSLionel Sambuc }
6815*0a6a1f1dSLionel Sambuc 
Write__extendedMethodTypes_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCMethodDecl * > Methods,StringRef VarName,StringRef ProtocolName)6816*0a6a1f1dSLionel Sambuc static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6817*0a6a1f1dSLionel Sambuc                                            ASTContext *Context, std::string &Result,
6818*0a6a1f1dSLionel Sambuc                                            ArrayRef<ObjCMethodDecl *> Methods,
6819*0a6a1f1dSLionel Sambuc                                            StringRef VarName,
6820*0a6a1f1dSLionel Sambuc                                            StringRef ProtocolName) {
6821*0a6a1f1dSLionel Sambuc   if (Methods.size() == 0)
6822*0a6a1f1dSLionel Sambuc     return;
6823*0a6a1f1dSLionel Sambuc 
6824*0a6a1f1dSLionel Sambuc   Result += "\nstatic const char *";
6825*0a6a1f1dSLionel Sambuc   Result += VarName; Result += ProtocolName;
6826*0a6a1f1dSLionel Sambuc   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6827*0a6a1f1dSLionel Sambuc   Result += "{\n";
6828*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6829*0a6a1f1dSLionel Sambuc     ObjCMethodDecl *MD = Methods[i];
6830*0a6a1f1dSLionel Sambuc     std::string MethodTypeString, QuoteMethodTypeString;
6831*0a6a1f1dSLionel Sambuc     Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6832*0a6a1f1dSLionel Sambuc     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6833*0a6a1f1dSLionel Sambuc     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6834*0a6a1f1dSLionel Sambuc     if (i == e-1)
6835*0a6a1f1dSLionel Sambuc       Result += "\n};\n";
6836*0a6a1f1dSLionel Sambuc     else {
6837*0a6a1f1dSLionel Sambuc       Result += ",\n";
6838*0a6a1f1dSLionel Sambuc     }
6839*0a6a1f1dSLionel Sambuc   }
6840*0a6a1f1dSLionel Sambuc }
6841*0a6a1f1dSLionel Sambuc 
Write_IvarOffsetVar(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCIvarDecl * > Ivars,ObjCInterfaceDecl * CDecl)6842*0a6a1f1dSLionel Sambuc static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6843*0a6a1f1dSLionel Sambuc                                 ASTContext *Context,
6844*0a6a1f1dSLionel Sambuc                                 std::string &Result,
6845*0a6a1f1dSLionel Sambuc                                 ArrayRef<ObjCIvarDecl *> Ivars,
6846*0a6a1f1dSLionel Sambuc                                 ObjCInterfaceDecl *CDecl) {
6847*0a6a1f1dSLionel Sambuc   // FIXME. visibilty of offset symbols may have to be set; for Darwin
6848*0a6a1f1dSLionel Sambuc   // this is what happens:
6849*0a6a1f1dSLionel Sambuc   /**
6850*0a6a1f1dSLionel Sambuc    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6851*0a6a1f1dSLionel Sambuc        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6852*0a6a1f1dSLionel Sambuc        Class->getVisibility() == HiddenVisibility)
6853*0a6a1f1dSLionel Sambuc      Visibility shoud be: HiddenVisibility;
6854*0a6a1f1dSLionel Sambuc    else
6855*0a6a1f1dSLionel Sambuc      Visibility shoud be: DefaultVisibility;
6856*0a6a1f1dSLionel Sambuc   */
6857*0a6a1f1dSLionel Sambuc 
6858*0a6a1f1dSLionel Sambuc   Result += "\n";
6859*0a6a1f1dSLionel Sambuc   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6860*0a6a1f1dSLionel Sambuc     ObjCIvarDecl *IvarDecl = Ivars[i];
6861*0a6a1f1dSLionel Sambuc     if (Context->getLangOpts().MicrosoftExt)
6862*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6863*0a6a1f1dSLionel Sambuc 
6864*0a6a1f1dSLionel Sambuc     if (!Context->getLangOpts().MicrosoftExt ||
6865*0a6a1f1dSLionel Sambuc         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6866*0a6a1f1dSLionel Sambuc         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6867*0a6a1f1dSLionel Sambuc       Result += "extern \"C\" unsigned long int ";
6868*0a6a1f1dSLionel Sambuc     else
6869*0a6a1f1dSLionel Sambuc       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6870*0a6a1f1dSLionel Sambuc     if (Ivars[i]->isBitField())
6871*0a6a1f1dSLionel Sambuc       RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6872*0a6a1f1dSLionel Sambuc     else
6873*0a6a1f1dSLionel Sambuc       WriteInternalIvarName(CDecl, IvarDecl, Result);
6874*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6875*0a6a1f1dSLionel Sambuc     Result += " = ";
6876*0a6a1f1dSLionel Sambuc     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6877*0a6a1f1dSLionel Sambuc     Result += ";\n";
6878*0a6a1f1dSLionel Sambuc     if (Ivars[i]->isBitField()) {
6879*0a6a1f1dSLionel Sambuc       // skip over rest of the ivar bitfields.
6880*0a6a1f1dSLionel Sambuc       SKIP_BITFIELDS(i , e, Ivars);
6881*0a6a1f1dSLionel Sambuc     }
6882*0a6a1f1dSLionel Sambuc   }
6883*0a6a1f1dSLionel Sambuc }
6884*0a6a1f1dSLionel Sambuc 
Write__ivar_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCIvarDecl * > OriginalIvars,StringRef VarName,ObjCInterfaceDecl * CDecl)6885*0a6a1f1dSLionel Sambuc static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6886*0a6a1f1dSLionel Sambuc                                            ASTContext *Context, std::string &Result,
6887*0a6a1f1dSLionel Sambuc                                            ArrayRef<ObjCIvarDecl *> OriginalIvars,
6888*0a6a1f1dSLionel Sambuc                                            StringRef VarName,
6889*0a6a1f1dSLionel Sambuc                                            ObjCInterfaceDecl *CDecl) {
6890*0a6a1f1dSLionel Sambuc   if (OriginalIvars.size() > 0) {
6891*0a6a1f1dSLionel Sambuc     Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6892*0a6a1f1dSLionel Sambuc     SmallVector<ObjCIvarDecl *, 8> Ivars;
6893*0a6a1f1dSLionel Sambuc     // strip off all but the first ivar bitfield from each group of ivars.
6894*0a6a1f1dSLionel Sambuc     // Such ivars in the ivar list table will be replaced by their grouping struct
6895*0a6a1f1dSLionel Sambuc     // 'ivar'.
6896*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6897*0a6a1f1dSLionel Sambuc       if (OriginalIvars[i]->isBitField()) {
6898*0a6a1f1dSLionel Sambuc         Ivars.push_back(OriginalIvars[i]);
6899*0a6a1f1dSLionel Sambuc         // skip over rest of the ivar bitfields.
6900*0a6a1f1dSLionel Sambuc         SKIP_BITFIELDS(i , e, OriginalIvars);
6901*0a6a1f1dSLionel Sambuc       }
6902*0a6a1f1dSLionel Sambuc       else
6903*0a6a1f1dSLionel Sambuc         Ivars.push_back(OriginalIvars[i]);
6904*0a6a1f1dSLionel Sambuc     }
6905*0a6a1f1dSLionel Sambuc 
6906*0a6a1f1dSLionel Sambuc     Result += "\nstatic ";
6907*0a6a1f1dSLionel Sambuc     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6908*0a6a1f1dSLionel Sambuc     Result += " "; Result += VarName;
6909*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
6910*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6911*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6912*0a6a1f1dSLionel Sambuc     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6913*0a6a1f1dSLionel Sambuc     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6914*0a6a1f1dSLionel Sambuc       ObjCIvarDecl *IvarDecl = Ivars[i];
6915*0a6a1f1dSLionel Sambuc       if (i == 0)
6916*0a6a1f1dSLionel Sambuc         Result += "\t{{";
6917*0a6a1f1dSLionel Sambuc       else
6918*0a6a1f1dSLionel Sambuc         Result += "\t {";
6919*0a6a1f1dSLionel Sambuc       Result += "(unsigned long int *)&";
6920*0a6a1f1dSLionel Sambuc       if (Ivars[i]->isBitField())
6921*0a6a1f1dSLionel Sambuc         RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6922*0a6a1f1dSLionel Sambuc       else
6923*0a6a1f1dSLionel Sambuc         WriteInternalIvarName(CDecl, IvarDecl, Result);
6924*0a6a1f1dSLionel Sambuc       Result += ", ";
6925*0a6a1f1dSLionel Sambuc 
6926*0a6a1f1dSLionel Sambuc       Result += "\"";
6927*0a6a1f1dSLionel Sambuc       if (Ivars[i]->isBitField())
6928*0a6a1f1dSLionel Sambuc         RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6929*0a6a1f1dSLionel Sambuc       else
6930*0a6a1f1dSLionel Sambuc         Result += IvarDecl->getName();
6931*0a6a1f1dSLionel Sambuc       Result += "\", ";
6932*0a6a1f1dSLionel Sambuc 
6933*0a6a1f1dSLionel Sambuc       QualType IVQT = IvarDecl->getType();
6934*0a6a1f1dSLionel Sambuc       if (IvarDecl->isBitField())
6935*0a6a1f1dSLionel Sambuc         IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6936*0a6a1f1dSLionel Sambuc 
6937*0a6a1f1dSLionel Sambuc       std::string IvarTypeString, QuoteIvarTypeString;
6938*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForType(IVQT, IvarTypeString,
6939*0a6a1f1dSLionel Sambuc                                       IvarDecl);
6940*0a6a1f1dSLionel Sambuc       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6941*0a6a1f1dSLionel Sambuc       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6942*0a6a1f1dSLionel Sambuc 
6943*0a6a1f1dSLionel Sambuc       // FIXME. this alignment represents the host alignment and need be changed to
6944*0a6a1f1dSLionel Sambuc       // represent the target alignment.
6945*0a6a1f1dSLionel Sambuc       unsigned Align = Context->getTypeAlign(IVQT)/8;
6946*0a6a1f1dSLionel Sambuc       Align = llvm::Log2_32(Align);
6947*0a6a1f1dSLionel Sambuc       Result += llvm::utostr(Align); Result += ", ";
6948*0a6a1f1dSLionel Sambuc       CharUnits Size = Context->getTypeSizeInChars(IVQT);
6949*0a6a1f1dSLionel Sambuc       Result += llvm::utostr(Size.getQuantity());
6950*0a6a1f1dSLionel Sambuc       if (i  == e-1)
6951*0a6a1f1dSLionel Sambuc         Result += "}}\n";
6952*0a6a1f1dSLionel Sambuc       else
6953*0a6a1f1dSLionel Sambuc         Result += "},\n";
6954*0a6a1f1dSLionel Sambuc     }
6955*0a6a1f1dSLionel Sambuc     Result += "};\n";
6956*0a6a1f1dSLionel Sambuc   }
6957*0a6a1f1dSLionel Sambuc }
6958*0a6a1f1dSLionel Sambuc 
6959*0a6a1f1dSLionel Sambuc /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
RewriteObjCProtocolMetaData(ObjCProtocolDecl * PDecl,std::string & Result)6960*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6961*0a6a1f1dSLionel Sambuc                                                     std::string &Result) {
6962*0a6a1f1dSLionel Sambuc 
6963*0a6a1f1dSLionel Sambuc   // Do not synthesize the protocol more than once.
6964*0a6a1f1dSLionel Sambuc   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6965*0a6a1f1dSLionel Sambuc     return;
6966*0a6a1f1dSLionel Sambuc   WriteModernMetadataDeclarations(Context, Result);
6967*0a6a1f1dSLionel Sambuc 
6968*0a6a1f1dSLionel Sambuc   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6969*0a6a1f1dSLionel Sambuc     PDecl = Def;
6970*0a6a1f1dSLionel Sambuc   // Must write out all protocol definitions in current qualifier list,
6971*0a6a1f1dSLionel Sambuc   // and in their nested qualifiers before writing out current definition.
6972*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->protocols())
6973*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(I, Result);
6974*0a6a1f1dSLionel Sambuc 
6975*0a6a1f1dSLionel Sambuc   // Construct method lists.
6976*0a6a1f1dSLionel Sambuc   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6977*0a6a1f1dSLionel Sambuc   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6978*0a6a1f1dSLionel Sambuc   for (auto *MD : PDecl->instance_methods()) {
6979*0a6a1f1dSLionel Sambuc     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6980*0a6a1f1dSLionel Sambuc       OptInstanceMethods.push_back(MD);
6981*0a6a1f1dSLionel Sambuc     } else {
6982*0a6a1f1dSLionel Sambuc       InstanceMethods.push_back(MD);
6983*0a6a1f1dSLionel Sambuc     }
6984*0a6a1f1dSLionel Sambuc   }
6985*0a6a1f1dSLionel Sambuc 
6986*0a6a1f1dSLionel Sambuc   for (auto *MD : PDecl->class_methods()) {
6987*0a6a1f1dSLionel Sambuc     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6988*0a6a1f1dSLionel Sambuc       OptClassMethods.push_back(MD);
6989*0a6a1f1dSLionel Sambuc     } else {
6990*0a6a1f1dSLionel Sambuc       ClassMethods.push_back(MD);
6991*0a6a1f1dSLionel Sambuc     }
6992*0a6a1f1dSLionel Sambuc   }
6993*0a6a1f1dSLionel Sambuc   std::vector<ObjCMethodDecl *> AllMethods;
6994*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6995*0a6a1f1dSLionel Sambuc     AllMethods.push_back(InstanceMethods[i]);
6996*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6997*0a6a1f1dSLionel Sambuc     AllMethods.push_back(ClassMethods[i]);
6998*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6999*0a6a1f1dSLionel Sambuc     AllMethods.push_back(OptInstanceMethods[i]);
7000*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7001*0a6a1f1dSLionel Sambuc     AllMethods.push_back(OptClassMethods[i]);
7002*0a6a1f1dSLionel Sambuc 
7003*0a6a1f1dSLionel Sambuc   Write__extendedMethodTypes_initializer(*this, Context, Result,
7004*0a6a1f1dSLionel Sambuc                                          AllMethods,
7005*0a6a1f1dSLionel Sambuc                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
7006*0a6a1f1dSLionel Sambuc                                          PDecl->getNameAsString());
7007*0a6a1f1dSLionel Sambuc   // Protocol's super protocol list
7008*0a6a1f1dSLionel Sambuc   SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
7009*0a6a1f1dSLionel Sambuc   Write_protocol_list_initializer(Context, Result, SuperProtocols,
7010*0a6a1f1dSLionel Sambuc                                   "_OBJC_PROTOCOL_REFS_",
7011*0a6a1f1dSLionel Sambuc                                   PDecl->getNameAsString());
7012*0a6a1f1dSLionel Sambuc 
7013*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7014*0a6a1f1dSLionel Sambuc                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
7015*0a6a1f1dSLionel Sambuc                                   PDecl->getNameAsString(), false);
7016*0a6a1f1dSLionel Sambuc 
7017*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7018*0a6a1f1dSLionel Sambuc                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
7019*0a6a1f1dSLionel Sambuc                                   PDecl->getNameAsString(), false);
7020*0a6a1f1dSLionel Sambuc 
7021*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
7022*0a6a1f1dSLionel Sambuc                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
7023*0a6a1f1dSLionel Sambuc                                   PDecl->getNameAsString(), false);
7024*0a6a1f1dSLionel Sambuc 
7025*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
7026*0a6a1f1dSLionel Sambuc                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
7027*0a6a1f1dSLionel Sambuc                                   PDecl->getNameAsString(), false);
7028*0a6a1f1dSLionel Sambuc 
7029*0a6a1f1dSLionel Sambuc   // Protocol's property metadata.
7030*0a6a1f1dSLionel Sambuc   SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
7031*0a6a1f1dSLionel Sambuc   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
7032*0a6a1f1dSLionel Sambuc                                  /* Container */nullptr,
7033*0a6a1f1dSLionel Sambuc                                  "_OBJC_PROTOCOL_PROPERTIES_",
7034*0a6a1f1dSLionel Sambuc                                  PDecl->getNameAsString());
7035*0a6a1f1dSLionel Sambuc 
7036*0a6a1f1dSLionel Sambuc   // Writer out root metadata for current protocol: struct _protocol_t
7037*0a6a1f1dSLionel Sambuc   Result += "\n";
7038*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
7039*0a6a1f1dSLionel Sambuc     Result += "static ";
7040*0a6a1f1dSLionel Sambuc   Result += "struct _protocol_t _OBJC_PROTOCOL_";
7041*0a6a1f1dSLionel Sambuc   Result += PDecl->getNameAsString();
7042*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7043*0a6a1f1dSLionel Sambuc   Result += "\t0,\n"; // id is; is null
7044*0a6a1f1dSLionel Sambuc   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
7045*0a6a1f1dSLionel Sambuc   if (SuperProtocols.size() > 0) {
7046*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7047*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7048*0a6a1f1dSLionel Sambuc   }
7049*0a6a1f1dSLionel Sambuc   else
7050*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7051*0a6a1f1dSLionel Sambuc   if (InstanceMethods.size() > 0) {
7052*0a6a1f1dSLionel Sambuc     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7053*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7054*0a6a1f1dSLionel Sambuc   }
7055*0a6a1f1dSLionel Sambuc   else
7056*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7057*0a6a1f1dSLionel Sambuc 
7058*0a6a1f1dSLionel Sambuc   if (ClassMethods.size() > 0) {
7059*0a6a1f1dSLionel Sambuc     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7060*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7061*0a6a1f1dSLionel Sambuc   }
7062*0a6a1f1dSLionel Sambuc   else
7063*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7064*0a6a1f1dSLionel Sambuc 
7065*0a6a1f1dSLionel Sambuc   if (OptInstanceMethods.size() > 0) {
7066*0a6a1f1dSLionel Sambuc     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7067*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7068*0a6a1f1dSLionel Sambuc   }
7069*0a6a1f1dSLionel Sambuc   else
7070*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7071*0a6a1f1dSLionel Sambuc 
7072*0a6a1f1dSLionel Sambuc   if (OptClassMethods.size() > 0) {
7073*0a6a1f1dSLionel Sambuc     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7074*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7075*0a6a1f1dSLionel Sambuc   }
7076*0a6a1f1dSLionel Sambuc   else
7077*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7078*0a6a1f1dSLionel Sambuc 
7079*0a6a1f1dSLionel Sambuc   if (ProtocolProperties.size() > 0) {
7080*0a6a1f1dSLionel Sambuc     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7081*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString(); Result += ",\n";
7082*0a6a1f1dSLionel Sambuc   }
7083*0a6a1f1dSLionel Sambuc   else
7084*0a6a1f1dSLionel Sambuc     Result += "\t0,\n";
7085*0a6a1f1dSLionel Sambuc 
7086*0a6a1f1dSLionel Sambuc   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7087*0a6a1f1dSLionel Sambuc   Result += "\t0,\n";
7088*0a6a1f1dSLionel Sambuc 
7089*0a6a1f1dSLionel Sambuc   if (AllMethods.size() > 0) {
7090*0a6a1f1dSLionel Sambuc     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7091*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString();
7092*0a6a1f1dSLionel Sambuc     Result += "\n};\n";
7093*0a6a1f1dSLionel Sambuc   }
7094*0a6a1f1dSLionel Sambuc   else
7095*0a6a1f1dSLionel Sambuc     Result += "\t0\n};\n";
7096*0a6a1f1dSLionel Sambuc 
7097*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
7098*0a6a1f1dSLionel Sambuc     Result += "static ";
7099*0a6a1f1dSLionel Sambuc   Result += "struct _protocol_t *";
7100*0a6a1f1dSLionel Sambuc   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7101*0a6a1f1dSLionel Sambuc   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7102*0a6a1f1dSLionel Sambuc   Result += ";\n";
7103*0a6a1f1dSLionel Sambuc 
7104*0a6a1f1dSLionel Sambuc   // Mark this protocol as having been generated.
7105*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
7106*0a6a1f1dSLionel Sambuc     llvm_unreachable("protocol already synthesized");
7107*0a6a1f1dSLionel Sambuc 
7108*0a6a1f1dSLionel Sambuc }
7109*0a6a1f1dSLionel Sambuc 
RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> & Protocols,StringRef prefix,StringRef ClassName,std::string & Result)7110*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7111*0a6a1f1dSLionel Sambuc                                 const ObjCList<ObjCProtocolDecl> &Protocols,
7112*0a6a1f1dSLionel Sambuc                                 StringRef prefix, StringRef ClassName,
7113*0a6a1f1dSLionel Sambuc                                 std::string &Result) {
7114*0a6a1f1dSLionel Sambuc   if (Protocols.empty()) return;
7115*0a6a1f1dSLionel Sambuc 
7116*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i != Protocols.size(); i++)
7117*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(Protocols[i], Result);
7118*0a6a1f1dSLionel Sambuc 
7119*0a6a1f1dSLionel Sambuc   // Output the top lovel protocol meta-data for the class.
7120*0a6a1f1dSLionel Sambuc   /* struct _objc_protocol_list {
7121*0a6a1f1dSLionel Sambuc    struct _objc_protocol_list *next;
7122*0a6a1f1dSLionel Sambuc    int    protocol_count;
7123*0a6a1f1dSLionel Sambuc    struct _objc_protocol *class_protocols[];
7124*0a6a1f1dSLionel Sambuc    }
7125*0a6a1f1dSLionel Sambuc    */
7126*0a6a1f1dSLionel Sambuc   Result += "\n";
7127*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
7128*0a6a1f1dSLionel Sambuc     Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7129*0a6a1f1dSLionel Sambuc   Result += "static struct {\n";
7130*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_protocol_list *next;\n";
7131*0a6a1f1dSLionel Sambuc   Result += "\tint    protocol_count;\n";
7132*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_protocol *class_protocols[";
7133*0a6a1f1dSLionel Sambuc   Result += utostr(Protocols.size());
7134*0a6a1f1dSLionel Sambuc   Result += "];\n} _OBJC_";
7135*0a6a1f1dSLionel Sambuc   Result += prefix;
7136*0a6a1f1dSLionel Sambuc   Result += "_PROTOCOLS_";
7137*0a6a1f1dSLionel Sambuc   Result += ClassName;
7138*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7139*0a6a1f1dSLionel Sambuc   "{\n\t0, ";
7140*0a6a1f1dSLionel Sambuc   Result += utostr(Protocols.size());
7141*0a6a1f1dSLionel Sambuc   Result += "\n";
7142*0a6a1f1dSLionel Sambuc 
7143*0a6a1f1dSLionel Sambuc   Result += "\t,{&_OBJC_PROTOCOL_";
7144*0a6a1f1dSLionel Sambuc   Result += Protocols[0]->getNameAsString();
7145*0a6a1f1dSLionel Sambuc   Result += " \n";
7146*0a6a1f1dSLionel Sambuc 
7147*0a6a1f1dSLionel Sambuc   for (unsigned i = 1; i != Protocols.size(); i++) {
7148*0a6a1f1dSLionel Sambuc     Result += "\t ,&_OBJC_PROTOCOL_";
7149*0a6a1f1dSLionel Sambuc     Result += Protocols[i]->getNameAsString();
7150*0a6a1f1dSLionel Sambuc     Result += "\n";
7151*0a6a1f1dSLionel Sambuc   }
7152*0a6a1f1dSLionel Sambuc   Result += "\t }\n};\n";
7153*0a6a1f1dSLionel Sambuc }
7154*0a6a1f1dSLionel Sambuc 
7155*0a6a1f1dSLionel Sambuc /// hasObjCExceptionAttribute - Return true if this class or any super
7156*0a6a1f1dSLionel Sambuc /// class has the __objc_exception__ attribute.
7157*0a6a1f1dSLionel Sambuc /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
hasObjCExceptionAttribute(ASTContext & Context,const ObjCInterfaceDecl * OID)7158*0a6a1f1dSLionel Sambuc static bool hasObjCExceptionAttribute(ASTContext &Context,
7159*0a6a1f1dSLionel Sambuc                                       const ObjCInterfaceDecl *OID) {
7160*0a6a1f1dSLionel Sambuc   if (OID->hasAttr<ObjCExceptionAttr>())
7161*0a6a1f1dSLionel Sambuc     return true;
7162*0a6a1f1dSLionel Sambuc   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7163*0a6a1f1dSLionel Sambuc     return hasObjCExceptionAttribute(Context, Super);
7164*0a6a1f1dSLionel Sambuc   return false;
7165*0a6a1f1dSLionel Sambuc }
7166*0a6a1f1dSLionel Sambuc 
RewriteObjCClassMetaData(ObjCImplementationDecl * IDecl,std::string & Result)7167*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7168*0a6a1f1dSLionel Sambuc                                            std::string &Result) {
7169*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7170*0a6a1f1dSLionel Sambuc 
7171*0a6a1f1dSLionel Sambuc   // Explicitly declared @interface's are already synthesized.
7172*0a6a1f1dSLionel Sambuc   if (CDecl->isImplicitInterfaceDecl())
7173*0a6a1f1dSLionel Sambuc     assert(false &&
7174*0a6a1f1dSLionel Sambuc            "Legacy implicit interface rewriting not supported in moder abi");
7175*0a6a1f1dSLionel Sambuc 
7176*0a6a1f1dSLionel Sambuc   WriteModernMetadataDeclarations(Context, Result);
7177*0a6a1f1dSLionel Sambuc   SmallVector<ObjCIvarDecl *, 8> IVars;
7178*0a6a1f1dSLionel Sambuc 
7179*0a6a1f1dSLionel Sambuc   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7180*0a6a1f1dSLionel Sambuc       IVD; IVD = IVD->getNextIvar()) {
7181*0a6a1f1dSLionel Sambuc     // Ignore unnamed bit-fields.
7182*0a6a1f1dSLionel Sambuc     if (!IVD->getDeclName())
7183*0a6a1f1dSLionel Sambuc       continue;
7184*0a6a1f1dSLionel Sambuc     IVars.push_back(IVD);
7185*0a6a1f1dSLionel Sambuc   }
7186*0a6a1f1dSLionel Sambuc 
7187*0a6a1f1dSLionel Sambuc   Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7188*0a6a1f1dSLionel Sambuc                                  "_OBJC_$_INSTANCE_VARIABLES_",
7189*0a6a1f1dSLionel Sambuc                                  CDecl);
7190*0a6a1f1dSLionel Sambuc 
7191*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's instance methods if needed
7192*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7193*0a6a1f1dSLionel Sambuc 
7194*0a6a1f1dSLionel Sambuc   // If any of our property implementations have associated getters or
7195*0a6a1f1dSLionel Sambuc   // setters, produce metadata for them as well.
7196*0a6a1f1dSLionel Sambuc   for (const auto *Prop : IDecl->property_impls()) {
7197*0a6a1f1dSLionel Sambuc     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7198*0a6a1f1dSLionel Sambuc       continue;
7199*0a6a1f1dSLionel Sambuc     if (!Prop->getPropertyIvarDecl())
7200*0a6a1f1dSLionel Sambuc       continue;
7201*0a6a1f1dSLionel Sambuc     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7202*0a6a1f1dSLionel Sambuc     if (!PD)
7203*0a6a1f1dSLionel Sambuc       continue;
7204*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7205*0a6a1f1dSLionel Sambuc       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7206*0a6a1f1dSLionel Sambuc         InstanceMethods.push_back(Getter);
7207*0a6a1f1dSLionel Sambuc     if (PD->isReadOnly())
7208*0a6a1f1dSLionel Sambuc       continue;
7209*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7210*0a6a1f1dSLionel Sambuc       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7211*0a6a1f1dSLionel Sambuc         InstanceMethods.push_back(Setter);
7212*0a6a1f1dSLionel Sambuc   }
7213*0a6a1f1dSLionel Sambuc 
7214*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7215*0a6a1f1dSLionel Sambuc                                   "_OBJC_$_INSTANCE_METHODS_",
7216*0a6a1f1dSLionel Sambuc                                   IDecl->getNameAsString(), true);
7217*0a6a1f1dSLionel Sambuc 
7218*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7219*0a6a1f1dSLionel Sambuc 
7220*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7221*0a6a1f1dSLionel Sambuc                                   "_OBJC_$_CLASS_METHODS_",
7222*0a6a1f1dSLionel Sambuc                                   IDecl->getNameAsString(), true);
7223*0a6a1f1dSLionel Sambuc 
7224*0a6a1f1dSLionel Sambuc   // Protocols referenced in class declaration?
7225*0a6a1f1dSLionel Sambuc   // Protocol's super protocol list
7226*0a6a1f1dSLionel Sambuc   std::vector<ObjCProtocolDecl *> RefedProtocols;
7227*0a6a1f1dSLionel Sambuc   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7228*0a6a1f1dSLionel Sambuc   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7229*0a6a1f1dSLionel Sambuc        E = Protocols.end();
7230*0a6a1f1dSLionel Sambuc        I != E; ++I) {
7231*0a6a1f1dSLionel Sambuc     RefedProtocols.push_back(*I);
7232*0a6a1f1dSLionel Sambuc     // Must write out all protocol definitions in current qualifier list,
7233*0a6a1f1dSLionel Sambuc     // and in their nested qualifiers before writing out current definition.
7234*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(*I, Result);
7235*0a6a1f1dSLionel Sambuc   }
7236*0a6a1f1dSLionel Sambuc 
7237*0a6a1f1dSLionel Sambuc   Write_protocol_list_initializer(Context, Result,
7238*0a6a1f1dSLionel Sambuc                                   RefedProtocols,
7239*0a6a1f1dSLionel Sambuc                                   "_OBJC_CLASS_PROTOCOLS_$_",
7240*0a6a1f1dSLionel Sambuc                                   IDecl->getNameAsString());
7241*0a6a1f1dSLionel Sambuc 
7242*0a6a1f1dSLionel Sambuc   // Protocol's property metadata.
7243*0a6a1f1dSLionel Sambuc   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
7244*0a6a1f1dSLionel Sambuc   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7245*0a6a1f1dSLionel Sambuc                                  /* Container */IDecl,
7246*0a6a1f1dSLionel Sambuc                                  "_OBJC_$_PROP_LIST_",
7247*0a6a1f1dSLionel Sambuc                                  CDecl->getNameAsString());
7248*0a6a1f1dSLionel Sambuc 
7249*0a6a1f1dSLionel Sambuc 
7250*0a6a1f1dSLionel Sambuc   // Data for initializing _class_ro_t  metaclass meta-data
7251*0a6a1f1dSLionel Sambuc   uint32_t flags = CLS_META;
7252*0a6a1f1dSLionel Sambuc   std::string InstanceSize;
7253*0a6a1f1dSLionel Sambuc   std::string InstanceStart;
7254*0a6a1f1dSLionel Sambuc 
7255*0a6a1f1dSLionel Sambuc 
7256*0a6a1f1dSLionel Sambuc   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7257*0a6a1f1dSLionel Sambuc   if (classIsHidden)
7258*0a6a1f1dSLionel Sambuc     flags |= OBJC2_CLS_HIDDEN;
7259*0a6a1f1dSLionel Sambuc 
7260*0a6a1f1dSLionel Sambuc   if (!CDecl->getSuperClass())
7261*0a6a1f1dSLionel Sambuc     // class is root
7262*0a6a1f1dSLionel Sambuc     flags |= CLS_ROOT;
7263*0a6a1f1dSLionel Sambuc   InstanceSize = "sizeof(struct _class_t)";
7264*0a6a1f1dSLionel Sambuc   InstanceStart = InstanceSize;
7265*0a6a1f1dSLionel Sambuc   Write__class_ro_t_initializer(Context, Result, flags,
7266*0a6a1f1dSLionel Sambuc                                 InstanceStart, InstanceSize,
7267*0a6a1f1dSLionel Sambuc                                 ClassMethods,
7268*0a6a1f1dSLionel Sambuc                                 nullptr,
7269*0a6a1f1dSLionel Sambuc                                 nullptr,
7270*0a6a1f1dSLionel Sambuc                                 nullptr,
7271*0a6a1f1dSLionel Sambuc                                 "_OBJC_METACLASS_RO_$_",
7272*0a6a1f1dSLionel Sambuc                                 CDecl->getNameAsString());
7273*0a6a1f1dSLionel Sambuc 
7274*0a6a1f1dSLionel Sambuc   // Data for initializing _class_ro_t meta-data
7275*0a6a1f1dSLionel Sambuc   flags = CLS;
7276*0a6a1f1dSLionel Sambuc   if (classIsHidden)
7277*0a6a1f1dSLionel Sambuc     flags |= OBJC2_CLS_HIDDEN;
7278*0a6a1f1dSLionel Sambuc 
7279*0a6a1f1dSLionel Sambuc   if (hasObjCExceptionAttribute(*Context, CDecl))
7280*0a6a1f1dSLionel Sambuc     flags |= CLS_EXCEPTION;
7281*0a6a1f1dSLionel Sambuc 
7282*0a6a1f1dSLionel Sambuc   if (!CDecl->getSuperClass())
7283*0a6a1f1dSLionel Sambuc     // class is root
7284*0a6a1f1dSLionel Sambuc     flags |= CLS_ROOT;
7285*0a6a1f1dSLionel Sambuc 
7286*0a6a1f1dSLionel Sambuc   InstanceSize.clear();
7287*0a6a1f1dSLionel Sambuc   InstanceStart.clear();
7288*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedStructs.count(CDecl)) {
7289*0a6a1f1dSLionel Sambuc     InstanceSize = "0";
7290*0a6a1f1dSLionel Sambuc     InstanceStart = "0";
7291*0a6a1f1dSLionel Sambuc   }
7292*0a6a1f1dSLionel Sambuc   else {
7293*0a6a1f1dSLionel Sambuc     InstanceSize = "sizeof(struct ";
7294*0a6a1f1dSLionel Sambuc     InstanceSize += CDecl->getNameAsString();
7295*0a6a1f1dSLionel Sambuc     InstanceSize += "_IMPL)";
7296*0a6a1f1dSLionel Sambuc 
7297*0a6a1f1dSLionel Sambuc     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7298*0a6a1f1dSLionel Sambuc     if (IVD) {
7299*0a6a1f1dSLionel Sambuc       RewriteIvarOffsetComputation(IVD, InstanceStart);
7300*0a6a1f1dSLionel Sambuc     }
7301*0a6a1f1dSLionel Sambuc     else
7302*0a6a1f1dSLionel Sambuc       InstanceStart = InstanceSize;
7303*0a6a1f1dSLionel Sambuc   }
7304*0a6a1f1dSLionel Sambuc   Write__class_ro_t_initializer(Context, Result, flags,
7305*0a6a1f1dSLionel Sambuc                                 InstanceStart, InstanceSize,
7306*0a6a1f1dSLionel Sambuc                                 InstanceMethods,
7307*0a6a1f1dSLionel Sambuc                                 RefedProtocols,
7308*0a6a1f1dSLionel Sambuc                                 IVars,
7309*0a6a1f1dSLionel Sambuc                                 ClassProperties,
7310*0a6a1f1dSLionel Sambuc                                 "_OBJC_CLASS_RO_$_",
7311*0a6a1f1dSLionel Sambuc                                 CDecl->getNameAsString());
7312*0a6a1f1dSLionel Sambuc 
7313*0a6a1f1dSLionel Sambuc   Write_class_t(Context, Result,
7314*0a6a1f1dSLionel Sambuc                 "OBJC_METACLASS_$_",
7315*0a6a1f1dSLionel Sambuc                 CDecl, /*metaclass*/true);
7316*0a6a1f1dSLionel Sambuc 
7317*0a6a1f1dSLionel Sambuc   Write_class_t(Context, Result,
7318*0a6a1f1dSLionel Sambuc                 "OBJC_CLASS_$_",
7319*0a6a1f1dSLionel Sambuc                 CDecl, /*metaclass*/false);
7320*0a6a1f1dSLionel Sambuc 
7321*0a6a1f1dSLionel Sambuc   if (ImplementationIsNonLazy(IDecl))
7322*0a6a1f1dSLionel Sambuc     DefinedNonLazyClasses.push_back(CDecl);
7323*0a6a1f1dSLionel Sambuc 
7324*0a6a1f1dSLionel Sambuc }
7325*0a6a1f1dSLionel Sambuc 
RewriteClassSetupInitHook(std::string & Result)7326*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7327*0a6a1f1dSLionel Sambuc   int ClsDefCount = ClassImplementation.size();
7328*0a6a1f1dSLionel Sambuc   if (!ClsDefCount)
7329*0a6a1f1dSLionel Sambuc     return;
7330*0a6a1f1dSLionel Sambuc   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7331*0a6a1f1dSLionel Sambuc   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7332*0a6a1f1dSLionel Sambuc   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7333*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++) {
7334*0a6a1f1dSLionel Sambuc     ObjCImplementationDecl *IDecl = ClassImplementation[i];
7335*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7336*0a6a1f1dSLionel Sambuc     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7337*0a6a1f1dSLionel Sambuc     Result  += CDecl->getName(); Result += ",\n";
7338*0a6a1f1dSLionel Sambuc   }
7339*0a6a1f1dSLionel Sambuc   Result += "};\n";
7340*0a6a1f1dSLionel Sambuc }
7341*0a6a1f1dSLionel Sambuc 
RewriteMetaDataIntoBuffer(std::string & Result)7342*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7343*0a6a1f1dSLionel Sambuc   int ClsDefCount = ClassImplementation.size();
7344*0a6a1f1dSLionel Sambuc   int CatDefCount = CategoryImplementation.size();
7345*0a6a1f1dSLionel Sambuc 
7346*0a6a1f1dSLionel Sambuc   // For each implemented class, write out all its meta data.
7347*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++)
7348*0a6a1f1dSLionel Sambuc     RewriteObjCClassMetaData(ClassImplementation[i], Result);
7349*0a6a1f1dSLionel Sambuc 
7350*0a6a1f1dSLionel Sambuc   RewriteClassSetupInitHook(Result);
7351*0a6a1f1dSLionel Sambuc 
7352*0a6a1f1dSLionel Sambuc   // For each implemented category, write out all its meta data.
7353*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++)
7354*0a6a1f1dSLionel Sambuc     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7355*0a6a1f1dSLionel Sambuc 
7356*0a6a1f1dSLionel Sambuc   RewriteCategorySetupInitHook(Result);
7357*0a6a1f1dSLionel Sambuc 
7358*0a6a1f1dSLionel Sambuc   if (ClsDefCount > 0) {
7359*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
7360*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7361*0a6a1f1dSLionel Sambuc     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7362*0a6a1f1dSLionel Sambuc     Result += llvm::utostr(ClsDefCount); Result += "]";
7363*0a6a1f1dSLionel Sambuc     Result +=
7364*0a6a1f1dSLionel Sambuc       " __attribute__((used, section (\"__DATA, __objc_classlist,"
7365*0a6a1f1dSLionel Sambuc       "regular,no_dead_strip\")))= {\n";
7366*0a6a1f1dSLionel Sambuc     for (int i = 0; i < ClsDefCount; i++) {
7367*0a6a1f1dSLionel Sambuc       Result += "\t&OBJC_CLASS_$_";
7368*0a6a1f1dSLionel Sambuc       Result += ClassImplementation[i]->getNameAsString();
7369*0a6a1f1dSLionel Sambuc       Result += ",\n";
7370*0a6a1f1dSLionel Sambuc     }
7371*0a6a1f1dSLionel Sambuc     Result += "};\n";
7372*0a6a1f1dSLionel Sambuc 
7373*0a6a1f1dSLionel Sambuc     if (!DefinedNonLazyClasses.empty()) {
7374*0a6a1f1dSLionel Sambuc       if (LangOpts.MicrosoftExt)
7375*0a6a1f1dSLionel Sambuc         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7376*0a6a1f1dSLionel Sambuc       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7377*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7378*0a6a1f1dSLionel Sambuc         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7379*0a6a1f1dSLionel Sambuc         Result += ",\n";
7380*0a6a1f1dSLionel Sambuc       }
7381*0a6a1f1dSLionel Sambuc       Result += "};\n";
7382*0a6a1f1dSLionel Sambuc     }
7383*0a6a1f1dSLionel Sambuc   }
7384*0a6a1f1dSLionel Sambuc 
7385*0a6a1f1dSLionel Sambuc   if (CatDefCount > 0) {
7386*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
7387*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7388*0a6a1f1dSLionel Sambuc     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7389*0a6a1f1dSLionel Sambuc     Result += llvm::utostr(CatDefCount); Result += "]";
7390*0a6a1f1dSLionel Sambuc     Result +=
7391*0a6a1f1dSLionel Sambuc     " __attribute__((used, section (\"__DATA, __objc_catlist,"
7392*0a6a1f1dSLionel Sambuc     "regular,no_dead_strip\")))= {\n";
7393*0a6a1f1dSLionel Sambuc     for (int i = 0; i < CatDefCount; i++) {
7394*0a6a1f1dSLionel Sambuc       Result += "\t&_OBJC_$_CATEGORY_";
7395*0a6a1f1dSLionel Sambuc       Result +=
7396*0a6a1f1dSLionel Sambuc         CategoryImplementation[i]->getClassInterface()->getNameAsString();
7397*0a6a1f1dSLionel Sambuc       Result += "_$_";
7398*0a6a1f1dSLionel Sambuc       Result += CategoryImplementation[i]->getNameAsString();
7399*0a6a1f1dSLionel Sambuc       Result += ",\n";
7400*0a6a1f1dSLionel Sambuc     }
7401*0a6a1f1dSLionel Sambuc     Result += "};\n";
7402*0a6a1f1dSLionel Sambuc   }
7403*0a6a1f1dSLionel Sambuc 
7404*0a6a1f1dSLionel Sambuc   if (!DefinedNonLazyCategories.empty()) {
7405*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
7406*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7407*0a6a1f1dSLionel Sambuc     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7408*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7409*0a6a1f1dSLionel Sambuc       Result += "\t&_OBJC_$_CATEGORY_";
7410*0a6a1f1dSLionel Sambuc       Result +=
7411*0a6a1f1dSLionel Sambuc         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7412*0a6a1f1dSLionel Sambuc       Result += "_$_";
7413*0a6a1f1dSLionel Sambuc       Result += DefinedNonLazyCategories[i]->getNameAsString();
7414*0a6a1f1dSLionel Sambuc       Result += ",\n";
7415*0a6a1f1dSLionel Sambuc     }
7416*0a6a1f1dSLionel Sambuc     Result += "};\n";
7417*0a6a1f1dSLionel Sambuc   }
7418*0a6a1f1dSLionel Sambuc }
7419*0a6a1f1dSLionel Sambuc 
WriteImageInfo(std::string & Result)7420*0a6a1f1dSLionel Sambuc void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7421*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
7422*0a6a1f1dSLionel Sambuc     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7423*0a6a1f1dSLionel Sambuc 
7424*0a6a1f1dSLionel Sambuc   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7425*0a6a1f1dSLionel Sambuc   // version 0, ObjCABI is 2
7426*0a6a1f1dSLionel Sambuc   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7427*0a6a1f1dSLionel Sambuc }
7428*0a6a1f1dSLionel Sambuc 
7429*0a6a1f1dSLionel Sambuc /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7430*0a6a1f1dSLionel Sambuc /// implementation.
RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl * IDecl,std::string & Result)7431*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7432*0a6a1f1dSLionel Sambuc                                               std::string &Result) {
7433*0a6a1f1dSLionel Sambuc   WriteModernMetadataDeclarations(Context, Result);
7434*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7435*0a6a1f1dSLionel Sambuc   // Find category declaration for this implementation.
7436*0a6a1f1dSLionel Sambuc   ObjCCategoryDecl *CDecl
7437*0a6a1f1dSLionel Sambuc     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7438*0a6a1f1dSLionel Sambuc 
7439*0a6a1f1dSLionel Sambuc   std::string FullCategoryName = ClassDecl->getNameAsString();
7440*0a6a1f1dSLionel Sambuc   FullCategoryName += "_$_";
7441*0a6a1f1dSLionel Sambuc   FullCategoryName += CDecl->getNameAsString();
7442*0a6a1f1dSLionel Sambuc 
7443*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's instance methods if needed
7444*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7445*0a6a1f1dSLionel Sambuc 
7446*0a6a1f1dSLionel Sambuc   // If any of our property implementations have associated getters or
7447*0a6a1f1dSLionel Sambuc   // setters, produce metadata for them as well.
7448*0a6a1f1dSLionel Sambuc   for (const auto *Prop : IDecl->property_impls()) {
7449*0a6a1f1dSLionel Sambuc     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7450*0a6a1f1dSLionel Sambuc       continue;
7451*0a6a1f1dSLionel Sambuc     if (!Prop->getPropertyIvarDecl())
7452*0a6a1f1dSLionel Sambuc       continue;
7453*0a6a1f1dSLionel Sambuc     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7454*0a6a1f1dSLionel Sambuc     if (!PD)
7455*0a6a1f1dSLionel Sambuc       continue;
7456*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7457*0a6a1f1dSLionel Sambuc       InstanceMethods.push_back(Getter);
7458*0a6a1f1dSLionel Sambuc     if (PD->isReadOnly())
7459*0a6a1f1dSLionel Sambuc       continue;
7460*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7461*0a6a1f1dSLionel Sambuc       InstanceMethods.push_back(Setter);
7462*0a6a1f1dSLionel Sambuc   }
7463*0a6a1f1dSLionel Sambuc 
7464*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7465*0a6a1f1dSLionel Sambuc                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7466*0a6a1f1dSLionel Sambuc                                   FullCategoryName, true);
7467*0a6a1f1dSLionel Sambuc 
7468*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7469*0a6a1f1dSLionel Sambuc 
7470*0a6a1f1dSLionel Sambuc   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7471*0a6a1f1dSLionel Sambuc                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
7472*0a6a1f1dSLionel Sambuc                                   FullCategoryName, true);
7473*0a6a1f1dSLionel Sambuc 
7474*0a6a1f1dSLionel Sambuc   // Protocols referenced in class declaration?
7475*0a6a1f1dSLionel Sambuc   // Protocol's super protocol list
7476*0a6a1f1dSLionel Sambuc   SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7477*0a6a1f1dSLionel Sambuc   for (auto *I : CDecl->protocols())
7478*0a6a1f1dSLionel Sambuc     // Must write out all protocol definitions in current qualifier list,
7479*0a6a1f1dSLionel Sambuc     // and in their nested qualifiers before writing out current definition.
7480*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(I, Result);
7481*0a6a1f1dSLionel Sambuc 
7482*0a6a1f1dSLionel Sambuc   Write_protocol_list_initializer(Context, Result,
7483*0a6a1f1dSLionel Sambuc                                   RefedProtocols,
7484*0a6a1f1dSLionel Sambuc                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
7485*0a6a1f1dSLionel Sambuc                                   FullCategoryName);
7486*0a6a1f1dSLionel Sambuc 
7487*0a6a1f1dSLionel Sambuc   // Protocol's property metadata.
7488*0a6a1f1dSLionel Sambuc   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
7489*0a6a1f1dSLionel Sambuc   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7490*0a6a1f1dSLionel Sambuc                                 /* Container */IDecl,
7491*0a6a1f1dSLionel Sambuc                                 "_OBJC_$_PROP_LIST_",
7492*0a6a1f1dSLionel Sambuc                                 FullCategoryName);
7493*0a6a1f1dSLionel Sambuc 
7494*0a6a1f1dSLionel Sambuc   Write_category_t(*this, Context, Result,
7495*0a6a1f1dSLionel Sambuc                    CDecl,
7496*0a6a1f1dSLionel Sambuc                    ClassDecl,
7497*0a6a1f1dSLionel Sambuc                    InstanceMethods,
7498*0a6a1f1dSLionel Sambuc                    ClassMethods,
7499*0a6a1f1dSLionel Sambuc                    RefedProtocols,
7500*0a6a1f1dSLionel Sambuc                    ClassProperties);
7501*0a6a1f1dSLionel Sambuc 
7502*0a6a1f1dSLionel Sambuc   // Determine if this category is also "non-lazy".
7503*0a6a1f1dSLionel Sambuc   if (ImplementationIsNonLazy(IDecl))
7504*0a6a1f1dSLionel Sambuc     DefinedNonLazyCategories.push_back(CDecl);
7505*0a6a1f1dSLionel Sambuc 
7506*0a6a1f1dSLionel Sambuc }
7507*0a6a1f1dSLionel Sambuc 
RewriteCategorySetupInitHook(std::string & Result)7508*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7509*0a6a1f1dSLionel Sambuc   int CatDefCount = CategoryImplementation.size();
7510*0a6a1f1dSLionel Sambuc   if (!CatDefCount)
7511*0a6a1f1dSLionel Sambuc     return;
7512*0a6a1f1dSLionel Sambuc   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7513*0a6a1f1dSLionel Sambuc   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7514*0a6a1f1dSLionel Sambuc   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7515*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++) {
7516*0a6a1f1dSLionel Sambuc     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7517*0a6a1f1dSLionel Sambuc     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7518*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7519*0a6a1f1dSLionel Sambuc     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7520*0a6a1f1dSLionel Sambuc     Result += ClassDecl->getName();
7521*0a6a1f1dSLionel Sambuc     Result += "_$_";
7522*0a6a1f1dSLionel Sambuc     Result += CatDecl->getName();
7523*0a6a1f1dSLionel Sambuc     Result += ",\n";
7524*0a6a1f1dSLionel Sambuc   }
7525*0a6a1f1dSLionel Sambuc   Result += "};\n";
7526*0a6a1f1dSLionel Sambuc }
7527*0a6a1f1dSLionel Sambuc 
7528*0a6a1f1dSLionel Sambuc // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7529*0a6a1f1dSLionel Sambuc /// class methods.
7530*0a6a1f1dSLionel Sambuc template<typename MethodIterator>
RewriteObjCMethodsMetaData(MethodIterator MethodBegin,MethodIterator MethodEnd,bool IsInstanceMethod,StringRef prefix,StringRef ClassName,std::string & Result)7531*0a6a1f1dSLionel Sambuc void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7532*0a6a1f1dSLionel Sambuc                                              MethodIterator MethodEnd,
7533*0a6a1f1dSLionel Sambuc                                              bool IsInstanceMethod,
7534*0a6a1f1dSLionel Sambuc                                              StringRef prefix,
7535*0a6a1f1dSLionel Sambuc                                              StringRef ClassName,
7536*0a6a1f1dSLionel Sambuc                                              std::string &Result) {
7537*0a6a1f1dSLionel Sambuc   if (MethodBegin == MethodEnd) return;
7538*0a6a1f1dSLionel Sambuc 
7539*0a6a1f1dSLionel Sambuc   if (!objc_impl_method) {
7540*0a6a1f1dSLionel Sambuc     /* struct _objc_method {
7541*0a6a1f1dSLionel Sambuc      SEL _cmd;
7542*0a6a1f1dSLionel Sambuc      char *method_types;
7543*0a6a1f1dSLionel Sambuc      void *_imp;
7544*0a6a1f1dSLionel Sambuc      }
7545*0a6a1f1dSLionel Sambuc      */
7546*0a6a1f1dSLionel Sambuc     Result += "\nstruct _objc_method {\n";
7547*0a6a1f1dSLionel Sambuc     Result += "\tSEL _cmd;\n";
7548*0a6a1f1dSLionel Sambuc     Result += "\tchar *method_types;\n";
7549*0a6a1f1dSLionel Sambuc     Result += "\tvoid *_imp;\n";
7550*0a6a1f1dSLionel Sambuc     Result += "};\n";
7551*0a6a1f1dSLionel Sambuc 
7552*0a6a1f1dSLionel Sambuc     objc_impl_method = true;
7553*0a6a1f1dSLionel Sambuc   }
7554*0a6a1f1dSLionel Sambuc 
7555*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's methods if needed
7556*0a6a1f1dSLionel Sambuc 
7557*0a6a1f1dSLionel Sambuc   /* struct  {
7558*0a6a1f1dSLionel Sambuc    struct _objc_method_list *next_method;
7559*0a6a1f1dSLionel Sambuc    int method_count;
7560*0a6a1f1dSLionel Sambuc    struct _objc_method method_list[];
7561*0a6a1f1dSLionel Sambuc    }
7562*0a6a1f1dSLionel Sambuc    */
7563*0a6a1f1dSLionel Sambuc   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7564*0a6a1f1dSLionel Sambuc   Result += "\n";
7565*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
7566*0a6a1f1dSLionel Sambuc     if (IsInstanceMethod)
7567*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".inst_meth$B\")) ";
7568*0a6a1f1dSLionel Sambuc     else
7569*0a6a1f1dSLionel Sambuc       Result += "__declspec(allocate(\".cls_meth$B\")) ";
7570*0a6a1f1dSLionel Sambuc   }
7571*0a6a1f1dSLionel Sambuc   Result += "static struct {\n";
7572*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_method_list *next_method;\n";
7573*0a6a1f1dSLionel Sambuc   Result += "\tint method_count;\n";
7574*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_method method_list[";
7575*0a6a1f1dSLionel Sambuc   Result += utostr(NumMethods);
7576*0a6a1f1dSLionel Sambuc   Result += "];\n} _OBJC_";
7577*0a6a1f1dSLionel Sambuc   Result += prefix;
7578*0a6a1f1dSLionel Sambuc   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7579*0a6a1f1dSLionel Sambuc   Result += "_METHODS_";
7580*0a6a1f1dSLionel Sambuc   Result += ClassName;
7581*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __";
7582*0a6a1f1dSLionel Sambuc   Result += IsInstanceMethod ? "inst" : "cls";
7583*0a6a1f1dSLionel Sambuc   Result += "_meth\")))= ";
7584*0a6a1f1dSLionel Sambuc   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7585*0a6a1f1dSLionel Sambuc 
7586*0a6a1f1dSLionel Sambuc   Result += "\t,{{(SEL)\"";
7587*0a6a1f1dSLionel Sambuc   Result += (*MethodBegin)->getSelector().getAsString().c_str();
7588*0a6a1f1dSLionel Sambuc   std::string MethodTypeString;
7589*0a6a1f1dSLionel Sambuc   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7590*0a6a1f1dSLionel Sambuc   Result += "\", \"";
7591*0a6a1f1dSLionel Sambuc   Result += MethodTypeString;
7592*0a6a1f1dSLionel Sambuc   Result += "\", (void *)";
7593*0a6a1f1dSLionel Sambuc   Result += MethodInternalNames[*MethodBegin];
7594*0a6a1f1dSLionel Sambuc   Result += "}\n";
7595*0a6a1f1dSLionel Sambuc   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7596*0a6a1f1dSLionel Sambuc     Result += "\t  ,{(SEL)\"";
7597*0a6a1f1dSLionel Sambuc     Result += (*MethodBegin)->getSelector().getAsString().c_str();
7598*0a6a1f1dSLionel Sambuc     std::string MethodTypeString;
7599*0a6a1f1dSLionel Sambuc     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7600*0a6a1f1dSLionel Sambuc     Result += "\", \"";
7601*0a6a1f1dSLionel Sambuc     Result += MethodTypeString;
7602*0a6a1f1dSLionel Sambuc     Result += "\", (void *)";
7603*0a6a1f1dSLionel Sambuc     Result += MethodInternalNames[*MethodBegin];
7604*0a6a1f1dSLionel Sambuc     Result += "}\n";
7605*0a6a1f1dSLionel Sambuc   }
7606*0a6a1f1dSLionel Sambuc   Result += "\t }\n};\n";
7607*0a6a1f1dSLionel Sambuc }
7608*0a6a1f1dSLionel Sambuc 
RewriteObjCIvarRefExpr(ObjCIvarRefExpr * IV)7609*0a6a1f1dSLionel Sambuc Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7610*0a6a1f1dSLionel Sambuc   SourceRange OldRange = IV->getSourceRange();
7611*0a6a1f1dSLionel Sambuc   Expr *BaseExpr = IV->getBase();
7612*0a6a1f1dSLionel Sambuc 
7613*0a6a1f1dSLionel Sambuc   // Rewrite the base, but without actually doing replaces.
7614*0a6a1f1dSLionel Sambuc   {
7615*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
7616*0a6a1f1dSLionel Sambuc     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7617*0a6a1f1dSLionel Sambuc     IV->setBase(BaseExpr);
7618*0a6a1f1dSLionel Sambuc   }
7619*0a6a1f1dSLionel Sambuc 
7620*0a6a1f1dSLionel Sambuc   ObjCIvarDecl *D = IV->getDecl();
7621*0a6a1f1dSLionel Sambuc 
7622*0a6a1f1dSLionel Sambuc   Expr *Replacement = IV;
7623*0a6a1f1dSLionel Sambuc 
7624*0a6a1f1dSLionel Sambuc     if (BaseExpr->getType()->isObjCObjectPointerType()) {
7625*0a6a1f1dSLionel Sambuc       const ObjCInterfaceType *iFaceDecl =
7626*0a6a1f1dSLionel Sambuc         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7627*0a6a1f1dSLionel Sambuc       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7628*0a6a1f1dSLionel Sambuc       // lookup which class implements the instance variable.
7629*0a6a1f1dSLionel Sambuc       ObjCInterfaceDecl *clsDeclared = nullptr;
7630*0a6a1f1dSLionel Sambuc       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7631*0a6a1f1dSLionel Sambuc                                                    clsDeclared);
7632*0a6a1f1dSLionel Sambuc       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7633*0a6a1f1dSLionel Sambuc 
7634*0a6a1f1dSLionel Sambuc       // Build name of symbol holding ivar offset.
7635*0a6a1f1dSLionel Sambuc       std::string IvarOffsetName;
7636*0a6a1f1dSLionel Sambuc       if (D->isBitField())
7637*0a6a1f1dSLionel Sambuc         ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7638*0a6a1f1dSLionel Sambuc       else
7639*0a6a1f1dSLionel Sambuc         WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7640*0a6a1f1dSLionel Sambuc 
7641*0a6a1f1dSLionel Sambuc       ReferencedIvars[clsDeclared].insert(D);
7642*0a6a1f1dSLionel Sambuc 
7643*0a6a1f1dSLionel Sambuc       // cast offset to "char *".
7644*0a6a1f1dSLionel Sambuc       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7645*0a6a1f1dSLionel Sambuc                                                     Context->getPointerType(Context->CharTy),
7646*0a6a1f1dSLionel Sambuc                                                     CK_BitCast,
7647*0a6a1f1dSLionel Sambuc                                                     BaseExpr);
7648*0a6a1f1dSLionel Sambuc       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7649*0a6a1f1dSLionel Sambuc                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
7650*0a6a1f1dSLionel Sambuc                                        Context->UnsignedLongTy, nullptr,
7651*0a6a1f1dSLionel Sambuc                                        SC_Extern);
7652*0a6a1f1dSLionel Sambuc       DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7653*0a6a1f1dSLionel Sambuc                                                    Context->UnsignedLongTy, VK_LValue,
7654*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
7655*0a6a1f1dSLionel Sambuc       BinaryOperator *addExpr =
7656*0a6a1f1dSLionel Sambuc         new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7657*0a6a1f1dSLionel Sambuc                                      Context->getPointerType(Context->CharTy),
7658*0a6a1f1dSLionel Sambuc                                      VK_RValue, OK_Ordinary, SourceLocation(), false);
7659*0a6a1f1dSLionel Sambuc       // Don't forget the parens to enforce the proper binding.
7660*0a6a1f1dSLionel Sambuc       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7661*0a6a1f1dSLionel Sambuc                                               SourceLocation(),
7662*0a6a1f1dSLionel Sambuc                                               addExpr);
7663*0a6a1f1dSLionel Sambuc       QualType IvarT = D->getType();
7664*0a6a1f1dSLionel Sambuc       if (D->isBitField())
7665*0a6a1f1dSLionel Sambuc         IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7666*0a6a1f1dSLionel Sambuc 
7667*0a6a1f1dSLionel Sambuc       if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7668*0a6a1f1dSLionel Sambuc         RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7669*0a6a1f1dSLionel Sambuc         RD = RD->getDefinition();
7670*0a6a1f1dSLionel Sambuc         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7671*0a6a1f1dSLionel Sambuc           // decltype(((Foo_IMPL*)0)->bar) *
7672*0a6a1f1dSLionel Sambuc           ObjCContainerDecl *CDecl =
7673*0a6a1f1dSLionel Sambuc             dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7674*0a6a1f1dSLionel Sambuc           // ivar in class extensions requires special treatment.
7675*0a6a1f1dSLionel Sambuc           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7676*0a6a1f1dSLionel Sambuc             CDecl = CatDecl->getClassInterface();
7677*0a6a1f1dSLionel Sambuc           std::string RecName = CDecl->getName();
7678*0a6a1f1dSLionel Sambuc           RecName += "_IMPL";
7679*0a6a1f1dSLionel Sambuc           RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7680*0a6a1f1dSLionel Sambuc                                               SourceLocation(), SourceLocation(),
7681*0a6a1f1dSLionel Sambuc                                               &Context->Idents.get(RecName.c_str()));
7682*0a6a1f1dSLionel Sambuc           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7683*0a6a1f1dSLionel Sambuc           unsigned UnsignedIntSize =
7684*0a6a1f1dSLionel Sambuc             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7685*0a6a1f1dSLionel Sambuc           Expr *Zero = IntegerLiteral::Create(*Context,
7686*0a6a1f1dSLionel Sambuc                                               llvm::APInt(UnsignedIntSize, 0),
7687*0a6a1f1dSLionel Sambuc                                               Context->UnsignedIntTy, SourceLocation());
7688*0a6a1f1dSLionel Sambuc           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7689*0a6a1f1dSLionel Sambuc           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7690*0a6a1f1dSLionel Sambuc                                                   Zero);
7691*0a6a1f1dSLionel Sambuc           FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7692*0a6a1f1dSLionel Sambuc                                             SourceLocation(),
7693*0a6a1f1dSLionel Sambuc                                             &Context->Idents.get(D->getNameAsString()),
7694*0a6a1f1dSLionel Sambuc                                             IvarT, nullptr,
7695*0a6a1f1dSLionel Sambuc                                             /*BitWidth=*/nullptr,
7696*0a6a1f1dSLionel Sambuc                                             /*Mutable=*/true, ICIS_NoInit);
7697*0a6a1f1dSLionel Sambuc           MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7698*0a6a1f1dSLionel Sambuc                                                     FD->getType(), VK_LValue,
7699*0a6a1f1dSLionel Sambuc                                                     OK_Ordinary);
7700*0a6a1f1dSLionel Sambuc           IvarT = Context->getDecltypeType(ME, ME->getType());
7701*0a6a1f1dSLionel Sambuc         }
7702*0a6a1f1dSLionel Sambuc       }
7703*0a6a1f1dSLionel Sambuc       convertObjCTypeToCStyleType(IvarT);
7704*0a6a1f1dSLionel Sambuc       QualType castT = Context->getPointerType(IvarT);
7705*0a6a1f1dSLionel Sambuc 
7706*0a6a1f1dSLionel Sambuc       castExpr = NoTypeInfoCStyleCastExpr(Context,
7707*0a6a1f1dSLionel Sambuc                                           castT,
7708*0a6a1f1dSLionel Sambuc                                           CK_BitCast,
7709*0a6a1f1dSLionel Sambuc                                           PE);
7710*0a6a1f1dSLionel Sambuc 
7711*0a6a1f1dSLionel Sambuc 
7712*0a6a1f1dSLionel Sambuc       Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7713*0a6a1f1dSLionel Sambuc                                               VK_LValue, OK_Ordinary,
7714*0a6a1f1dSLionel Sambuc                                               SourceLocation());
7715*0a6a1f1dSLionel Sambuc       PE = new (Context) ParenExpr(OldRange.getBegin(),
7716*0a6a1f1dSLionel Sambuc                                    OldRange.getEnd(),
7717*0a6a1f1dSLionel Sambuc                                    Exp);
7718*0a6a1f1dSLionel Sambuc 
7719*0a6a1f1dSLionel Sambuc       if (D->isBitField()) {
7720*0a6a1f1dSLionel Sambuc         FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7721*0a6a1f1dSLionel Sambuc                                           SourceLocation(),
7722*0a6a1f1dSLionel Sambuc                                           &Context->Idents.get(D->getNameAsString()),
7723*0a6a1f1dSLionel Sambuc                                           D->getType(), nullptr,
7724*0a6a1f1dSLionel Sambuc                                           /*BitWidth=*/D->getBitWidth(),
7725*0a6a1f1dSLionel Sambuc                                           /*Mutable=*/true, ICIS_NoInit);
7726*0a6a1f1dSLionel Sambuc         MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7727*0a6a1f1dSLionel Sambuc                                                   FD->getType(), VK_LValue,
7728*0a6a1f1dSLionel Sambuc                                                   OK_Ordinary);
7729*0a6a1f1dSLionel Sambuc         Replacement = ME;
7730*0a6a1f1dSLionel Sambuc 
7731*0a6a1f1dSLionel Sambuc       }
7732*0a6a1f1dSLionel Sambuc       else
7733*0a6a1f1dSLionel Sambuc         Replacement = PE;
7734*0a6a1f1dSLionel Sambuc     }
7735*0a6a1f1dSLionel Sambuc 
7736*0a6a1f1dSLionel Sambuc     ReplaceStmtWithRange(IV, Replacement, OldRange);
7737*0a6a1f1dSLionel Sambuc     return Replacement;
7738*0a6a1f1dSLionel Sambuc }
7739*0a6a1f1dSLionel Sambuc 
7740*0a6a1f1dSLionel Sambuc #endif
7741