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/Lex/Lexer.h"
24*0a6a1f1dSLionel Sambuc #include "clang/Rewrite/Core/Rewriter.h"
25*0a6a1f1dSLionel Sambuc #include "llvm/ADT/DenseSet.h"
26*0a6a1f1dSLionel Sambuc #include "llvm/ADT/SmallPtrSet.h"
27*0a6a1f1dSLionel Sambuc #include "llvm/ADT/StringExtras.h"
28*0a6a1f1dSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
29*0a6a1f1dSLionel Sambuc #include "llvm/Support/raw_ostream.h"
30*0a6a1f1dSLionel Sambuc #include <memory>
31*0a6a1f1dSLionel Sambuc 
32*0a6a1f1dSLionel Sambuc #ifdef CLANG_ENABLE_OBJC_REWRITER
33*0a6a1f1dSLionel Sambuc 
34*0a6a1f1dSLionel Sambuc using namespace clang;
35*0a6a1f1dSLionel Sambuc using llvm::utostr;
36*0a6a1f1dSLionel Sambuc 
37*0a6a1f1dSLionel Sambuc namespace {
38*0a6a1f1dSLionel Sambuc   class RewriteObjC : public ASTConsumer {
39*0a6a1f1dSLionel Sambuc   protected:
40*0a6a1f1dSLionel Sambuc 
41*0a6a1f1dSLionel Sambuc     enum {
42*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
43*0a6a1f1dSLionel Sambuc                                         block, ... */
44*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
45*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
46*0a6a1f1dSLionel Sambuc                                         __block variable */
47*0a6a1f1dSLionel Sambuc       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
48*0a6a1f1dSLionel Sambuc                                         helpers */
49*0a6a1f1dSLionel Sambuc       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
50*0a6a1f1dSLionel Sambuc                                         support routines */
51*0a6a1f1dSLionel Sambuc       BLOCK_BYREF_CURRENT_MAX = 256
52*0a6a1f1dSLionel Sambuc     };
53*0a6a1f1dSLionel Sambuc 
54*0a6a1f1dSLionel Sambuc     enum {
55*0a6a1f1dSLionel Sambuc       BLOCK_NEEDS_FREE =        (1 << 24),
56*0a6a1f1dSLionel Sambuc       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
57*0a6a1f1dSLionel Sambuc       BLOCK_HAS_CXX_OBJ =       (1 << 26),
58*0a6a1f1dSLionel Sambuc       BLOCK_IS_GC =             (1 << 27),
59*0a6a1f1dSLionel Sambuc       BLOCK_IS_GLOBAL =         (1 << 28),
60*0a6a1f1dSLionel Sambuc       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
61*0a6a1f1dSLionel Sambuc     };
62*0a6a1f1dSLionel Sambuc     static const int OBJC_ABI_VERSION = 7;
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     unsigned RewriteFailedDiag;
81*0a6a1f1dSLionel Sambuc     // ObjC string constant support.
82*0a6a1f1dSLionel Sambuc     unsigned NumObjCStringLiterals;
83*0a6a1f1dSLionel Sambuc     VarDecl *ConstantStringClassReference;
84*0a6a1f1dSLionel Sambuc     RecordDecl *NSStringRecord;
85*0a6a1f1dSLionel Sambuc 
86*0a6a1f1dSLionel Sambuc     // ObjC foreach break/continue generation support.
87*0a6a1f1dSLionel Sambuc     int BcLabelCount;
88*0a6a1f1dSLionel Sambuc 
89*0a6a1f1dSLionel Sambuc     unsigned TryFinallyContainsReturnDiag;
90*0a6a1f1dSLionel Sambuc     // Needed for super.
91*0a6a1f1dSLionel Sambuc     ObjCMethodDecl *CurMethodDef;
92*0a6a1f1dSLionel Sambuc     RecordDecl *SuperStructDecl;
93*0a6a1f1dSLionel Sambuc     RecordDecl *ConstantStringDecl;
94*0a6a1f1dSLionel Sambuc 
95*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendFunctionDecl;
96*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendSuperFunctionDecl;
97*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendStretFunctionDecl;
98*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendSuperStretFunctionDecl;
99*0a6a1f1dSLionel Sambuc     FunctionDecl *MsgSendFpretFunctionDecl;
100*0a6a1f1dSLionel Sambuc     FunctionDecl *GetClassFunctionDecl;
101*0a6a1f1dSLionel Sambuc     FunctionDecl *GetMetaClassFunctionDecl;
102*0a6a1f1dSLionel Sambuc     FunctionDecl *GetSuperClassFunctionDecl;
103*0a6a1f1dSLionel Sambuc     FunctionDecl *SelGetUidFunctionDecl;
104*0a6a1f1dSLionel Sambuc     FunctionDecl *CFStringFunctionDecl;
105*0a6a1f1dSLionel Sambuc     FunctionDecl *SuperConstructorFunctionDecl;
106*0a6a1f1dSLionel Sambuc     FunctionDecl *CurFunctionDef;
107*0a6a1f1dSLionel Sambuc     FunctionDecl *CurFunctionDeclToDeclareForBlock;
108*0a6a1f1dSLionel Sambuc 
109*0a6a1f1dSLionel Sambuc     /* Misc. containers needed for meta-data rewrite. */
110*0a6a1f1dSLionel Sambuc     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111*0a6a1f1dSLionel Sambuc     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
114*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115*0a6a1f1dSLionel Sambuc     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
116*0a6a1f1dSLionel Sambuc     SmallVector<Stmt *, 32> Stmts;
117*0a6a1f1dSLionel Sambuc     SmallVector<int, 8> ObjCBcLabelNo;
118*0a6a1f1dSLionel Sambuc     // Remember all the @protocol(<expr>) expressions.
119*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
120*0a6a1f1dSLionel Sambuc 
121*0a6a1f1dSLionel Sambuc     llvm::DenseSet<uint64_t> CopyDestroyCache;
122*0a6a1f1dSLionel Sambuc 
123*0a6a1f1dSLionel Sambuc     // Block expressions.
124*0a6a1f1dSLionel Sambuc     SmallVector<BlockExpr *, 32> Blocks;
125*0a6a1f1dSLionel Sambuc     SmallVector<int, 32> InnerDeclRefsCount;
126*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
127*0a6a1f1dSLionel Sambuc 
128*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
129*0a6a1f1dSLionel Sambuc 
130*0a6a1f1dSLionel Sambuc     // Block related declarations.
131*0a6a1f1dSLionel Sambuc     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133*0a6a1f1dSLionel Sambuc     SmallVector<ValueDecl *, 8> BlockByRefDecls;
134*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135*0a6a1f1dSLionel Sambuc     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138*0a6a1f1dSLionel Sambuc 
139*0a6a1f1dSLionel Sambuc     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140*0a6a1f1dSLionel Sambuc 
141*0a6a1f1dSLionel Sambuc     // This maps an original source AST to it's rewritten form. This allows
142*0a6a1f1dSLionel Sambuc     // us to avoid rewriting the same node twice (which is very uncommon).
143*0a6a1f1dSLionel Sambuc     // This is needed to support some of the exotic property rewriting.
144*0a6a1f1dSLionel Sambuc     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
145*0a6a1f1dSLionel Sambuc 
146*0a6a1f1dSLionel Sambuc     // Needed for header files being rewritten
147*0a6a1f1dSLionel Sambuc     bool IsHeader;
148*0a6a1f1dSLionel Sambuc     bool SilenceRewriteMacroWarning;
149*0a6a1f1dSLionel Sambuc     bool objc_impl_method;
150*0a6a1f1dSLionel Sambuc 
151*0a6a1f1dSLionel Sambuc     bool DisableReplaceStmt;
152*0a6a1f1dSLionel Sambuc     class DisableReplaceStmtScope {
153*0a6a1f1dSLionel Sambuc       RewriteObjC &R;
154*0a6a1f1dSLionel Sambuc       bool SavedValue;
155*0a6a1f1dSLionel Sambuc 
156*0a6a1f1dSLionel Sambuc     public:
DisableReplaceStmtScope(RewriteObjC & R)157*0a6a1f1dSLionel Sambuc       DisableReplaceStmtScope(RewriteObjC &R)
158*0a6a1f1dSLionel Sambuc         : R(R), SavedValue(R.DisableReplaceStmt) {
159*0a6a1f1dSLionel Sambuc         R.DisableReplaceStmt = true;
160*0a6a1f1dSLionel Sambuc       }
~DisableReplaceStmtScope()161*0a6a1f1dSLionel Sambuc       ~DisableReplaceStmtScope() {
162*0a6a1f1dSLionel Sambuc         R.DisableReplaceStmt = SavedValue;
163*0a6a1f1dSLionel Sambuc       }
164*0a6a1f1dSLionel Sambuc     };
165*0a6a1f1dSLionel Sambuc     void InitializeCommon(ASTContext &context);
166*0a6a1f1dSLionel Sambuc 
167*0a6a1f1dSLionel Sambuc   public:
168*0a6a1f1dSLionel Sambuc 
169*0a6a1f1dSLionel Sambuc     // Top Level Driver code.
HandleTopLevelDecl(DeclGroupRef D)170*0a6a1f1dSLionel Sambuc     bool HandleTopLevelDecl(DeclGroupRef D) override {
171*0a6a1f1dSLionel Sambuc       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172*0a6a1f1dSLionel Sambuc         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173*0a6a1f1dSLionel Sambuc           if (!Class->isThisDeclarationADefinition()) {
174*0a6a1f1dSLionel Sambuc             RewriteForwardClassDecl(D);
175*0a6a1f1dSLionel Sambuc             break;
176*0a6a1f1dSLionel Sambuc           }
177*0a6a1f1dSLionel Sambuc         }
178*0a6a1f1dSLionel Sambuc 
179*0a6a1f1dSLionel Sambuc         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180*0a6a1f1dSLionel Sambuc           if (!Proto->isThisDeclarationADefinition()) {
181*0a6a1f1dSLionel Sambuc             RewriteForwardProtocolDecl(D);
182*0a6a1f1dSLionel Sambuc             break;
183*0a6a1f1dSLionel Sambuc           }
184*0a6a1f1dSLionel Sambuc         }
185*0a6a1f1dSLionel Sambuc 
186*0a6a1f1dSLionel Sambuc         HandleTopLevelSingleDecl(*I);
187*0a6a1f1dSLionel Sambuc       }
188*0a6a1f1dSLionel Sambuc       return true;
189*0a6a1f1dSLionel Sambuc     }
190*0a6a1f1dSLionel Sambuc     void HandleTopLevelSingleDecl(Decl *D);
191*0a6a1f1dSLionel Sambuc     void HandleDeclInMainFile(Decl *D);
192*0a6a1f1dSLionel Sambuc     RewriteObjC(std::string inFile, raw_ostream *OS,
193*0a6a1f1dSLionel Sambuc                 DiagnosticsEngine &D, const LangOptions &LOpts,
194*0a6a1f1dSLionel Sambuc                 bool silenceMacroWarn);
195*0a6a1f1dSLionel Sambuc 
~RewriteObjC()196*0a6a1f1dSLionel Sambuc     ~RewriteObjC() {}
197*0a6a1f1dSLionel Sambuc 
198*0a6a1f1dSLionel Sambuc     void HandleTranslationUnit(ASTContext &C) override;
199*0a6a1f1dSLionel Sambuc 
ReplaceStmt(Stmt * Old,Stmt * New)200*0a6a1f1dSLionel Sambuc     void ReplaceStmt(Stmt *Old, Stmt *New) {
201*0a6a1f1dSLionel Sambuc       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
202*0a6a1f1dSLionel Sambuc     }
203*0a6a1f1dSLionel Sambuc 
ReplaceStmtWithRange(Stmt * Old,Stmt * New,SourceRange SrcRange)204*0a6a1f1dSLionel Sambuc     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
205*0a6a1f1dSLionel Sambuc       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
206*0a6a1f1dSLionel Sambuc 
207*0a6a1f1dSLionel Sambuc       Stmt *ReplacingStmt = ReplacedNodes[Old];
208*0a6a1f1dSLionel Sambuc       if (ReplacingStmt)
209*0a6a1f1dSLionel Sambuc         return; // We can't rewrite the same node twice.
210*0a6a1f1dSLionel Sambuc 
211*0a6a1f1dSLionel Sambuc       if (DisableReplaceStmt)
212*0a6a1f1dSLionel Sambuc         return;
213*0a6a1f1dSLionel Sambuc 
214*0a6a1f1dSLionel Sambuc       // Measure the old text.
215*0a6a1f1dSLionel Sambuc       int Size = Rewrite.getRangeSize(SrcRange);
216*0a6a1f1dSLionel Sambuc       if (Size == -1) {
217*0a6a1f1dSLionel Sambuc         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
218*0a6a1f1dSLionel Sambuc                      << Old->getSourceRange();
219*0a6a1f1dSLionel Sambuc         return;
220*0a6a1f1dSLionel Sambuc       }
221*0a6a1f1dSLionel Sambuc       // Get the new text.
222*0a6a1f1dSLionel Sambuc       std::string SStr;
223*0a6a1f1dSLionel Sambuc       llvm::raw_string_ostream S(SStr);
224*0a6a1f1dSLionel Sambuc       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
225*0a6a1f1dSLionel Sambuc       const std::string &Str = S.str();
226*0a6a1f1dSLionel Sambuc 
227*0a6a1f1dSLionel Sambuc       // If replacement succeeded or warning disabled return with no warning.
228*0a6a1f1dSLionel Sambuc       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
229*0a6a1f1dSLionel Sambuc         ReplacedNodes[Old] = New;
230*0a6a1f1dSLionel Sambuc         return;
231*0a6a1f1dSLionel Sambuc       }
232*0a6a1f1dSLionel Sambuc       if (SilenceRewriteMacroWarning)
233*0a6a1f1dSLionel Sambuc         return;
234*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
235*0a6a1f1dSLionel Sambuc                    << Old->getSourceRange();
236*0a6a1f1dSLionel Sambuc     }
237*0a6a1f1dSLionel Sambuc 
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter=true)238*0a6a1f1dSLionel Sambuc     void InsertText(SourceLocation Loc, StringRef Str,
239*0a6a1f1dSLionel Sambuc                     bool InsertAfter = true) {
240*0a6a1f1dSLionel Sambuc       // If insertion succeeded or warning disabled return with no warning.
241*0a6a1f1dSLionel Sambuc       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
242*0a6a1f1dSLionel Sambuc           SilenceRewriteMacroWarning)
243*0a6a1f1dSLionel Sambuc         return;
244*0a6a1f1dSLionel Sambuc 
245*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
246*0a6a1f1dSLionel Sambuc     }
247*0a6a1f1dSLionel Sambuc 
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef Str)248*0a6a1f1dSLionel Sambuc     void ReplaceText(SourceLocation Start, unsigned OrigLength,
249*0a6a1f1dSLionel Sambuc                      StringRef Str) {
250*0a6a1f1dSLionel Sambuc       // If removal succeeded or warning disabled return with no warning.
251*0a6a1f1dSLionel Sambuc       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
252*0a6a1f1dSLionel Sambuc           SilenceRewriteMacroWarning)
253*0a6a1f1dSLionel Sambuc         return;
254*0a6a1f1dSLionel Sambuc 
255*0a6a1f1dSLionel Sambuc       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
256*0a6a1f1dSLionel Sambuc     }
257*0a6a1f1dSLionel Sambuc 
258*0a6a1f1dSLionel Sambuc     // Syntactic Rewriting.
259*0a6a1f1dSLionel Sambuc     void RewriteRecordBody(RecordDecl *RD);
260*0a6a1f1dSLionel Sambuc     void RewriteInclude();
261*0a6a1f1dSLionel Sambuc     void RewriteForwardClassDecl(DeclGroupRef D);
262*0a6a1f1dSLionel Sambuc     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
263*0a6a1f1dSLionel Sambuc     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
264*0a6a1f1dSLionel Sambuc                                      const std::string &typedefString);
265*0a6a1f1dSLionel Sambuc     void RewriteImplementations();
266*0a6a1f1dSLionel Sambuc     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
267*0a6a1f1dSLionel Sambuc                                  ObjCImplementationDecl *IMD,
268*0a6a1f1dSLionel Sambuc                                  ObjCCategoryImplDecl *CID);
269*0a6a1f1dSLionel Sambuc     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
270*0a6a1f1dSLionel Sambuc     void RewriteImplementationDecl(Decl *Dcl);
271*0a6a1f1dSLionel Sambuc     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
272*0a6a1f1dSLionel Sambuc                                ObjCMethodDecl *MDecl, std::string &ResultStr);
273*0a6a1f1dSLionel Sambuc     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
274*0a6a1f1dSLionel Sambuc                                const FunctionType *&FPRetType);
275*0a6a1f1dSLionel Sambuc     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
276*0a6a1f1dSLionel Sambuc                             ValueDecl *VD, bool def=false);
277*0a6a1f1dSLionel Sambuc     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
278*0a6a1f1dSLionel Sambuc     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
279*0a6a1f1dSLionel Sambuc     void RewriteForwardProtocolDecl(DeclGroupRef D);
280*0a6a1f1dSLionel Sambuc     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
281*0a6a1f1dSLionel Sambuc     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
282*0a6a1f1dSLionel Sambuc     void RewriteProperty(ObjCPropertyDecl *prop);
283*0a6a1f1dSLionel Sambuc     void RewriteFunctionDecl(FunctionDecl *FD);
284*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerType(std::string& Str, QualType Type);
285*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
286*0a6a1f1dSLionel Sambuc     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
287*0a6a1f1dSLionel Sambuc     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
288*0a6a1f1dSLionel Sambuc     void RewriteTypeOfDecl(VarDecl *VD);
289*0a6a1f1dSLionel Sambuc     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
290*0a6a1f1dSLionel Sambuc 
291*0a6a1f1dSLionel Sambuc     // Expression Rewriting.
292*0a6a1f1dSLionel Sambuc     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
293*0a6a1f1dSLionel Sambuc     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
294*0a6a1f1dSLionel Sambuc     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
295*0a6a1f1dSLionel Sambuc     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
296*0a6a1f1dSLionel Sambuc     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
297*0a6a1f1dSLionel Sambuc     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
298*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
299*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
300*0a6a1f1dSLionel Sambuc     void RewriteTryReturnStmts(Stmt *S);
301*0a6a1f1dSLionel Sambuc     void RewriteSyncReturnStmts(Stmt *S, std::string buf);
302*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
303*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
304*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
305*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
306*0a6a1f1dSLionel Sambuc                                        SourceLocation OrigEnd);
307*0a6a1f1dSLionel Sambuc     Stmt *RewriteBreakStmt(BreakStmt *S);
308*0a6a1f1dSLionel Sambuc     Stmt *RewriteContinueStmt(ContinueStmt *S);
309*0a6a1f1dSLionel Sambuc     void RewriteCastExpr(CStyleCastExpr *CE);
310*0a6a1f1dSLionel Sambuc 
311*0a6a1f1dSLionel Sambuc     // Block rewriting.
312*0a6a1f1dSLionel Sambuc     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
313*0a6a1f1dSLionel Sambuc 
314*0a6a1f1dSLionel Sambuc     // Block specific rewrite rules.
315*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerDecl(NamedDecl *VD);
316*0a6a1f1dSLionel Sambuc     void RewriteByRefVar(VarDecl *VD);
317*0a6a1f1dSLionel Sambuc     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
318*0a6a1f1dSLionel Sambuc     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
319*0a6a1f1dSLionel Sambuc     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
320*0a6a1f1dSLionel Sambuc 
321*0a6a1f1dSLionel Sambuc     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
322*0a6a1f1dSLionel Sambuc                                       std::string &Result);
323*0a6a1f1dSLionel Sambuc 
324*0a6a1f1dSLionel Sambuc     void Initialize(ASTContext &context) override = 0;
325*0a6a1f1dSLionel Sambuc 
326*0a6a1f1dSLionel Sambuc     // Metadata Rewriting.
327*0a6a1f1dSLionel Sambuc     virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
328*0a6a1f1dSLionel Sambuc     virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
329*0a6a1f1dSLionel Sambuc                                                  StringRef prefix,
330*0a6a1f1dSLionel Sambuc                                                  StringRef ClassName,
331*0a6a1f1dSLionel Sambuc                                                  std::string &Result) = 0;
332*0a6a1f1dSLionel Sambuc     virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
333*0a6a1f1dSLionel Sambuc                                              std::string &Result) = 0;
334*0a6a1f1dSLionel Sambuc     virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335*0a6a1f1dSLionel Sambuc                                      StringRef prefix,
336*0a6a1f1dSLionel Sambuc                                      StringRef ClassName,
337*0a6a1f1dSLionel Sambuc                                      std::string &Result) = 0;
338*0a6a1f1dSLionel Sambuc     virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
339*0a6a1f1dSLionel Sambuc                                           std::string &Result) = 0;
340*0a6a1f1dSLionel Sambuc 
341*0a6a1f1dSLionel Sambuc     // Rewriting ivar access
342*0a6a1f1dSLionel Sambuc     virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
343*0a6a1f1dSLionel Sambuc     virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
344*0a6a1f1dSLionel Sambuc                                          std::string &Result) = 0;
345*0a6a1f1dSLionel Sambuc 
346*0a6a1f1dSLionel Sambuc     // Misc. AST transformation routines. Sometimes they end up calling
347*0a6a1f1dSLionel Sambuc     // rewriting routines on the new ASTs.
348*0a6a1f1dSLionel Sambuc     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
349*0a6a1f1dSLionel Sambuc                                            Expr **args, unsigned nargs,
350*0a6a1f1dSLionel Sambuc                                            SourceLocation StartLoc=SourceLocation(),
351*0a6a1f1dSLionel Sambuc                                            SourceLocation EndLoc=SourceLocation());
352*0a6a1f1dSLionel Sambuc     CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
353*0a6a1f1dSLionel Sambuc                                         QualType msgSendType,
354*0a6a1f1dSLionel Sambuc                                         QualType returnType,
355*0a6a1f1dSLionel Sambuc                                         SmallVectorImpl<QualType> &ArgTypes,
356*0a6a1f1dSLionel Sambuc                                         SmallVectorImpl<Expr*> &MsgExprs,
357*0a6a1f1dSLionel Sambuc                                         ObjCMethodDecl *Method);
358*0a6a1f1dSLionel Sambuc     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
359*0a6a1f1dSLionel Sambuc                            SourceLocation StartLoc=SourceLocation(),
360*0a6a1f1dSLionel Sambuc                            SourceLocation EndLoc=SourceLocation());
361*0a6a1f1dSLionel Sambuc 
362*0a6a1f1dSLionel Sambuc     void SynthCountByEnumWithState(std::string &buf);
363*0a6a1f1dSLionel Sambuc     void SynthMsgSendFunctionDecl();
364*0a6a1f1dSLionel Sambuc     void SynthMsgSendSuperFunctionDecl();
365*0a6a1f1dSLionel Sambuc     void SynthMsgSendStretFunctionDecl();
366*0a6a1f1dSLionel Sambuc     void SynthMsgSendFpretFunctionDecl();
367*0a6a1f1dSLionel Sambuc     void SynthMsgSendSuperStretFunctionDecl();
368*0a6a1f1dSLionel Sambuc     void SynthGetClassFunctionDecl();
369*0a6a1f1dSLionel Sambuc     void SynthGetMetaClassFunctionDecl();
370*0a6a1f1dSLionel Sambuc     void SynthGetSuperClassFunctionDecl();
371*0a6a1f1dSLionel Sambuc     void SynthSelGetUidFunctionDecl();
372*0a6a1f1dSLionel Sambuc     void SynthSuperConstructorFunctionDecl();
373*0a6a1f1dSLionel Sambuc 
374*0a6a1f1dSLionel Sambuc     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
375*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
376*0a6a1f1dSLionel Sambuc                                       StringRef funcName, std::string Tag);
377*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
378*0a6a1f1dSLionel Sambuc                                       StringRef funcName, std::string Tag);
379*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockImpl(BlockExpr *CE,
380*0a6a1f1dSLionel Sambuc                                     std::string Tag, std::string Desc);
381*0a6a1f1dSLionel Sambuc     std::string SynthesizeBlockDescriptor(std::string DescTag,
382*0a6a1f1dSLionel Sambuc                                           std::string ImplTag,
383*0a6a1f1dSLionel Sambuc                                           int i, StringRef funcName,
384*0a6a1f1dSLionel Sambuc                                           unsigned hasCopy);
385*0a6a1f1dSLionel Sambuc     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
386*0a6a1f1dSLionel Sambuc     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
387*0a6a1f1dSLionel Sambuc                                  StringRef FunName);
388*0a6a1f1dSLionel Sambuc     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
389*0a6a1f1dSLionel Sambuc     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
390*0a6a1f1dSLionel Sambuc             const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
391*0a6a1f1dSLionel Sambuc 
392*0a6a1f1dSLionel Sambuc     // Misc. helper routines.
393*0a6a1f1dSLionel Sambuc     QualType getProtocolType();
394*0a6a1f1dSLionel Sambuc     void WarnAboutReturnGotoStmts(Stmt *S);
395*0a6a1f1dSLionel Sambuc     void HasReturnStmts(Stmt *S, bool &hasReturns);
396*0a6a1f1dSLionel Sambuc     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
397*0a6a1f1dSLionel Sambuc     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
398*0a6a1f1dSLionel Sambuc     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
399*0a6a1f1dSLionel Sambuc 
400*0a6a1f1dSLionel Sambuc     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
401*0a6a1f1dSLionel Sambuc     void CollectBlockDeclRefInfo(BlockExpr *Exp);
402*0a6a1f1dSLionel Sambuc     void GetBlockDeclRefExprs(Stmt *S);
403*0a6a1f1dSLionel Sambuc     void GetInnerBlockDeclRefExprs(Stmt *S,
404*0a6a1f1dSLionel Sambuc                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
405*0a6a1f1dSLionel Sambuc                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
406*0a6a1f1dSLionel Sambuc 
407*0a6a1f1dSLionel Sambuc     // We avoid calling Type::isBlockPointerType(), since it operates on the
408*0a6a1f1dSLionel Sambuc     // canonical type. We only care if the top-level type is a closure pointer.
isTopLevelBlockPointerType(QualType T)409*0a6a1f1dSLionel Sambuc     bool isTopLevelBlockPointerType(QualType T) {
410*0a6a1f1dSLionel Sambuc       return isa<BlockPointerType>(T);
411*0a6a1f1dSLionel Sambuc     }
412*0a6a1f1dSLionel Sambuc 
413*0a6a1f1dSLionel Sambuc     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
414*0a6a1f1dSLionel Sambuc     /// to a function pointer type and upon success, returns true; false
415*0a6a1f1dSLionel Sambuc     /// otherwise.
convertBlockPointerToFunctionPointer(QualType & T)416*0a6a1f1dSLionel Sambuc     bool convertBlockPointerToFunctionPointer(QualType &T) {
417*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(T)) {
418*0a6a1f1dSLionel Sambuc         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
419*0a6a1f1dSLionel Sambuc         T = Context->getPointerType(BPT->getPointeeType());
420*0a6a1f1dSLionel Sambuc         return true;
421*0a6a1f1dSLionel Sambuc       }
422*0a6a1f1dSLionel Sambuc       return false;
423*0a6a1f1dSLionel Sambuc     }
424*0a6a1f1dSLionel Sambuc 
425*0a6a1f1dSLionel Sambuc     bool needToScanForQualifiers(QualType T);
426*0a6a1f1dSLionel Sambuc     QualType getSuperStructType();
427*0a6a1f1dSLionel Sambuc     QualType getConstantStringStructType();
428*0a6a1f1dSLionel Sambuc     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
429*0a6a1f1dSLionel Sambuc     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
430*0a6a1f1dSLionel Sambuc 
convertToUnqualifiedObjCType(QualType & T)431*0a6a1f1dSLionel Sambuc     void convertToUnqualifiedObjCType(QualType &T) {
432*0a6a1f1dSLionel Sambuc       if (T->isObjCQualifiedIdType())
433*0a6a1f1dSLionel Sambuc         T = Context->getObjCIdType();
434*0a6a1f1dSLionel Sambuc       else if (T->isObjCQualifiedClassType())
435*0a6a1f1dSLionel Sambuc         T = Context->getObjCClassType();
436*0a6a1f1dSLionel Sambuc       else if (T->isObjCObjectPointerType() &&
437*0a6a1f1dSLionel Sambuc                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
438*0a6a1f1dSLionel Sambuc         if (const ObjCObjectPointerType * OBJPT =
439*0a6a1f1dSLionel Sambuc               T->getAsObjCInterfacePointerType()) {
440*0a6a1f1dSLionel Sambuc           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
441*0a6a1f1dSLionel Sambuc           T = QualType(IFaceT, 0);
442*0a6a1f1dSLionel Sambuc           T = Context->getPointerType(T);
443*0a6a1f1dSLionel Sambuc         }
444*0a6a1f1dSLionel Sambuc      }
445*0a6a1f1dSLionel Sambuc     }
446*0a6a1f1dSLionel Sambuc 
447*0a6a1f1dSLionel Sambuc     // FIXME: This predicate seems like it would be useful to add to ASTContext.
isObjCType(QualType T)448*0a6a1f1dSLionel Sambuc     bool isObjCType(QualType T) {
449*0a6a1f1dSLionel Sambuc       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
450*0a6a1f1dSLionel Sambuc         return false;
451*0a6a1f1dSLionel Sambuc 
452*0a6a1f1dSLionel Sambuc       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
453*0a6a1f1dSLionel Sambuc 
454*0a6a1f1dSLionel Sambuc       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
455*0a6a1f1dSLionel Sambuc           OCT == Context->getCanonicalType(Context->getObjCClassType()))
456*0a6a1f1dSLionel Sambuc         return true;
457*0a6a1f1dSLionel Sambuc 
458*0a6a1f1dSLionel Sambuc       if (const PointerType *PT = OCT->getAs<PointerType>()) {
459*0a6a1f1dSLionel Sambuc         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
460*0a6a1f1dSLionel Sambuc             PT->getPointeeType()->isObjCQualifiedIdType())
461*0a6a1f1dSLionel Sambuc           return true;
462*0a6a1f1dSLionel Sambuc       }
463*0a6a1f1dSLionel Sambuc       return false;
464*0a6a1f1dSLionel Sambuc     }
465*0a6a1f1dSLionel Sambuc     bool PointerTypeTakesAnyBlockArguments(QualType QT);
466*0a6a1f1dSLionel Sambuc     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
467*0a6a1f1dSLionel Sambuc     void GetExtentOfArgList(const char *Name, const char *&LParen,
468*0a6a1f1dSLionel Sambuc                             const char *&RParen);
469*0a6a1f1dSLionel Sambuc 
QuoteDoublequotes(std::string & From,std::string & To)470*0a6a1f1dSLionel Sambuc     void QuoteDoublequotes(std::string &From, std::string &To) {
471*0a6a1f1dSLionel Sambuc       for (unsigned i = 0; i < From.length(); i++) {
472*0a6a1f1dSLionel Sambuc         if (From[i] == '"')
473*0a6a1f1dSLionel Sambuc           To += "\\\"";
474*0a6a1f1dSLionel Sambuc         else
475*0a6a1f1dSLionel Sambuc           To += From[i];
476*0a6a1f1dSLionel Sambuc       }
477*0a6a1f1dSLionel Sambuc     }
478*0a6a1f1dSLionel Sambuc 
getSimpleFunctionType(QualType result,ArrayRef<QualType> args,bool variadic=false)479*0a6a1f1dSLionel Sambuc     QualType getSimpleFunctionType(QualType result,
480*0a6a1f1dSLionel Sambuc                                    ArrayRef<QualType> args,
481*0a6a1f1dSLionel Sambuc                                    bool variadic = false) {
482*0a6a1f1dSLionel Sambuc       if (result == Context->getObjCInstanceType())
483*0a6a1f1dSLionel Sambuc         result =  Context->getObjCIdType();
484*0a6a1f1dSLionel Sambuc       FunctionProtoType::ExtProtoInfo fpi;
485*0a6a1f1dSLionel Sambuc       fpi.Variadic = variadic;
486*0a6a1f1dSLionel Sambuc       return Context->getFunctionType(result, args, fpi);
487*0a6a1f1dSLionel Sambuc     }
488*0a6a1f1dSLionel Sambuc 
489*0a6a1f1dSLionel Sambuc     // Helper function: create a CStyleCastExpr with trivial type source info.
NoTypeInfoCStyleCastExpr(ASTContext * Ctx,QualType Ty,CastKind Kind,Expr * E)490*0a6a1f1dSLionel Sambuc     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
491*0a6a1f1dSLionel Sambuc                                              CastKind Kind, Expr *E) {
492*0a6a1f1dSLionel Sambuc       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
493*0a6a1f1dSLionel Sambuc       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
494*0a6a1f1dSLionel Sambuc                                     TInfo, SourceLocation(), SourceLocation());
495*0a6a1f1dSLionel Sambuc     }
496*0a6a1f1dSLionel Sambuc 
getStringLiteral(StringRef Str)497*0a6a1f1dSLionel Sambuc     StringLiteral *getStringLiteral(StringRef Str) {
498*0a6a1f1dSLionel Sambuc       QualType StrType = Context->getConstantArrayType(
499*0a6a1f1dSLionel Sambuc           Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
500*0a6a1f1dSLionel Sambuc           0);
501*0a6a1f1dSLionel Sambuc       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
502*0a6a1f1dSLionel Sambuc                                    /*Pascal=*/false, StrType, SourceLocation());
503*0a6a1f1dSLionel Sambuc     }
504*0a6a1f1dSLionel Sambuc   };
505*0a6a1f1dSLionel Sambuc 
506*0a6a1f1dSLionel Sambuc   class RewriteObjCFragileABI : public RewriteObjC {
507*0a6a1f1dSLionel Sambuc   public:
508*0a6a1f1dSLionel Sambuc 
RewriteObjCFragileABI(std::string inFile,raw_ostream * OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)509*0a6a1f1dSLionel Sambuc     RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510*0a6a1f1dSLionel Sambuc                 DiagnosticsEngine &D, const LangOptions &LOpts,
511*0a6a1f1dSLionel Sambuc                 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512*0a6a1f1dSLionel Sambuc                                                      D, LOpts,
513*0a6a1f1dSLionel Sambuc                                                      silenceMacroWarn) {}
514*0a6a1f1dSLionel Sambuc 
~RewriteObjCFragileABI()515*0a6a1f1dSLionel Sambuc     ~RewriteObjCFragileABI() {}
516*0a6a1f1dSLionel Sambuc     void Initialize(ASTContext &context) override;
517*0a6a1f1dSLionel Sambuc 
518*0a6a1f1dSLionel Sambuc     // Rewriting metadata
519*0a6a1f1dSLionel Sambuc     template<typename MethodIterator>
520*0a6a1f1dSLionel Sambuc     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521*0a6a1f1dSLionel Sambuc                                     MethodIterator MethodEnd,
522*0a6a1f1dSLionel Sambuc                                     bool IsInstanceMethod,
523*0a6a1f1dSLionel Sambuc                                     StringRef prefix,
524*0a6a1f1dSLionel Sambuc                                     StringRef ClassName,
525*0a6a1f1dSLionel Sambuc                                     std::string &Result);
526*0a6a1f1dSLionel Sambuc     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527*0a6a1f1dSLionel Sambuc                                      StringRef prefix, StringRef ClassName,
528*0a6a1f1dSLionel Sambuc                                      std::string &Result) override;
529*0a6a1f1dSLionel Sambuc     void RewriteObjCProtocolListMetaData(
530*0a6a1f1dSLionel Sambuc           const ObjCList<ObjCProtocolDecl> &Prots,
531*0a6a1f1dSLionel Sambuc           StringRef prefix, StringRef ClassName, std::string &Result) override;
532*0a6a1f1dSLionel Sambuc     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533*0a6a1f1dSLionel Sambuc                                   std::string &Result) override;
534*0a6a1f1dSLionel Sambuc     void RewriteMetaDataIntoBuffer(std::string &Result) override;
535*0a6a1f1dSLionel Sambuc     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536*0a6a1f1dSLionel Sambuc                                      std::string &Result) override;
537*0a6a1f1dSLionel Sambuc 
538*0a6a1f1dSLionel Sambuc     // Rewriting ivar
539*0a6a1f1dSLionel Sambuc     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540*0a6a1f1dSLionel Sambuc                                       std::string &Result) override;
541*0a6a1f1dSLionel Sambuc     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
542*0a6a1f1dSLionel Sambuc   };
543*0a6a1f1dSLionel Sambuc }
544*0a6a1f1dSLionel Sambuc 
RewriteBlocksInFunctionProtoType(QualType funcType,NamedDecl * D)545*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546*0a6a1f1dSLionel Sambuc                                                    NamedDecl *D) {
547*0a6a1f1dSLionel Sambuc   if (const FunctionProtoType *fproto
548*0a6a1f1dSLionel Sambuc       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
549*0a6a1f1dSLionel Sambuc     for (const auto &I : fproto->param_types())
550*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(I)) {
551*0a6a1f1dSLionel Sambuc         // All the args are checked/rewritten. Don't call twice!
552*0a6a1f1dSLionel Sambuc         RewriteBlockPointerDecl(D);
553*0a6a1f1dSLionel Sambuc         break;
554*0a6a1f1dSLionel Sambuc       }
555*0a6a1f1dSLionel Sambuc   }
556*0a6a1f1dSLionel Sambuc }
557*0a6a1f1dSLionel Sambuc 
CheckFunctionPointerDecl(QualType funcType,NamedDecl * ND)558*0a6a1f1dSLionel Sambuc void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
559*0a6a1f1dSLionel Sambuc   const PointerType *PT = funcType->getAs<PointerType>();
560*0a6a1f1dSLionel Sambuc   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
561*0a6a1f1dSLionel Sambuc     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
562*0a6a1f1dSLionel Sambuc }
563*0a6a1f1dSLionel Sambuc 
IsHeaderFile(const std::string & Filename)564*0a6a1f1dSLionel Sambuc static bool IsHeaderFile(const std::string &Filename) {
565*0a6a1f1dSLionel Sambuc   std::string::size_type DotPos = Filename.rfind('.');
566*0a6a1f1dSLionel Sambuc 
567*0a6a1f1dSLionel Sambuc   if (DotPos == std::string::npos) {
568*0a6a1f1dSLionel Sambuc     // no file extension
569*0a6a1f1dSLionel Sambuc     return false;
570*0a6a1f1dSLionel Sambuc   }
571*0a6a1f1dSLionel Sambuc 
572*0a6a1f1dSLionel Sambuc   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
573*0a6a1f1dSLionel Sambuc   // C header: .h
574*0a6a1f1dSLionel Sambuc   // C++ header: .hh or .H;
575*0a6a1f1dSLionel Sambuc   return Ext == "h" || Ext == "hh" || Ext == "H";
576*0a6a1f1dSLionel Sambuc }
577*0a6a1f1dSLionel Sambuc 
RewriteObjC(std::string inFile,raw_ostream * OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)578*0a6a1f1dSLionel Sambuc RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
579*0a6a1f1dSLionel Sambuc                          DiagnosticsEngine &D, const LangOptions &LOpts,
580*0a6a1f1dSLionel Sambuc                          bool silenceMacroWarn)
581*0a6a1f1dSLionel Sambuc       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
582*0a6a1f1dSLionel Sambuc         SilenceRewriteMacroWarning(silenceMacroWarn) {
583*0a6a1f1dSLionel Sambuc   IsHeader = IsHeaderFile(inFile);
584*0a6a1f1dSLionel Sambuc   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
585*0a6a1f1dSLionel Sambuc                "rewriting sub-expression within a macro (may not be correct)");
586*0a6a1f1dSLionel Sambuc   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587*0a6a1f1dSLionel Sambuc                DiagnosticsEngine::Warning,
588*0a6a1f1dSLionel Sambuc                "rewriter doesn't support user-specified control flow semantics "
589*0a6a1f1dSLionel Sambuc                "for @try/@finally (code may not execute properly)");
590*0a6a1f1dSLionel Sambuc }
591*0a6a1f1dSLionel Sambuc 
592*0a6a1f1dSLionel Sambuc std::unique_ptr<ASTConsumer>
CreateObjCRewriter(const std::string & InFile,raw_ostream * OS,DiagnosticsEngine & Diags,const LangOptions & LOpts,bool SilenceRewriteMacroWarning)593*0a6a1f1dSLionel Sambuc clang::CreateObjCRewriter(const std::string &InFile, raw_ostream *OS,
594*0a6a1f1dSLionel Sambuc                           DiagnosticsEngine &Diags, const LangOptions &LOpts,
595*0a6a1f1dSLionel Sambuc                           bool SilenceRewriteMacroWarning) {
596*0a6a1f1dSLionel Sambuc   return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
597*0a6a1f1dSLionel Sambuc                                                   SilenceRewriteMacroWarning);
598*0a6a1f1dSLionel Sambuc }
599*0a6a1f1dSLionel Sambuc 
InitializeCommon(ASTContext & context)600*0a6a1f1dSLionel Sambuc void RewriteObjC::InitializeCommon(ASTContext &context) {
601*0a6a1f1dSLionel Sambuc   Context = &context;
602*0a6a1f1dSLionel Sambuc   SM = &Context->getSourceManager();
603*0a6a1f1dSLionel Sambuc   TUDecl = Context->getTranslationUnitDecl();
604*0a6a1f1dSLionel Sambuc   MsgSendFunctionDecl = nullptr;
605*0a6a1f1dSLionel Sambuc   MsgSendSuperFunctionDecl = nullptr;
606*0a6a1f1dSLionel Sambuc   MsgSendStretFunctionDecl = nullptr;
607*0a6a1f1dSLionel Sambuc   MsgSendSuperStretFunctionDecl = nullptr;
608*0a6a1f1dSLionel Sambuc   MsgSendFpretFunctionDecl = nullptr;
609*0a6a1f1dSLionel Sambuc   GetClassFunctionDecl = nullptr;
610*0a6a1f1dSLionel Sambuc   GetMetaClassFunctionDecl = nullptr;
611*0a6a1f1dSLionel Sambuc   GetSuperClassFunctionDecl = nullptr;
612*0a6a1f1dSLionel Sambuc   SelGetUidFunctionDecl = nullptr;
613*0a6a1f1dSLionel Sambuc   CFStringFunctionDecl = nullptr;
614*0a6a1f1dSLionel Sambuc   ConstantStringClassReference = nullptr;
615*0a6a1f1dSLionel Sambuc   NSStringRecord = nullptr;
616*0a6a1f1dSLionel Sambuc   CurMethodDef = nullptr;
617*0a6a1f1dSLionel Sambuc   CurFunctionDef = nullptr;
618*0a6a1f1dSLionel Sambuc   CurFunctionDeclToDeclareForBlock = nullptr;
619*0a6a1f1dSLionel Sambuc   GlobalVarDecl = nullptr;
620*0a6a1f1dSLionel Sambuc   SuperStructDecl = nullptr;
621*0a6a1f1dSLionel Sambuc   ProtocolTypeDecl = nullptr;
622*0a6a1f1dSLionel Sambuc   ConstantStringDecl = nullptr;
623*0a6a1f1dSLionel Sambuc   BcLabelCount = 0;
624*0a6a1f1dSLionel Sambuc   SuperConstructorFunctionDecl = nullptr;
625*0a6a1f1dSLionel Sambuc   NumObjCStringLiterals = 0;
626*0a6a1f1dSLionel Sambuc   PropParentMap = nullptr;
627*0a6a1f1dSLionel Sambuc   CurrentBody = nullptr;
628*0a6a1f1dSLionel Sambuc   DisableReplaceStmt = false;
629*0a6a1f1dSLionel Sambuc   objc_impl_method = false;
630*0a6a1f1dSLionel Sambuc 
631*0a6a1f1dSLionel Sambuc   // Get the ID and start/end of the main file.
632*0a6a1f1dSLionel Sambuc   MainFileID = SM->getMainFileID();
633*0a6a1f1dSLionel Sambuc   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634*0a6a1f1dSLionel Sambuc   MainFileStart = MainBuf->getBufferStart();
635*0a6a1f1dSLionel Sambuc   MainFileEnd = MainBuf->getBufferEnd();
636*0a6a1f1dSLionel Sambuc 
637*0a6a1f1dSLionel Sambuc   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
638*0a6a1f1dSLionel Sambuc }
639*0a6a1f1dSLionel Sambuc 
640*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
641*0a6a1f1dSLionel Sambuc // Top Level Driver Code
642*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
643*0a6a1f1dSLionel Sambuc 
HandleTopLevelSingleDecl(Decl * D)644*0a6a1f1dSLionel Sambuc void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
645*0a6a1f1dSLionel Sambuc   if (Diags.hasErrorOccurred())
646*0a6a1f1dSLionel Sambuc     return;
647*0a6a1f1dSLionel Sambuc 
648*0a6a1f1dSLionel Sambuc   // Two cases: either the decl could be in the main file, or it could be in a
649*0a6a1f1dSLionel Sambuc   // #included file.  If the former, rewrite it now.  If the later, check to see
650*0a6a1f1dSLionel Sambuc   // if we rewrote the #include/#import.
651*0a6a1f1dSLionel Sambuc   SourceLocation Loc = D->getLocation();
652*0a6a1f1dSLionel Sambuc   Loc = SM->getExpansionLoc(Loc);
653*0a6a1f1dSLionel Sambuc 
654*0a6a1f1dSLionel Sambuc   // If this is for a builtin, ignore it.
655*0a6a1f1dSLionel Sambuc   if (Loc.isInvalid()) return;
656*0a6a1f1dSLionel Sambuc 
657*0a6a1f1dSLionel Sambuc   // Look for built-in declarations that we need to refer during the rewrite.
658*0a6a1f1dSLionel Sambuc   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
659*0a6a1f1dSLionel Sambuc     RewriteFunctionDecl(FD);
660*0a6a1f1dSLionel Sambuc   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
661*0a6a1f1dSLionel Sambuc     // declared in <Foundation/NSString.h>
662*0a6a1f1dSLionel Sambuc     if (FVD->getName() == "_NSConstantStringClassReference") {
663*0a6a1f1dSLionel Sambuc       ConstantStringClassReference = FVD;
664*0a6a1f1dSLionel Sambuc       return;
665*0a6a1f1dSLionel Sambuc     }
666*0a6a1f1dSLionel Sambuc   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667*0a6a1f1dSLionel Sambuc     if (ID->isThisDeclarationADefinition())
668*0a6a1f1dSLionel Sambuc       RewriteInterfaceDecl(ID);
669*0a6a1f1dSLionel Sambuc   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670*0a6a1f1dSLionel Sambuc     RewriteCategoryDecl(CD);
671*0a6a1f1dSLionel Sambuc   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672*0a6a1f1dSLionel Sambuc     if (PD->isThisDeclarationADefinition())
673*0a6a1f1dSLionel Sambuc       RewriteProtocolDecl(PD);
674*0a6a1f1dSLionel Sambuc   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675*0a6a1f1dSLionel Sambuc     // Recurse into linkage specifications
676*0a6a1f1dSLionel Sambuc     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677*0a6a1f1dSLionel Sambuc                                  DIEnd = LSD->decls_end();
678*0a6a1f1dSLionel Sambuc          DI != DIEnd; ) {
679*0a6a1f1dSLionel Sambuc       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680*0a6a1f1dSLionel Sambuc         if (!IFace->isThisDeclarationADefinition()) {
681*0a6a1f1dSLionel Sambuc           SmallVector<Decl *, 8> DG;
682*0a6a1f1dSLionel Sambuc           SourceLocation StartLoc = IFace->getLocStart();
683*0a6a1f1dSLionel Sambuc           do {
684*0a6a1f1dSLionel Sambuc             if (isa<ObjCInterfaceDecl>(*DI) &&
685*0a6a1f1dSLionel Sambuc                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686*0a6a1f1dSLionel Sambuc                 StartLoc == (*DI)->getLocStart())
687*0a6a1f1dSLionel Sambuc               DG.push_back(*DI);
688*0a6a1f1dSLionel Sambuc             else
689*0a6a1f1dSLionel Sambuc               break;
690*0a6a1f1dSLionel Sambuc 
691*0a6a1f1dSLionel Sambuc             ++DI;
692*0a6a1f1dSLionel Sambuc           } while (DI != DIEnd);
693*0a6a1f1dSLionel Sambuc           RewriteForwardClassDecl(DG);
694*0a6a1f1dSLionel Sambuc           continue;
695*0a6a1f1dSLionel Sambuc         }
696*0a6a1f1dSLionel Sambuc       }
697*0a6a1f1dSLionel Sambuc 
698*0a6a1f1dSLionel Sambuc       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699*0a6a1f1dSLionel Sambuc         if (!Proto->isThisDeclarationADefinition()) {
700*0a6a1f1dSLionel Sambuc           SmallVector<Decl *, 8> DG;
701*0a6a1f1dSLionel Sambuc           SourceLocation StartLoc = Proto->getLocStart();
702*0a6a1f1dSLionel Sambuc           do {
703*0a6a1f1dSLionel Sambuc             if (isa<ObjCProtocolDecl>(*DI) &&
704*0a6a1f1dSLionel Sambuc                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705*0a6a1f1dSLionel Sambuc                 StartLoc == (*DI)->getLocStart())
706*0a6a1f1dSLionel Sambuc               DG.push_back(*DI);
707*0a6a1f1dSLionel Sambuc             else
708*0a6a1f1dSLionel Sambuc               break;
709*0a6a1f1dSLionel Sambuc 
710*0a6a1f1dSLionel Sambuc             ++DI;
711*0a6a1f1dSLionel Sambuc           } while (DI != DIEnd);
712*0a6a1f1dSLionel Sambuc           RewriteForwardProtocolDecl(DG);
713*0a6a1f1dSLionel Sambuc           continue;
714*0a6a1f1dSLionel Sambuc         }
715*0a6a1f1dSLionel Sambuc       }
716*0a6a1f1dSLionel Sambuc 
717*0a6a1f1dSLionel Sambuc       HandleTopLevelSingleDecl(*DI);
718*0a6a1f1dSLionel Sambuc       ++DI;
719*0a6a1f1dSLionel Sambuc     }
720*0a6a1f1dSLionel Sambuc   }
721*0a6a1f1dSLionel Sambuc   // If we have a decl in the main file, see if we should rewrite it.
722*0a6a1f1dSLionel Sambuc   if (SM->isWrittenInMainFile(Loc))
723*0a6a1f1dSLionel Sambuc     return HandleDeclInMainFile(D);
724*0a6a1f1dSLionel Sambuc }
725*0a6a1f1dSLionel Sambuc 
726*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
727*0a6a1f1dSLionel Sambuc // Syntactic (non-AST) Rewriting Code
728*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
729*0a6a1f1dSLionel Sambuc 
RewriteInclude()730*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteInclude() {
731*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732*0a6a1f1dSLionel Sambuc   StringRef MainBuf = SM->getBufferData(MainFileID);
733*0a6a1f1dSLionel Sambuc   const char *MainBufStart = MainBuf.begin();
734*0a6a1f1dSLionel Sambuc   const char *MainBufEnd = MainBuf.end();
735*0a6a1f1dSLionel Sambuc   size_t ImportLen = strlen("import");
736*0a6a1f1dSLionel Sambuc 
737*0a6a1f1dSLionel Sambuc   // Loop over the whole file, looking for includes.
738*0a6a1f1dSLionel Sambuc   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739*0a6a1f1dSLionel Sambuc     if (*BufPtr == '#') {
740*0a6a1f1dSLionel Sambuc       if (++BufPtr == MainBufEnd)
741*0a6a1f1dSLionel Sambuc         return;
742*0a6a1f1dSLionel Sambuc       while (*BufPtr == ' ' || *BufPtr == '\t')
743*0a6a1f1dSLionel Sambuc         if (++BufPtr == MainBufEnd)
744*0a6a1f1dSLionel Sambuc           return;
745*0a6a1f1dSLionel Sambuc       if (!strncmp(BufPtr, "import", ImportLen)) {
746*0a6a1f1dSLionel Sambuc         // replace import with include
747*0a6a1f1dSLionel Sambuc         SourceLocation ImportLoc =
748*0a6a1f1dSLionel Sambuc           LocStart.getLocWithOffset(BufPtr-MainBufStart);
749*0a6a1f1dSLionel Sambuc         ReplaceText(ImportLoc, ImportLen, "include");
750*0a6a1f1dSLionel Sambuc         BufPtr += ImportLen;
751*0a6a1f1dSLionel Sambuc       }
752*0a6a1f1dSLionel Sambuc     }
753*0a6a1f1dSLionel Sambuc   }
754*0a6a1f1dSLionel Sambuc }
755*0a6a1f1dSLionel Sambuc 
getIvarAccessString(ObjCIvarDecl * OID)756*0a6a1f1dSLionel Sambuc static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757*0a6a1f1dSLionel Sambuc   const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
758*0a6a1f1dSLionel Sambuc   std::string S;
759*0a6a1f1dSLionel Sambuc   S = "((struct ";
760*0a6a1f1dSLionel Sambuc   S += ClassDecl->getIdentifier()->getName();
761*0a6a1f1dSLionel Sambuc   S += "_IMPL *)self)->";
762*0a6a1f1dSLionel Sambuc   S += OID->getName();
763*0a6a1f1dSLionel Sambuc   return S;
764*0a6a1f1dSLionel Sambuc }
765*0a6a1f1dSLionel Sambuc 
RewritePropertyImplDecl(ObjCPropertyImplDecl * PID,ObjCImplementationDecl * IMD,ObjCCategoryImplDecl * CID)766*0a6a1f1dSLionel Sambuc void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767*0a6a1f1dSLionel Sambuc                                           ObjCImplementationDecl *IMD,
768*0a6a1f1dSLionel Sambuc                                           ObjCCategoryImplDecl *CID) {
769*0a6a1f1dSLionel Sambuc   static bool objcGetPropertyDefined = false;
770*0a6a1f1dSLionel Sambuc   static bool objcSetPropertyDefined = false;
771*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = PID->getLocStart();
772*0a6a1f1dSLionel Sambuc   InsertText(startLoc, "// ");
773*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
774*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @synthesize location");
775*0a6a1f1dSLionel Sambuc   const char *semiBuf = strchr(startBuf, ';');
776*0a6a1f1dSLionel Sambuc   assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777*0a6a1f1dSLionel Sambuc   SourceLocation onePastSemiLoc =
778*0a6a1f1dSLionel Sambuc     startLoc.getLocWithOffset(semiBuf-startBuf+1);
779*0a6a1f1dSLionel Sambuc 
780*0a6a1f1dSLionel Sambuc   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781*0a6a1f1dSLionel Sambuc     return; // FIXME: is this correct?
782*0a6a1f1dSLionel Sambuc 
783*0a6a1f1dSLionel Sambuc   // Generate the 'getter' function.
784*0a6a1f1dSLionel Sambuc   ObjCPropertyDecl *PD = PID->getPropertyDecl();
785*0a6a1f1dSLionel Sambuc   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
786*0a6a1f1dSLionel Sambuc 
787*0a6a1f1dSLionel Sambuc   if (!OID)
788*0a6a1f1dSLionel Sambuc     return;
789*0a6a1f1dSLionel Sambuc   unsigned Attributes = PD->getPropertyAttributes();
790*0a6a1f1dSLionel Sambuc   if (!PD->getGetterMethodDecl()->isDefined()) {
791*0a6a1f1dSLionel Sambuc     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792*0a6a1f1dSLionel Sambuc                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793*0a6a1f1dSLionel Sambuc                                          ObjCPropertyDecl::OBJC_PR_copy));
794*0a6a1f1dSLionel Sambuc     std::string Getr;
795*0a6a1f1dSLionel Sambuc     if (GenGetProperty && !objcGetPropertyDefined) {
796*0a6a1f1dSLionel Sambuc       objcGetPropertyDefined = true;
797*0a6a1f1dSLionel Sambuc       // FIXME. Is this attribute correct in all cases?
798*0a6a1f1dSLionel Sambuc       Getr = "\nextern \"C\" __declspec(dllimport) "
799*0a6a1f1dSLionel Sambuc             "id objc_getProperty(id, SEL, long, bool);\n";
800*0a6a1f1dSLionel Sambuc     }
801*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OID->getContainingInterface(),
802*0a6a1f1dSLionel Sambuc                           PD->getGetterMethodDecl(), Getr);
803*0a6a1f1dSLionel Sambuc     Getr += "{ ";
804*0a6a1f1dSLionel Sambuc     // Synthesize an explicit cast to gain access to the ivar.
805*0a6a1f1dSLionel Sambuc     // See objc-act.c:objc_synthesize_new_getter() for details.
806*0a6a1f1dSLionel Sambuc     if (GenGetProperty) {
807*0a6a1f1dSLionel Sambuc       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808*0a6a1f1dSLionel Sambuc       Getr += "typedef ";
809*0a6a1f1dSLionel Sambuc       const FunctionType *FPRetType = nullptr;
810*0a6a1f1dSLionel Sambuc       RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
811*0a6a1f1dSLionel Sambuc                             FPRetType);
812*0a6a1f1dSLionel Sambuc       Getr += " _TYPE";
813*0a6a1f1dSLionel Sambuc       if (FPRetType) {
814*0a6a1f1dSLionel Sambuc         Getr += ")"; // close the precedence "scope" for "*".
815*0a6a1f1dSLionel Sambuc 
816*0a6a1f1dSLionel Sambuc         // Now, emit the argument types (if any).
817*0a6a1f1dSLionel Sambuc         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818*0a6a1f1dSLionel Sambuc           Getr += "(";
819*0a6a1f1dSLionel Sambuc           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
820*0a6a1f1dSLionel Sambuc             if (i) Getr += ", ";
821*0a6a1f1dSLionel Sambuc             std::string ParamStr =
822*0a6a1f1dSLionel Sambuc                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
823*0a6a1f1dSLionel Sambuc             Getr += ParamStr;
824*0a6a1f1dSLionel Sambuc           }
825*0a6a1f1dSLionel Sambuc           if (FT->isVariadic()) {
826*0a6a1f1dSLionel Sambuc             if (FT->getNumParams())
827*0a6a1f1dSLionel Sambuc               Getr += ", ";
828*0a6a1f1dSLionel Sambuc             Getr += "...";
829*0a6a1f1dSLionel Sambuc           }
830*0a6a1f1dSLionel Sambuc           Getr += ")";
831*0a6a1f1dSLionel Sambuc         } else
832*0a6a1f1dSLionel Sambuc           Getr += "()";
833*0a6a1f1dSLionel Sambuc       }
834*0a6a1f1dSLionel Sambuc       Getr += ";\n";
835*0a6a1f1dSLionel Sambuc       Getr += "return (_TYPE)";
836*0a6a1f1dSLionel Sambuc       Getr += "objc_getProperty(self, _cmd, ";
837*0a6a1f1dSLionel Sambuc       RewriteIvarOffsetComputation(OID, Getr);
838*0a6a1f1dSLionel Sambuc       Getr += ", 1)";
839*0a6a1f1dSLionel Sambuc     }
840*0a6a1f1dSLionel Sambuc     else
841*0a6a1f1dSLionel Sambuc       Getr += "return " + getIvarAccessString(OID);
842*0a6a1f1dSLionel Sambuc     Getr += "; }";
843*0a6a1f1dSLionel Sambuc     InsertText(onePastSemiLoc, Getr);
844*0a6a1f1dSLionel Sambuc   }
845*0a6a1f1dSLionel Sambuc 
846*0a6a1f1dSLionel Sambuc   if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
847*0a6a1f1dSLionel Sambuc     return;
848*0a6a1f1dSLionel Sambuc 
849*0a6a1f1dSLionel Sambuc   // Generate the 'setter' function.
850*0a6a1f1dSLionel Sambuc   std::string Setr;
851*0a6a1f1dSLionel Sambuc   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852*0a6a1f1dSLionel Sambuc                                       ObjCPropertyDecl::OBJC_PR_copy);
853*0a6a1f1dSLionel Sambuc   if (GenSetProperty && !objcSetPropertyDefined) {
854*0a6a1f1dSLionel Sambuc     objcSetPropertyDefined = true;
855*0a6a1f1dSLionel Sambuc     // FIXME. Is this attribute correct in all cases?
856*0a6a1f1dSLionel Sambuc     Setr = "\nextern \"C\" __declspec(dllimport) "
857*0a6a1f1dSLionel Sambuc     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858*0a6a1f1dSLionel Sambuc   }
859*0a6a1f1dSLionel Sambuc 
860*0a6a1f1dSLionel Sambuc   RewriteObjCMethodDecl(OID->getContainingInterface(),
861*0a6a1f1dSLionel Sambuc                         PD->getSetterMethodDecl(), Setr);
862*0a6a1f1dSLionel Sambuc   Setr += "{ ";
863*0a6a1f1dSLionel Sambuc   // Synthesize an explicit cast to initialize the ivar.
864*0a6a1f1dSLionel Sambuc   // See objc-act.c:objc_synthesize_new_setter() for details.
865*0a6a1f1dSLionel Sambuc   if (GenSetProperty) {
866*0a6a1f1dSLionel Sambuc     Setr += "objc_setProperty (self, _cmd, ";
867*0a6a1f1dSLionel Sambuc     RewriteIvarOffsetComputation(OID, Setr);
868*0a6a1f1dSLionel Sambuc     Setr += ", (id)";
869*0a6a1f1dSLionel Sambuc     Setr += PD->getName();
870*0a6a1f1dSLionel Sambuc     Setr += ", ";
871*0a6a1f1dSLionel Sambuc     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872*0a6a1f1dSLionel Sambuc       Setr += "0, ";
873*0a6a1f1dSLionel Sambuc     else
874*0a6a1f1dSLionel Sambuc       Setr += "1, ";
875*0a6a1f1dSLionel Sambuc     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876*0a6a1f1dSLionel Sambuc       Setr += "1)";
877*0a6a1f1dSLionel Sambuc     else
878*0a6a1f1dSLionel Sambuc       Setr += "0)";
879*0a6a1f1dSLionel Sambuc   }
880*0a6a1f1dSLionel Sambuc   else {
881*0a6a1f1dSLionel Sambuc     Setr += getIvarAccessString(OID) + " = ";
882*0a6a1f1dSLionel Sambuc     Setr += PD->getName();
883*0a6a1f1dSLionel Sambuc   }
884*0a6a1f1dSLionel Sambuc   Setr += "; }";
885*0a6a1f1dSLionel Sambuc   InsertText(onePastSemiLoc, Setr);
886*0a6a1f1dSLionel Sambuc }
887*0a6a1f1dSLionel Sambuc 
RewriteOneForwardClassDecl(ObjCInterfaceDecl * ForwardDecl,std::string & typedefString)888*0a6a1f1dSLionel Sambuc static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889*0a6a1f1dSLionel Sambuc                                        std::string &typedefString) {
890*0a6a1f1dSLionel Sambuc   typedefString += "#ifndef _REWRITER_typedef_";
891*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
892*0a6a1f1dSLionel Sambuc   typedefString += "\n";
893*0a6a1f1dSLionel Sambuc   typedefString += "#define _REWRITER_typedef_";
894*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
895*0a6a1f1dSLionel Sambuc   typedefString += "\n";
896*0a6a1f1dSLionel Sambuc   typedefString += "typedef struct objc_object ";
897*0a6a1f1dSLionel Sambuc   typedefString += ForwardDecl->getNameAsString();
898*0a6a1f1dSLionel Sambuc   typedefString += ";\n#endif\n";
899*0a6a1f1dSLionel Sambuc }
900*0a6a1f1dSLionel Sambuc 
RewriteForwardClassEpilogue(ObjCInterfaceDecl * ClassDecl,const std::string & typedefString)901*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
902*0a6a1f1dSLionel Sambuc                                               const std::string &typedefString) {
903*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = ClassDecl->getLocStart();
904*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
905*0a6a1f1dSLionel Sambuc     const char *semiPtr = strchr(startBuf, ';');
906*0a6a1f1dSLionel Sambuc     // Replace the @class with typedefs corresponding to the classes.
907*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908*0a6a1f1dSLionel Sambuc }
909*0a6a1f1dSLionel Sambuc 
RewriteForwardClassDecl(DeclGroupRef D)910*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
911*0a6a1f1dSLionel Sambuc   std::string typedefString;
912*0a6a1f1dSLionel Sambuc   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
913*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
914*0a6a1f1dSLionel Sambuc     if (I == D.begin()) {
915*0a6a1f1dSLionel Sambuc       // Translate to typedef's that forward reference structs with the same name
916*0a6a1f1dSLionel Sambuc       // as the class. As a convenience, we include the original declaration
917*0a6a1f1dSLionel Sambuc       // as a comment.
918*0a6a1f1dSLionel Sambuc       typedefString += "// @class ";
919*0a6a1f1dSLionel Sambuc       typedefString += ForwardDecl->getNameAsString();
920*0a6a1f1dSLionel Sambuc       typedefString += ";\n";
921*0a6a1f1dSLionel Sambuc     }
922*0a6a1f1dSLionel Sambuc     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
923*0a6a1f1dSLionel Sambuc   }
924*0a6a1f1dSLionel Sambuc   DeclGroupRef::iterator I = D.begin();
925*0a6a1f1dSLionel Sambuc   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
926*0a6a1f1dSLionel Sambuc }
927*0a6a1f1dSLionel Sambuc 
RewriteForwardClassDecl(const SmallVectorImpl<Decl * > & D)928*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
929*0a6a1f1dSLionel Sambuc   std::string typedefString;
930*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < D.size(); i++) {
931*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
932*0a6a1f1dSLionel Sambuc     if (i == 0) {
933*0a6a1f1dSLionel Sambuc       typedefString += "// @class ";
934*0a6a1f1dSLionel Sambuc       typedefString += ForwardDecl->getNameAsString();
935*0a6a1f1dSLionel Sambuc       typedefString += ";\n";
936*0a6a1f1dSLionel Sambuc     }
937*0a6a1f1dSLionel Sambuc     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
938*0a6a1f1dSLionel Sambuc   }
939*0a6a1f1dSLionel Sambuc   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
940*0a6a1f1dSLionel Sambuc }
941*0a6a1f1dSLionel Sambuc 
RewriteMethodDeclaration(ObjCMethodDecl * Method)942*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
943*0a6a1f1dSLionel Sambuc   // When method is a synthesized one, such as a getter/setter there is
944*0a6a1f1dSLionel Sambuc   // nothing to rewrite.
945*0a6a1f1dSLionel Sambuc   if (Method->isImplicit())
946*0a6a1f1dSLionel Sambuc     return;
947*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = Method->getLocStart();
948*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = Method->getLocEnd();
949*0a6a1f1dSLionel Sambuc 
950*0a6a1f1dSLionel Sambuc   if (SM->getExpansionLineNumber(LocEnd) >
951*0a6a1f1dSLionel Sambuc       SM->getExpansionLineNumber(LocStart)) {
952*0a6a1f1dSLionel Sambuc     InsertText(LocStart, "#if 0\n");
953*0a6a1f1dSLionel Sambuc     ReplaceText(LocEnd, 1, ";\n#endif\n");
954*0a6a1f1dSLionel Sambuc   } else {
955*0a6a1f1dSLionel Sambuc     InsertText(LocStart, "// ");
956*0a6a1f1dSLionel Sambuc   }
957*0a6a1f1dSLionel Sambuc }
958*0a6a1f1dSLionel Sambuc 
RewriteProperty(ObjCPropertyDecl * prop)959*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
960*0a6a1f1dSLionel Sambuc   SourceLocation Loc = prop->getAtLoc();
961*0a6a1f1dSLionel Sambuc 
962*0a6a1f1dSLionel Sambuc   ReplaceText(Loc, 0, "// ");
963*0a6a1f1dSLionel Sambuc   // FIXME: handle properties that are declared across multiple lines.
964*0a6a1f1dSLionel Sambuc }
965*0a6a1f1dSLionel Sambuc 
RewriteCategoryDecl(ObjCCategoryDecl * CatDecl)966*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
967*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CatDecl->getLocStart();
968*0a6a1f1dSLionel Sambuc 
969*0a6a1f1dSLionel Sambuc   // FIXME: handle category headers that are declared across multiple lines.
970*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
971*0a6a1f1dSLionel Sambuc 
972*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->properties())
973*0a6a1f1dSLionel Sambuc     RewriteProperty(I);
974*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->instance_methods())
975*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
976*0a6a1f1dSLionel Sambuc   for (auto *I : CatDecl->class_methods())
977*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
978*0a6a1f1dSLionel Sambuc 
979*0a6a1f1dSLionel Sambuc   // Lastly, comment out the @end.
980*0a6a1f1dSLionel Sambuc   ReplaceText(CatDecl->getAtEndRange().getBegin(),
981*0a6a1f1dSLionel Sambuc               strlen("@end"), "/* @end */");
982*0a6a1f1dSLionel Sambuc }
983*0a6a1f1dSLionel Sambuc 
RewriteProtocolDecl(ObjCProtocolDecl * PDecl)984*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
985*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = PDecl->getLocStart();
986*0a6a1f1dSLionel Sambuc   assert(PDecl->isThisDeclarationADefinition());
987*0a6a1f1dSLionel Sambuc 
988*0a6a1f1dSLionel Sambuc   // FIXME: handle protocol headers that are declared across multiple lines.
989*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
990*0a6a1f1dSLionel Sambuc 
991*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->instance_methods())
992*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
993*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->class_methods())
994*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
995*0a6a1f1dSLionel Sambuc   for (auto *I : PDecl->properties())
996*0a6a1f1dSLionel Sambuc     RewriteProperty(I);
997*0a6a1f1dSLionel Sambuc 
998*0a6a1f1dSLionel Sambuc   // Lastly, comment out the @end.
999*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1000*0a6a1f1dSLionel Sambuc   ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1001*0a6a1f1dSLionel Sambuc 
1002*0a6a1f1dSLionel Sambuc   // Must comment out @optional/@required
1003*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
1004*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
1005*0a6a1f1dSLionel Sambuc   for (const char *p = startBuf; p < endBuf; p++) {
1006*0a6a1f1dSLionel Sambuc     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1007*0a6a1f1dSLionel Sambuc       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1008*0a6a1f1dSLionel Sambuc       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1009*0a6a1f1dSLionel Sambuc 
1010*0a6a1f1dSLionel Sambuc     }
1011*0a6a1f1dSLionel Sambuc     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1012*0a6a1f1dSLionel Sambuc       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1013*0a6a1f1dSLionel Sambuc       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1014*0a6a1f1dSLionel Sambuc 
1015*0a6a1f1dSLionel Sambuc     }
1016*0a6a1f1dSLionel Sambuc   }
1017*0a6a1f1dSLionel Sambuc }
1018*0a6a1f1dSLionel Sambuc 
RewriteForwardProtocolDecl(DeclGroupRef D)1019*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = (*D.begin())->getLocStart();
1021*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
1022*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid SourceLocation");
1023*0a6a1f1dSLionel Sambuc   // FIXME: handle forward protocol that are declared across multiple lines.
1024*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1025*0a6a1f1dSLionel Sambuc }
1026*0a6a1f1dSLionel Sambuc 
1027*0a6a1f1dSLionel Sambuc void
RewriteForwardProtocolDecl(const SmallVectorImpl<Decl * > & DG)1028*0a6a1f1dSLionel Sambuc RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1029*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = DG[0]->getLocStart();
1030*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
1031*0a6a1f1dSLionel Sambuc     llvm_unreachable("Invalid SourceLocation");
1032*0a6a1f1dSLionel Sambuc   // FIXME: handle forward protocol that are declared across multiple lines.
1033*0a6a1f1dSLionel Sambuc   ReplaceText(LocStart, 0, "// ");
1034*0a6a1f1dSLionel Sambuc }
1035*0a6a1f1dSLionel Sambuc 
RewriteTypeIntoString(QualType T,std::string & ResultStr,const FunctionType * & FPRetType)1036*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037*0a6a1f1dSLionel Sambuc                                         const FunctionType *&FPRetType) {
1038*0a6a1f1dSLionel Sambuc   if (T->isObjCQualifiedIdType())
1039*0a6a1f1dSLionel Sambuc     ResultStr += "id";
1040*0a6a1f1dSLionel Sambuc   else if (T->isFunctionPointerType() ||
1041*0a6a1f1dSLionel Sambuc            T->isBlockPointerType()) {
1042*0a6a1f1dSLionel Sambuc     // needs special handling, since pointer-to-functions have special
1043*0a6a1f1dSLionel Sambuc     // syntax (where a decaration models use).
1044*0a6a1f1dSLionel Sambuc     QualType retType = T;
1045*0a6a1f1dSLionel Sambuc     QualType PointeeTy;
1046*0a6a1f1dSLionel Sambuc     if (const PointerType* PT = retType->getAs<PointerType>())
1047*0a6a1f1dSLionel Sambuc       PointeeTy = PT->getPointeeType();
1048*0a6a1f1dSLionel Sambuc     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1049*0a6a1f1dSLionel Sambuc       PointeeTy = BPT->getPointeeType();
1050*0a6a1f1dSLionel Sambuc     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1051*0a6a1f1dSLionel Sambuc       ResultStr +=
1052*0a6a1f1dSLionel Sambuc           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1053*0a6a1f1dSLionel Sambuc       ResultStr += "(*";
1054*0a6a1f1dSLionel Sambuc     }
1055*0a6a1f1dSLionel Sambuc   } else
1056*0a6a1f1dSLionel Sambuc     ResultStr += T.getAsString(Context->getPrintingPolicy());
1057*0a6a1f1dSLionel Sambuc }
1058*0a6a1f1dSLionel Sambuc 
RewriteObjCMethodDecl(const ObjCInterfaceDecl * IDecl,ObjCMethodDecl * OMD,std::string & ResultStr)1059*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060*0a6a1f1dSLionel Sambuc                                         ObjCMethodDecl *OMD,
1061*0a6a1f1dSLionel Sambuc                                         std::string &ResultStr) {
1062*0a6a1f1dSLionel Sambuc   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1063*0a6a1f1dSLionel Sambuc   const FunctionType *FPRetType = nullptr;
1064*0a6a1f1dSLionel Sambuc   ResultStr += "\nstatic ";
1065*0a6a1f1dSLionel Sambuc   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1066*0a6a1f1dSLionel Sambuc   ResultStr += " ";
1067*0a6a1f1dSLionel Sambuc 
1068*0a6a1f1dSLionel Sambuc   // Unique method name
1069*0a6a1f1dSLionel Sambuc   std::string NameStr;
1070*0a6a1f1dSLionel Sambuc 
1071*0a6a1f1dSLionel Sambuc   if (OMD->isInstanceMethod())
1072*0a6a1f1dSLionel Sambuc     NameStr += "_I_";
1073*0a6a1f1dSLionel Sambuc   else
1074*0a6a1f1dSLionel Sambuc     NameStr += "_C_";
1075*0a6a1f1dSLionel Sambuc 
1076*0a6a1f1dSLionel Sambuc   NameStr += IDecl->getNameAsString();
1077*0a6a1f1dSLionel Sambuc   NameStr += "_";
1078*0a6a1f1dSLionel Sambuc 
1079*0a6a1f1dSLionel Sambuc   if (ObjCCategoryImplDecl *CID =
1080*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1081*0a6a1f1dSLionel Sambuc     NameStr += CID->getNameAsString();
1082*0a6a1f1dSLionel Sambuc     NameStr += "_";
1083*0a6a1f1dSLionel Sambuc   }
1084*0a6a1f1dSLionel Sambuc   // Append selector names, replacing ':' with '_'
1085*0a6a1f1dSLionel Sambuc   {
1086*0a6a1f1dSLionel Sambuc     std::string selString = OMD->getSelector().getAsString();
1087*0a6a1f1dSLionel Sambuc     int len = selString.size();
1088*0a6a1f1dSLionel Sambuc     for (int i = 0; i < len; i++)
1089*0a6a1f1dSLionel Sambuc       if (selString[i] == ':')
1090*0a6a1f1dSLionel Sambuc         selString[i] = '_';
1091*0a6a1f1dSLionel Sambuc     NameStr += selString;
1092*0a6a1f1dSLionel Sambuc   }
1093*0a6a1f1dSLionel Sambuc   // Remember this name for metadata emission
1094*0a6a1f1dSLionel Sambuc   MethodInternalNames[OMD] = NameStr;
1095*0a6a1f1dSLionel Sambuc   ResultStr += NameStr;
1096*0a6a1f1dSLionel Sambuc 
1097*0a6a1f1dSLionel Sambuc   // Rewrite arguments
1098*0a6a1f1dSLionel Sambuc   ResultStr += "(";
1099*0a6a1f1dSLionel Sambuc 
1100*0a6a1f1dSLionel Sambuc   // invisible arguments
1101*0a6a1f1dSLionel Sambuc   if (OMD->isInstanceMethod()) {
1102*0a6a1f1dSLionel Sambuc     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1103*0a6a1f1dSLionel Sambuc     selfTy = Context->getPointerType(selfTy);
1104*0a6a1f1dSLionel Sambuc     if (!LangOpts.MicrosoftExt) {
1105*0a6a1f1dSLionel Sambuc       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1106*0a6a1f1dSLionel Sambuc         ResultStr += "struct ";
1107*0a6a1f1dSLionel Sambuc     }
1108*0a6a1f1dSLionel Sambuc     // When rewriting for Microsoft, explicitly omit the structure name.
1109*0a6a1f1dSLionel Sambuc     ResultStr += IDecl->getNameAsString();
1110*0a6a1f1dSLionel Sambuc     ResultStr += " *";
1111*0a6a1f1dSLionel Sambuc   }
1112*0a6a1f1dSLionel Sambuc   else
1113*0a6a1f1dSLionel Sambuc     ResultStr += Context->getObjCClassType().getAsString(
1114*0a6a1f1dSLionel Sambuc       Context->getPrintingPolicy());
1115*0a6a1f1dSLionel Sambuc 
1116*0a6a1f1dSLionel Sambuc   ResultStr += " self, ";
1117*0a6a1f1dSLionel Sambuc   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1118*0a6a1f1dSLionel Sambuc   ResultStr += " _cmd";
1119*0a6a1f1dSLionel Sambuc 
1120*0a6a1f1dSLionel Sambuc   // Method arguments.
1121*0a6a1f1dSLionel Sambuc   for (const auto *PDecl : OMD->params()) {
1122*0a6a1f1dSLionel Sambuc     ResultStr += ", ";
1123*0a6a1f1dSLionel Sambuc     if (PDecl->getType()->isObjCQualifiedIdType()) {
1124*0a6a1f1dSLionel Sambuc       ResultStr += "id ";
1125*0a6a1f1dSLionel Sambuc       ResultStr += PDecl->getNameAsString();
1126*0a6a1f1dSLionel Sambuc     } else {
1127*0a6a1f1dSLionel Sambuc       std::string Name = PDecl->getNameAsString();
1128*0a6a1f1dSLionel Sambuc       QualType QT = PDecl->getType();
1129*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1130*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(QT);
1131*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1132*0a6a1f1dSLionel Sambuc       ResultStr += Name;
1133*0a6a1f1dSLionel Sambuc     }
1134*0a6a1f1dSLionel Sambuc   }
1135*0a6a1f1dSLionel Sambuc   if (OMD->isVariadic())
1136*0a6a1f1dSLionel Sambuc     ResultStr += ", ...";
1137*0a6a1f1dSLionel Sambuc   ResultStr += ") ";
1138*0a6a1f1dSLionel Sambuc 
1139*0a6a1f1dSLionel Sambuc   if (FPRetType) {
1140*0a6a1f1dSLionel Sambuc     ResultStr += ")"; // close the precedence "scope" for "*".
1141*0a6a1f1dSLionel Sambuc 
1142*0a6a1f1dSLionel Sambuc     // Now, emit the argument types (if any).
1143*0a6a1f1dSLionel Sambuc     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1144*0a6a1f1dSLionel Sambuc       ResultStr += "(";
1145*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1146*0a6a1f1dSLionel Sambuc         if (i) ResultStr += ", ";
1147*0a6a1f1dSLionel Sambuc         std::string ParamStr =
1148*0a6a1f1dSLionel Sambuc             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1149*0a6a1f1dSLionel Sambuc         ResultStr += ParamStr;
1150*0a6a1f1dSLionel Sambuc       }
1151*0a6a1f1dSLionel Sambuc       if (FT->isVariadic()) {
1152*0a6a1f1dSLionel Sambuc         if (FT->getNumParams())
1153*0a6a1f1dSLionel Sambuc           ResultStr += ", ";
1154*0a6a1f1dSLionel Sambuc         ResultStr += "...";
1155*0a6a1f1dSLionel Sambuc       }
1156*0a6a1f1dSLionel Sambuc       ResultStr += ")";
1157*0a6a1f1dSLionel Sambuc     } else {
1158*0a6a1f1dSLionel Sambuc       ResultStr += "()";
1159*0a6a1f1dSLionel Sambuc     }
1160*0a6a1f1dSLionel Sambuc   }
1161*0a6a1f1dSLionel Sambuc }
RewriteImplementationDecl(Decl * OID)1162*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1163*0a6a1f1dSLionel Sambuc   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1164*0a6a1f1dSLionel Sambuc   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1165*0a6a1f1dSLionel Sambuc 
1166*0a6a1f1dSLionel Sambuc   InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1167*0a6a1f1dSLionel Sambuc 
1168*0a6a1f1dSLionel Sambuc   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1169*0a6a1f1dSLionel Sambuc     std::string ResultStr;
1170*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1171*0a6a1f1dSLionel Sambuc     SourceLocation LocStart = OMD->getLocStart();
1172*0a6a1f1dSLionel Sambuc     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1173*0a6a1f1dSLionel Sambuc 
1174*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(LocStart);
1175*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(LocEnd);
1176*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1177*0a6a1f1dSLionel Sambuc   }
1178*0a6a1f1dSLionel Sambuc 
1179*0a6a1f1dSLionel Sambuc   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1180*0a6a1f1dSLionel Sambuc     std::string ResultStr;
1181*0a6a1f1dSLionel Sambuc     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1182*0a6a1f1dSLionel Sambuc     SourceLocation LocStart = OMD->getLocStart();
1183*0a6a1f1dSLionel Sambuc     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1184*0a6a1f1dSLionel Sambuc 
1185*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(LocStart);
1186*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(LocEnd);
1187*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1188*0a6a1f1dSLionel Sambuc   }
1189*0a6a1f1dSLionel Sambuc   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1190*0a6a1f1dSLionel Sambuc     RewritePropertyImplDecl(I, IMD, CID);
1191*0a6a1f1dSLionel Sambuc 
1192*0a6a1f1dSLionel Sambuc   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1193*0a6a1f1dSLionel Sambuc }
1194*0a6a1f1dSLionel Sambuc 
RewriteInterfaceDecl(ObjCInterfaceDecl * ClassDecl)1195*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1196*0a6a1f1dSLionel Sambuc   std::string ResultStr;
1197*0a6a1f1dSLionel Sambuc   if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1198*0a6a1f1dSLionel Sambuc     // we haven't seen a forward decl - generate a typedef.
1199*0a6a1f1dSLionel Sambuc     ResultStr = "#ifndef _REWRITER_typedef_";
1200*0a6a1f1dSLionel Sambuc     ResultStr += ClassDecl->getNameAsString();
1201*0a6a1f1dSLionel Sambuc     ResultStr += "\n";
1202*0a6a1f1dSLionel Sambuc     ResultStr += "#define _REWRITER_typedef_";
1203*0a6a1f1dSLionel Sambuc     ResultStr += ClassDecl->getNameAsString();
1204*0a6a1f1dSLionel Sambuc     ResultStr += "\n";
1205*0a6a1f1dSLionel Sambuc     ResultStr += "typedef struct objc_object ";
1206*0a6a1f1dSLionel Sambuc     ResultStr += ClassDecl->getNameAsString();
1207*0a6a1f1dSLionel Sambuc     ResultStr += ";\n#endif\n";
1208*0a6a1f1dSLionel Sambuc     // Mark this typedef as having been generated.
1209*0a6a1f1dSLionel Sambuc     ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1210*0a6a1f1dSLionel Sambuc   }
1211*0a6a1f1dSLionel Sambuc   RewriteObjCInternalStruct(ClassDecl, ResultStr);
1212*0a6a1f1dSLionel Sambuc 
1213*0a6a1f1dSLionel Sambuc   for (auto *I : ClassDecl->properties())
1214*0a6a1f1dSLionel Sambuc     RewriteProperty(I);
1215*0a6a1f1dSLionel Sambuc   for (auto *I : ClassDecl->instance_methods())
1216*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1217*0a6a1f1dSLionel Sambuc   for (auto *I : ClassDecl->class_methods())
1218*0a6a1f1dSLionel Sambuc     RewriteMethodDeclaration(I);
1219*0a6a1f1dSLionel Sambuc 
1220*0a6a1f1dSLionel Sambuc   // Lastly, comment out the @end.
1221*0a6a1f1dSLionel Sambuc   ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1222*0a6a1f1dSLionel Sambuc               "/* @end */");
1223*0a6a1f1dSLionel Sambuc }
1224*0a6a1f1dSLionel Sambuc 
RewritePropertyOrImplicitSetter(PseudoObjectExpr * PseudoOp)1225*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1226*0a6a1f1dSLionel Sambuc   SourceRange OldRange = PseudoOp->getSourceRange();
1227*0a6a1f1dSLionel Sambuc 
1228*0a6a1f1dSLionel Sambuc   // We just magically know some things about the structure of this
1229*0a6a1f1dSLionel Sambuc   // expression.
1230*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *OldMsg =
1231*0a6a1f1dSLionel Sambuc     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1232*0a6a1f1dSLionel Sambuc                             PseudoOp->getNumSemanticExprs() - 1));
1233*0a6a1f1dSLionel Sambuc 
1234*0a6a1f1dSLionel Sambuc   // Because the rewriter doesn't allow us to rewrite rewritten code,
1235*0a6a1f1dSLionel Sambuc   // we need to suppress rewriting the sub-statements.
1236*0a6a1f1dSLionel Sambuc   Expr *Base, *RHS;
1237*0a6a1f1dSLionel Sambuc   {
1238*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
1239*0a6a1f1dSLionel Sambuc 
1240*0a6a1f1dSLionel Sambuc     // Rebuild the base expression if we have one.
1241*0a6a1f1dSLionel Sambuc     Base = nullptr;
1242*0a6a1f1dSLionel Sambuc     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1243*0a6a1f1dSLionel Sambuc       Base = OldMsg->getInstanceReceiver();
1244*0a6a1f1dSLionel Sambuc       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245*0a6a1f1dSLionel Sambuc       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1246*0a6a1f1dSLionel Sambuc     }
1247*0a6a1f1dSLionel Sambuc 
1248*0a6a1f1dSLionel Sambuc     // Rebuild the RHS.
1249*0a6a1f1dSLionel Sambuc     RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1250*0a6a1f1dSLionel Sambuc     RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251*0a6a1f1dSLionel Sambuc     RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1252*0a6a1f1dSLionel Sambuc   }
1253*0a6a1f1dSLionel Sambuc 
1254*0a6a1f1dSLionel Sambuc   // TODO: avoid this copy.
1255*0a6a1f1dSLionel Sambuc   SmallVector<SourceLocation, 1> SelLocs;
1256*0a6a1f1dSLionel Sambuc   OldMsg->getSelectorLocs(SelLocs);
1257*0a6a1f1dSLionel Sambuc 
1258*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *NewMsg = nullptr;
1259*0a6a1f1dSLionel Sambuc   switch (OldMsg->getReceiverKind()) {
1260*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class:
1261*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1262*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1263*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1264*0a6a1f1dSLionel Sambuc                                      OldMsg->getClassReceiverTypeInfo(),
1265*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1266*0a6a1f1dSLionel Sambuc                                      SelLocs,
1267*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1268*0a6a1f1dSLionel Sambuc                                      RHS,
1269*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1270*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1271*0a6a1f1dSLionel Sambuc     break;
1272*0a6a1f1dSLionel Sambuc 
1273*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance:
1274*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1275*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1276*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1277*0a6a1f1dSLionel Sambuc                                      Base,
1278*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1279*0a6a1f1dSLionel Sambuc                                      SelLocs,
1280*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1281*0a6a1f1dSLionel Sambuc                                      RHS,
1282*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1283*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1284*0a6a1f1dSLionel Sambuc     break;
1285*0a6a1f1dSLionel Sambuc 
1286*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass:
1287*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
1288*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1289*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1290*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1291*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperLoc(),
1292*0a6a1f1dSLionel Sambuc                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1293*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperType(),
1294*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1295*0a6a1f1dSLionel Sambuc                                      SelLocs,
1296*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1297*0a6a1f1dSLionel Sambuc                                      RHS,
1298*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1299*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1300*0a6a1f1dSLionel Sambuc     break;
1301*0a6a1f1dSLionel Sambuc   }
1302*0a6a1f1dSLionel Sambuc 
1303*0a6a1f1dSLionel Sambuc   Stmt *Replacement = SynthMessageExpr(NewMsg);
1304*0a6a1f1dSLionel Sambuc   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1305*0a6a1f1dSLionel Sambuc   return Replacement;
1306*0a6a1f1dSLionel Sambuc }
1307*0a6a1f1dSLionel Sambuc 
RewritePropertyOrImplicitGetter(PseudoObjectExpr * PseudoOp)1308*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1309*0a6a1f1dSLionel Sambuc   SourceRange OldRange = PseudoOp->getSourceRange();
1310*0a6a1f1dSLionel Sambuc 
1311*0a6a1f1dSLionel Sambuc   // We just magically know some things about the structure of this
1312*0a6a1f1dSLionel Sambuc   // expression.
1313*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *OldMsg =
1314*0a6a1f1dSLionel Sambuc     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1315*0a6a1f1dSLionel Sambuc 
1316*0a6a1f1dSLionel Sambuc   // Because the rewriter doesn't allow us to rewrite rewritten code,
1317*0a6a1f1dSLionel Sambuc   // we need to suppress rewriting the sub-statements.
1318*0a6a1f1dSLionel Sambuc   Expr *Base = nullptr;
1319*0a6a1f1dSLionel Sambuc   {
1320*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
1321*0a6a1f1dSLionel Sambuc 
1322*0a6a1f1dSLionel Sambuc     // Rebuild the base expression if we have one.
1323*0a6a1f1dSLionel Sambuc     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1324*0a6a1f1dSLionel Sambuc       Base = OldMsg->getInstanceReceiver();
1325*0a6a1f1dSLionel Sambuc       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1326*0a6a1f1dSLionel Sambuc       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1327*0a6a1f1dSLionel Sambuc     }
1328*0a6a1f1dSLionel Sambuc   }
1329*0a6a1f1dSLionel Sambuc 
1330*0a6a1f1dSLionel Sambuc   // Intentionally empty.
1331*0a6a1f1dSLionel Sambuc   SmallVector<SourceLocation, 1> SelLocs;
1332*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 1> Args;
1333*0a6a1f1dSLionel Sambuc 
1334*0a6a1f1dSLionel Sambuc   ObjCMessageExpr *NewMsg = nullptr;
1335*0a6a1f1dSLionel Sambuc   switch (OldMsg->getReceiverKind()) {
1336*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class:
1337*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1338*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1339*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1340*0a6a1f1dSLionel Sambuc                                      OldMsg->getClassReceiverTypeInfo(),
1341*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1342*0a6a1f1dSLionel Sambuc                                      SelLocs,
1343*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1344*0a6a1f1dSLionel Sambuc                                      Args,
1345*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1346*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1347*0a6a1f1dSLionel Sambuc     break;
1348*0a6a1f1dSLionel Sambuc 
1349*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance:
1350*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1351*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1352*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1353*0a6a1f1dSLionel Sambuc                                      Base,
1354*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1355*0a6a1f1dSLionel Sambuc                                      SelLocs,
1356*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1357*0a6a1f1dSLionel Sambuc                                      Args,
1358*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1359*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1360*0a6a1f1dSLionel Sambuc     break;
1361*0a6a1f1dSLionel Sambuc 
1362*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass:
1363*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
1364*0a6a1f1dSLionel Sambuc     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1365*0a6a1f1dSLionel Sambuc                                      OldMsg->getValueKind(),
1366*0a6a1f1dSLionel Sambuc                                      OldMsg->getLeftLoc(),
1367*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperLoc(),
1368*0a6a1f1dSLionel Sambuc                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1369*0a6a1f1dSLionel Sambuc                                      OldMsg->getSuperType(),
1370*0a6a1f1dSLionel Sambuc                                      OldMsg->getSelector(),
1371*0a6a1f1dSLionel Sambuc                                      SelLocs,
1372*0a6a1f1dSLionel Sambuc                                      OldMsg->getMethodDecl(),
1373*0a6a1f1dSLionel Sambuc                                      Args,
1374*0a6a1f1dSLionel Sambuc                                      OldMsg->getRightLoc(),
1375*0a6a1f1dSLionel Sambuc                                      OldMsg->isImplicit());
1376*0a6a1f1dSLionel Sambuc     break;
1377*0a6a1f1dSLionel Sambuc   }
1378*0a6a1f1dSLionel Sambuc 
1379*0a6a1f1dSLionel Sambuc   Stmt *Replacement = SynthMessageExpr(NewMsg);
1380*0a6a1f1dSLionel Sambuc   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1381*0a6a1f1dSLionel Sambuc   return Replacement;
1382*0a6a1f1dSLionel Sambuc }
1383*0a6a1f1dSLionel Sambuc 
1384*0a6a1f1dSLionel Sambuc /// SynthCountByEnumWithState - To print:
1385*0a6a1f1dSLionel Sambuc /// ((unsigned int (*)
1386*0a6a1f1dSLionel Sambuc ///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1387*0a6a1f1dSLionel Sambuc ///  (void *)objc_msgSend)((id)l_collection,
1388*0a6a1f1dSLionel Sambuc ///                        sel_registerName(
1389*0a6a1f1dSLionel Sambuc ///                          "countByEnumeratingWithState:objects:count:"),
1390*0a6a1f1dSLionel Sambuc ///                        &enumState,
1391*0a6a1f1dSLionel Sambuc ///                        (id *)__rw_items, (unsigned int)16)
1392*0a6a1f1dSLionel Sambuc ///
SynthCountByEnumWithState(std::string & buf)1393*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1394*0a6a1f1dSLionel Sambuc   buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1395*0a6a1f1dSLionel Sambuc   "id *, unsigned int))(void *)objc_msgSend)";
1396*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1397*0a6a1f1dSLionel Sambuc   buf += "((id)l_collection,\n\t\t";
1398*0a6a1f1dSLionel Sambuc   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1399*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1400*0a6a1f1dSLionel Sambuc   buf += "&enumState, "
1401*0a6a1f1dSLionel Sambuc          "(id *)__rw_items, (unsigned int)16)";
1402*0a6a1f1dSLionel Sambuc }
1403*0a6a1f1dSLionel Sambuc 
1404*0a6a1f1dSLionel Sambuc /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1405*0a6a1f1dSLionel Sambuc /// statement to exit to its outer synthesized loop.
1406*0a6a1f1dSLionel Sambuc ///
RewriteBreakStmt(BreakStmt * S)1407*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1408*0a6a1f1dSLionel Sambuc   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1409*0a6a1f1dSLionel Sambuc     return S;
1410*0a6a1f1dSLionel Sambuc   // replace break with goto __break_label
1411*0a6a1f1dSLionel Sambuc   std::string buf;
1412*0a6a1f1dSLionel Sambuc 
1413*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1414*0a6a1f1dSLionel Sambuc   buf = "goto __break_label_";
1415*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1416*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, strlen("break"), buf);
1417*0a6a1f1dSLionel Sambuc 
1418*0a6a1f1dSLionel Sambuc   return nullptr;
1419*0a6a1f1dSLionel Sambuc }
1420*0a6a1f1dSLionel Sambuc 
1421*0a6a1f1dSLionel Sambuc /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1422*0a6a1f1dSLionel Sambuc /// statement to continue with its inner synthesized loop.
1423*0a6a1f1dSLionel Sambuc ///
RewriteContinueStmt(ContinueStmt * S)1424*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1425*0a6a1f1dSLionel Sambuc   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1426*0a6a1f1dSLionel Sambuc     return S;
1427*0a6a1f1dSLionel Sambuc   // replace continue with goto __continue_label
1428*0a6a1f1dSLionel Sambuc   std::string buf;
1429*0a6a1f1dSLionel Sambuc 
1430*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1431*0a6a1f1dSLionel Sambuc   buf = "goto __continue_label_";
1432*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1433*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, strlen("continue"), buf);
1434*0a6a1f1dSLionel Sambuc 
1435*0a6a1f1dSLionel Sambuc   return nullptr;
1436*0a6a1f1dSLionel Sambuc }
1437*0a6a1f1dSLionel Sambuc 
1438*0a6a1f1dSLionel Sambuc /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1439*0a6a1f1dSLionel Sambuc ///  It rewrites:
1440*0a6a1f1dSLionel Sambuc /// for ( type elem in collection) { stmts; }
1441*0a6a1f1dSLionel Sambuc 
1442*0a6a1f1dSLionel Sambuc /// Into:
1443*0a6a1f1dSLionel Sambuc /// {
1444*0a6a1f1dSLionel Sambuc ///   type elem;
1445*0a6a1f1dSLionel Sambuc ///   struct __objcFastEnumerationState enumState = { 0 };
1446*0a6a1f1dSLionel Sambuc ///   id __rw_items[16];
1447*0a6a1f1dSLionel Sambuc ///   id l_collection = (id)collection;
1448*0a6a1f1dSLionel Sambuc ///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1449*0a6a1f1dSLionel Sambuc ///                                       objects:__rw_items count:16];
1450*0a6a1f1dSLionel Sambuc /// if (limit) {
1451*0a6a1f1dSLionel Sambuc ///   unsigned long startMutations = *enumState.mutationsPtr;
1452*0a6a1f1dSLionel Sambuc ///   do {
1453*0a6a1f1dSLionel Sambuc ///        unsigned long counter = 0;
1454*0a6a1f1dSLionel Sambuc ///        do {
1455*0a6a1f1dSLionel Sambuc ///             if (startMutations != *enumState.mutationsPtr)
1456*0a6a1f1dSLionel Sambuc ///               objc_enumerationMutation(l_collection);
1457*0a6a1f1dSLionel Sambuc ///             elem = (type)enumState.itemsPtr[counter++];
1458*0a6a1f1dSLionel Sambuc ///             stmts;
1459*0a6a1f1dSLionel Sambuc ///             __continue_label: ;
1460*0a6a1f1dSLionel Sambuc ///        } while (counter < limit);
1461*0a6a1f1dSLionel Sambuc ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1462*0a6a1f1dSLionel Sambuc ///                                  objects:__rw_items count:16]);
1463*0a6a1f1dSLionel Sambuc ///   elem = nil;
1464*0a6a1f1dSLionel Sambuc ///   __break_label: ;
1465*0a6a1f1dSLionel Sambuc ///  }
1466*0a6a1f1dSLionel Sambuc ///  else
1467*0a6a1f1dSLionel Sambuc ///       elem = nil;
1468*0a6a1f1dSLionel Sambuc ///  }
1469*0a6a1f1dSLionel Sambuc ///
RewriteObjCForCollectionStmt(ObjCForCollectionStmt * S,SourceLocation OrigEnd)1470*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1471*0a6a1f1dSLionel Sambuc                                                 SourceLocation OrigEnd) {
1472*0a6a1f1dSLionel Sambuc   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1473*0a6a1f1dSLionel Sambuc   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1474*0a6a1f1dSLionel Sambuc          "ObjCForCollectionStmt Statement stack mismatch");
1475*0a6a1f1dSLionel Sambuc   assert(!ObjCBcLabelNo.empty() &&
1476*0a6a1f1dSLionel Sambuc          "ObjCForCollectionStmt - Label No stack empty");
1477*0a6a1f1dSLionel Sambuc 
1478*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1479*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1480*0a6a1f1dSLionel Sambuc   StringRef elementName;
1481*0a6a1f1dSLionel Sambuc   std::string elementTypeAsString;
1482*0a6a1f1dSLionel Sambuc   std::string buf;
1483*0a6a1f1dSLionel Sambuc   buf = "\n{\n\t";
1484*0a6a1f1dSLionel Sambuc   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1485*0a6a1f1dSLionel Sambuc     // type elem;
1486*0a6a1f1dSLionel Sambuc     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1487*0a6a1f1dSLionel Sambuc     QualType ElementType = cast<ValueDecl>(D)->getType();
1488*0a6a1f1dSLionel Sambuc     if (ElementType->isObjCQualifiedIdType() ||
1489*0a6a1f1dSLionel Sambuc         ElementType->isObjCQualifiedInterfaceType())
1490*0a6a1f1dSLionel Sambuc       // Simply use 'id' for all qualified types.
1491*0a6a1f1dSLionel Sambuc       elementTypeAsString = "id";
1492*0a6a1f1dSLionel Sambuc     else
1493*0a6a1f1dSLionel Sambuc       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1494*0a6a1f1dSLionel Sambuc     buf += elementTypeAsString;
1495*0a6a1f1dSLionel Sambuc     buf += " ";
1496*0a6a1f1dSLionel Sambuc     elementName = D->getName();
1497*0a6a1f1dSLionel Sambuc     buf += elementName;
1498*0a6a1f1dSLionel Sambuc     buf += ";\n\t";
1499*0a6a1f1dSLionel Sambuc   }
1500*0a6a1f1dSLionel Sambuc   else {
1501*0a6a1f1dSLionel Sambuc     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1502*0a6a1f1dSLionel Sambuc     elementName = DR->getDecl()->getName();
1503*0a6a1f1dSLionel Sambuc     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1504*0a6a1f1dSLionel Sambuc     if (VD->getType()->isObjCQualifiedIdType() ||
1505*0a6a1f1dSLionel Sambuc         VD->getType()->isObjCQualifiedInterfaceType())
1506*0a6a1f1dSLionel Sambuc       // Simply use 'id' for all qualified types.
1507*0a6a1f1dSLionel Sambuc       elementTypeAsString = "id";
1508*0a6a1f1dSLionel Sambuc     else
1509*0a6a1f1dSLionel Sambuc       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1510*0a6a1f1dSLionel Sambuc   }
1511*0a6a1f1dSLionel Sambuc 
1512*0a6a1f1dSLionel Sambuc   // struct __objcFastEnumerationState enumState = { 0 };
1513*0a6a1f1dSLionel Sambuc   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1514*0a6a1f1dSLionel Sambuc   // id __rw_items[16];
1515*0a6a1f1dSLionel Sambuc   buf += "id __rw_items[16];\n\t";
1516*0a6a1f1dSLionel Sambuc   // id l_collection = (id)
1517*0a6a1f1dSLionel Sambuc   buf += "id l_collection = (id)";
1518*0a6a1f1dSLionel Sambuc   // Find start location of 'collection' the hard way!
1519*0a6a1f1dSLionel Sambuc   const char *startCollectionBuf = startBuf;
1520*0a6a1f1dSLionel Sambuc   startCollectionBuf += 3;  // skip 'for'
1521*0a6a1f1dSLionel Sambuc   startCollectionBuf = strchr(startCollectionBuf, '(');
1522*0a6a1f1dSLionel Sambuc   startCollectionBuf++; // skip '('
1523*0a6a1f1dSLionel Sambuc   // find 'in' and skip it.
1524*0a6a1f1dSLionel Sambuc   while (*startCollectionBuf != ' ' ||
1525*0a6a1f1dSLionel Sambuc          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1526*0a6a1f1dSLionel Sambuc          (*(startCollectionBuf+3) != ' ' &&
1527*0a6a1f1dSLionel Sambuc           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1528*0a6a1f1dSLionel Sambuc     startCollectionBuf++;
1529*0a6a1f1dSLionel Sambuc   startCollectionBuf += 3;
1530*0a6a1f1dSLionel Sambuc 
1531*0a6a1f1dSLionel Sambuc   // Replace: "for (type element in" with string constructed thus far.
1532*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1533*0a6a1f1dSLionel Sambuc   // Replace ')' in for '(' type elem in collection ')' with ';'
1534*0a6a1f1dSLionel Sambuc   SourceLocation rightParenLoc = S->getRParenLoc();
1535*0a6a1f1dSLionel Sambuc   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1536*0a6a1f1dSLionel Sambuc   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1537*0a6a1f1dSLionel Sambuc   buf = ";\n\t";
1538*0a6a1f1dSLionel Sambuc 
1539*0a6a1f1dSLionel Sambuc   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1540*0a6a1f1dSLionel Sambuc   //                                   objects:__rw_items count:16];
1541*0a6a1f1dSLionel Sambuc   // which is synthesized into:
1542*0a6a1f1dSLionel Sambuc   // unsigned int limit =
1543*0a6a1f1dSLionel Sambuc   // ((unsigned int (*)
1544*0a6a1f1dSLionel Sambuc   //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1545*0a6a1f1dSLionel Sambuc   //  (void *)objc_msgSend)((id)l_collection,
1546*0a6a1f1dSLionel Sambuc   //                        sel_registerName(
1547*0a6a1f1dSLionel Sambuc   //                          "countByEnumeratingWithState:objects:count:"),
1548*0a6a1f1dSLionel Sambuc   //                        (struct __objcFastEnumerationState *)&state,
1549*0a6a1f1dSLionel Sambuc   //                        (id *)__rw_items, (unsigned int)16);
1550*0a6a1f1dSLionel Sambuc   buf += "unsigned long limit =\n\t\t";
1551*0a6a1f1dSLionel Sambuc   SynthCountByEnumWithState(buf);
1552*0a6a1f1dSLionel Sambuc   buf += ";\n\t";
1553*0a6a1f1dSLionel Sambuc   /// if (limit) {
1554*0a6a1f1dSLionel Sambuc   ///   unsigned long startMutations = *enumState.mutationsPtr;
1555*0a6a1f1dSLionel Sambuc   ///   do {
1556*0a6a1f1dSLionel Sambuc   ///        unsigned long counter = 0;
1557*0a6a1f1dSLionel Sambuc   ///        do {
1558*0a6a1f1dSLionel Sambuc   ///             if (startMutations != *enumState.mutationsPtr)
1559*0a6a1f1dSLionel Sambuc   ///               objc_enumerationMutation(l_collection);
1560*0a6a1f1dSLionel Sambuc   ///             elem = (type)enumState.itemsPtr[counter++];
1561*0a6a1f1dSLionel Sambuc   buf += "if (limit) {\n\t";
1562*0a6a1f1dSLionel Sambuc   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1563*0a6a1f1dSLionel Sambuc   buf += "do {\n\t\t";
1564*0a6a1f1dSLionel Sambuc   buf += "unsigned long counter = 0;\n\t\t";
1565*0a6a1f1dSLionel Sambuc   buf += "do {\n\t\t\t";
1566*0a6a1f1dSLionel Sambuc   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1567*0a6a1f1dSLionel Sambuc   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1568*0a6a1f1dSLionel Sambuc   buf += elementName;
1569*0a6a1f1dSLionel Sambuc   buf += " = (";
1570*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1571*0a6a1f1dSLionel Sambuc   buf += ")enumState.itemsPtr[counter++];";
1572*0a6a1f1dSLionel Sambuc   // Replace ')' in for '(' type elem in collection ')' with all of these.
1573*0a6a1f1dSLionel Sambuc   ReplaceText(lparenLoc, 1, buf);
1574*0a6a1f1dSLionel Sambuc 
1575*0a6a1f1dSLionel Sambuc   ///            __continue_label: ;
1576*0a6a1f1dSLionel Sambuc   ///        } while (counter < limit);
1577*0a6a1f1dSLionel Sambuc   ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1578*0a6a1f1dSLionel Sambuc   ///                                  objects:__rw_items count:16]);
1579*0a6a1f1dSLionel Sambuc   ///   elem = nil;
1580*0a6a1f1dSLionel Sambuc   ///   __break_label: ;
1581*0a6a1f1dSLionel Sambuc   ///  }
1582*0a6a1f1dSLionel Sambuc   ///  else
1583*0a6a1f1dSLionel Sambuc   ///       elem = nil;
1584*0a6a1f1dSLionel Sambuc   ///  }
1585*0a6a1f1dSLionel Sambuc   ///
1586*0a6a1f1dSLionel Sambuc   buf = ";\n\t";
1587*0a6a1f1dSLionel Sambuc   buf += "__continue_label_";
1588*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1589*0a6a1f1dSLionel Sambuc   buf += ": ;";
1590*0a6a1f1dSLionel Sambuc   buf += "\n\t\t";
1591*0a6a1f1dSLionel Sambuc   buf += "} while (counter < limit);\n\t";
1592*0a6a1f1dSLionel Sambuc   buf += "} while (limit = ";
1593*0a6a1f1dSLionel Sambuc   SynthCountByEnumWithState(buf);
1594*0a6a1f1dSLionel Sambuc   buf += ");\n\t";
1595*0a6a1f1dSLionel Sambuc   buf += elementName;
1596*0a6a1f1dSLionel Sambuc   buf += " = ((";
1597*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1598*0a6a1f1dSLionel Sambuc   buf += ")0);\n\t";
1599*0a6a1f1dSLionel Sambuc   buf += "__break_label_";
1600*0a6a1f1dSLionel Sambuc   buf += utostr(ObjCBcLabelNo.back());
1601*0a6a1f1dSLionel Sambuc   buf += ": ;\n\t";
1602*0a6a1f1dSLionel Sambuc   buf += "}\n\t";
1603*0a6a1f1dSLionel Sambuc   buf += "else\n\t\t";
1604*0a6a1f1dSLionel Sambuc   buf += elementName;
1605*0a6a1f1dSLionel Sambuc   buf += " = ((";
1606*0a6a1f1dSLionel Sambuc   buf += elementTypeAsString;
1607*0a6a1f1dSLionel Sambuc   buf += ")0);\n\t";
1608*0a6a1f1dSLionel Sambuc   buf += "}\n";
1609*0a6a1f1dSLionel Sambuc 
1610*0a6a1f1dSLionel Sambuc   // Insert all these *after* the statement body.
1611*0a6a1f1dSLionel Sambuc   // FIXME: If this should support Obj-C++, support CXXTryStmt
1612*0a6a1f1dSLionel Sambuc   if (isa<CompoundStmt>(S->getBody())) {
1613*0a6a1f1dSLionel Sambuc     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1614*0a6a1f1dSLionel Sambuc     InsertText(endBodyLoc, buf);
1615*0a6a1f1dSLionel Sambuc   } else {
1616*0a6a1f1dSLionel Sambuc     /* Need to treat single statements specially. For example:
1617*0a6a1f1dSLionel Sambuc      *
1618*0a6a1f1dSLionel Sambuc      *     for (A *a in b) if (stuff()) break;
1619*0a6a1f1dSLionel Sambuc      *     for (A *a in b) xxxyy;
1620*0a6a1f1dSLionel Sambuc      *
1621*0a6a1f1dSLionel Sambuc      * The following code simply scans ahead to the semi to find the actual end.
1622*0a6a1f1dSLionel Sambuc      */
1623*0a6a1f1dSLionel Sambuc     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1624*0a6a1f1dSLionel Sambuc     const char *semiBuf = strchr(stmtBuf, ';');
1625*0a6a1f1dSLionel Sambuc     assert(semiBuf && "Can't find ';'");
1626*0a6a1f1dSLionel Sambuc     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1627*0a6a1f1dSLionel Sambuc     InsertText(endBodyLoc, buf);
1628*0a6a1f1dSLionel Sambuc   }
1629*0a6a1f1dSLionel Sambuc   Stmts.pop_back();
1630*0a6a1f1dSLionel Sambuc   ObjCBcLabelNo.pop_back();
1631*0a6a1f1dSLionel Sambuc   return nullptr;
1632*0a6a1f1dSLionel Sambuc }
1633*0a6a1f1dSLionel Sambuc 
1634*0a6a1f1dSLionel Sambuc /// RewriteObjCSynchronizedStmt -
1635*0a6a1f1dSLionel Sambuc /// This routine rewrites @synchronized(expr) stmt;
1636*0a6a1f1dSLionel Sambuc /// into:
1637*0a6a1f1dSLionel Sambuc /// objc_sync_enter(expr);
1638*0a6a1f1dSLionel Sambuc /// @try stmt @finally { objc_sync_exit(expr); }
1639*0a6a1f1dSLionel Sambuc ///
RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt * S)1640*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1641*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
1642*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1643*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1644*0a6a1f1dSLionel Sambuc 
1645*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @synchronized location");
1646*0a6a1f1dSLionel Sambuc 
1647*0a6a1f1dSLionel Sambuc   std::string buf;
1648*0a6a1f1dSLionel Sambuc   buf = "objc_sync_enter((id)";
1649*0a6a1f1dSLionel Sambuc   const char *lparenBuf = startBuf;
1650*0a6a1f1dSLionel Sambuc   while (*lparenBuf != '(') lparenBuf++;
1651*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1652*0a6a1f1dSLionel Sambuc   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1653*0a6a1f1dSLionel Sambuc   // the sync expression is typically a message expression that's already
1654*0a6a1f1dSLionel Sambuc   // been rewritten! (which implies the SourceLocation's are invalid).
1655*0a6a1f1dSLionel Sambuc   SourceLocation endLoc = S->getSynchBody()->getLocStart();
1656*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(endLoc);
1657*0a6a1f1dSLionel Sambuc   while (*endBuf != ')') endBuf--;
1658*0a6a1f1dSLionel Sambuc   SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1659*0a6a1f1dSLionel Sambuc   buf = ");\n";
1660*0a6a1f1dSLionel Sambuc   // declare a new scope with two variables, _stack and _rethrow.
1661*0a6a1f1dSLionel Sambuc   buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1662*0a6a1f1dSLionel Sambuc   buf += "int buf[18/*32-bit i386*/];\n";
1663*0a6a1f1dSLionel Sambuc   buf += "char *pointers[4];} _stack;\n";
1664*0a6a1f1dSLionel Sambuc   buf += "id volatile _rethrow = 0;\n";
1665*0a6a1f1dSLionel Sambuc   buf += "objc_exception_try_enter(&_stack);\n";
1666*0a6a1f1dSLionel Sambuc   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1667*0a6a1f1dSLionel Sambuc   ReplaceText(rparenLoc, 1, buf);
1668*0a6a1f1dSLionel Sambuc   startLoc = S->getSynchBody()->getLocEnd();
1669*0a6a1f1dSLionel Sambuc   startBuf = SM->getCharacterData(startLoc);
1670*0a6a1f1dSLionel Sambuc 
1671*0a6a1f1dSLionel Sambuc   assert((*startBuf == '}') && "bogus @synchronized block");
1672*0a6a1f1dSLionel Sambuc   SourceLocation lastCurlyLoc = startLoc;
1673*0a6a1f1dSLionel Sambuc   buf = "}\nelse {\n";
1674*0a6a1f1dSLionel Sambuc   buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1675*0a6a1f1dSLionel Sambuc   buf += "}\n";
1676*0a6a1f1dSLionel Sambuc   buf += "{ /* implicit finally clause */\n";
1677*0a6a1f1dSLionel Sambuc   buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1678*0a6a1f1dSLionel Sambuc 
1679*0a6a1f1dSLionel Sambuc   std::string syncBuf;
1680*0a6a1f1dSLionel Sambuc   syncBuf += " objc_sync_exit(";
1681*0a6a1f1dSLionel Sambuc 
1682*0a6a1f1dSLionel Sambuc   Expr *syncExpr = S->getSynchExpr();
1683*0a6a1f1dSLionel Sambuc   CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1684*0a6a1f1dSLionel Sambuc                   ? CK_BitCast :
1685*0a6a1f1dSLionel Sambuc                 syncExpr->getType()->isBlockPointerType()
1686*0a6a1f1dSLionel Sambuc                   ? CK_BlockPointerToObjCPointerCast
1687*0a6a1f1dSLionel Sambuc                   : CK_CPointerToObjCPointerCast;
1688*0a6a1f1dSLionel Sambuc   syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1689*0a6a1f1dSLionel Sambuc                                       CK, syncExpr);
1690*0a6a1f1dSLionel Sambuc   std::string syncExprBufS;
1691*0a6a1f1dSLionel Sambuc   llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1692*0a6a1f1dSLionel Sambuc   assert(syncExpr != nullptr && "Expected non-null Expr");
1693*0a6a1f1dSLionel Sambuc   syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1694*0a6a1f1dSLionel Sambuc   syncBuf += syncExprBuf.str();
1695*0a6a1f1dSLionel Sambuc   syncBuf += ");";
1696*0a6a1f1dSLionel Sambuc 
1697*0a6a1f1dSLionel Sambuc   buf += syncBuf;
1698*0a6a1f1dSLionel Sambuc   buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1699*0a6a1f1dSLionel Sambuc   buf += "}\n";
1700*0a6a1f1dSLionel Sambuc   buf += "}";
1701*0a6a1f1dSLionel Sambuc 
1702*0a6a1f1dSLionel Sambuc   ReplaceText(lastCurlyLoc, 1, buf);
1703*0a6a1f1dSLionel Sambuc 
1704*0a6a1f1dSLionel Sambuc   bool hasReturns = false;
1705*0a6a1f1dSLionel Sambuc   HasReturnStmts(S->getSynchBody(), hasReturns);
1706*0a6a1f1dSLionel Sambuc   if (hasReturns)
1707*0a6a1f1dSLionel Sambuc     RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1708*0a6a1f1dSLionel Sambuc 
1709*0a6a1f1dSLionel Sambuc   return nullptr;
1710*0a6a1f1dSLionel Sambuc }
1711*0a6a1f1dSLionel Sambuc 
WarnAboutReturnGotoStmts(Stmt * S)1712*0a6a1f1dSLionel Sambuc void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1713*0a6a1f1dSLionel Sambuc {
1714*0a6a1f1dSLionel Sambuc   // Perform a bottom up traversal of all children.
1715*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
1716*0a6a1f1dSLionel Sambuc     if (*CI)
1717*0a6a1f1dSLionel Sambuc       WarnAboutReturnGotoStmts(*CI);
1718*0a6a1f1dSLionel Sambuc 
1719*0a6a1f1dSLionel Sambuc   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1720*0a6a1f1dSLionel Sambuc     Diags.Report(Context->getFullLoc(S->getLocStart()),
1721*0a6a1f1dSLionel Sambuc                  TryFinallyContainsReturnDiag);
1722*0a6a1f1dSLionel Sambuc   }
1723*0a6a1f1dSLionel Sambuc   return;
1724*0a6a1f1dSLionel Sambuc }
1725*0a6a1f1dSLionel Sambuc 
HasReturnStmts(Stmt * S,bool & hasReturns)1726*0a6a1f1dSLionel Sambuc void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1727*0a6a1f1dSLionel Sambuc {
1728*0a6a1f1dSLionel Sambuc   // Perform a bottom up traversal of all children.
1729*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
1730*0a6a1f1dSLionel Sambuc    if (*CI)
1731*0a6a1f1dSLionel Sambuc      HasReturnStmts(*CI, hasReturns);
1732*0a6a1f1dSLionel Sambuc 
1733*0a6a1f1dSLionel Sambuc  if (isa<ReturnStmt>(S))
1734*0a6a1f1dSLionel Sambuc    hasReturns = true;
1735*0a6a1f1dSLionel Sambuc  return;
1736*0a6a1f1dSLionel Sambuc }
1737*0a6a1f1dSLionel Sambuc 
RewriteTryReturnStmts(Stmt * S)1738*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739*0a6a1f1dSLionel Sambuc  // Perform a bottom up traversal of all children.
1740*0a6a1f1dSLionel Sambuc  for (Stmt::child_range CI = S->children(); CI; ++CI)
1741*0a6a1f1dSLionel Sambuc    if (*CI) {
1742*0a6a1f1dSLionel Sambuc      RewriteTryReturnStmts(*CI);
1743*0a6a1f1dSLionel Sambuc    }
1744*0a6a1f1dSLionel Sambuc  if (isa<ReturnStmt>(S)) {
1745*0a6a1f1dSLionel Sambuc    SourceLocation startLoc = S->getLocStart();
1746*0a6a1f1dSLionel Sambuc    const char *startBuf = SM->getCharacterData(startLoc);
1747*0a6a1f1dSLionel Sambuc 
1748*0a6a1f1dSLionel Sambuc    const char *semiBuf = strchr(startBuf, ';');
1749*0a6a1f1dSLionel Sambuc    assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1750*0a6a1f1dSLionel Sambuc    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1751*0a6a1f1dSLionel Sambuc 
1752*0a6a1f1dSLionel Sambuc    std::string buf;
1753*0a6a1f1dSLionel Sambuc    buf = "{ objc_exception_try_exit(&_stack); return";
1754*0a6a1f1dSLionel Sambuc 
1755*0a6a1f1dSLionel Sambuc    ReplaceText(startLoc, 6, buf);
1756*0a6a1f1dSLionel Sambuc    InsertText(onePastSemiLoc, "}");
1757*0a6a1f1dSLionel Sambuc  }
1758*0a6a1f1dSLionel Sambuc  return;
1759*0a6a1f1dSLionel Sambuc }
1760*0a6a1f1dSLionel Sambuc 
RewriteSyncReturnStmts(Stmt * S,std::string syncExitBuf)1761*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1762*0a6a1f1dSLionel Sambuc   // Perform a bottom up traversal of all children.
1763*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
1764*0a6a1f1dSLionel Sambuc     if (*CI) {
1765*0a6a1f1dSLionel Sambuc       RewriteSyncReturnStmts(*CI, syncExitBuf);
1766*0a6a1f1dSLionel Sambuc     }
1767*0a6a1f1dSLionel Sambuc   if (isa<ReturnStmt>(S)) {
1768*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = S->getLocStart();
1769*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
1770*0a6a1f1dSLionel Sambuc 
1771*0a6a1f1dSLionel Sambuc     const char *semiBuf = strchr(startBuf, ';');
1772*0a6a1f1dSLionel Sambuc     assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1773*0a6a1f1dSLionel Sambuc     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1774*0a6a1f1dSLionel Sambuc 
1775*0a6a1f1dSLionel Sambuc     std::string buf;
1776*0a6a1f1dSLionel Sambuc     buf = "{ objc_exception_try_exit(&_stack);";
1777*0a6a1f1dSLionel Sambuc     buf += syncExitBuf;
1778*0a6a1f1dSLionel Sambuc     buf += " return";
1779*0a6a1f1dSLionel Sambuc 
1780*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, 6, buf);
1781*0a6a1f1dSLionel Sambuc     InsertText(onePastSemiLoc, "}");
1782*0a6a1f1dSLionel Sambuc   }
1783*0a6a1f1dSLionel Sambuc   return;
1784*0a6a1f1dSLionel Sambuc }
1785*0a6a1f1dSLionel Sambuc 
RewriteObjCTryStmt(ObjCAtTryStmt * S)1786*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1787*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
1788*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1789*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1790*0a6a1f1dSLionel Sambuc 
1791*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @try location");
1792*0a6a1f1dSLionel Sambuc 
1793*0a6a1f1dSLionel Sambuc   std::string buf;
1794*0a6a1f1dSLionel Sambuc   // declare a new scope with two variables, _stack and _rethrow.
1795*0a6a1f1dSLionel Sambuc   buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1796*0a6a1f1dSLionel Sambuc   buf += "int buf[18/*32-bit i386*/];\n";
1797*0a6a1f1dSLionel Sambuc   buf += "char *pointers[4];} _stack;\n";
1798*0a6a1f1dSLionel Sambuc   buf += "id volatile _rethrow = 0;\n";
1799*0a6a1f1dSLionel Sambuc   buf += "objc_exception_try_enter(&_stack);\n";
1800*0a6a1f1dSLionel Sambuc   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1801*0a6a1f1dSLionel Sambuc 
1802*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, 4, buf);
1803*0a6a1f1dSLionel Sambuc 
1804*0a6a1f1dSLionel Sambuc   startLoc = S->getTryBody()->getLocEnd();
1805*0a6a1f1dSLionel Sambuc   startBuf = SM->getCharacterData(startLoc);
1806*0a6a1f1dSLionel Sambuc 
1807*0a6a1f1dSLionel Sambuc   assert((*startBuf == '}') && "bogus @try block");
1808*0a6a1f1dSLionel Sambuc 
1809*0a6a1f1dSLionel Sambuc   SourceLocation lastCurlyLoc = startLoc;
1810*0a6a1f1dSLionel Sambuc   if (S->getNumCatchStmts()) {
1811*0a6a1f1dSLionel Sambuc     startLoc = startLoc.getLocWithOffset(1);
1812*0a6a1f1dSLionel Sambuc     buf = " /* @catch begin */ else {\n";
1813*0a6a1f1dSLionel Sambuc     buf += " id _caught = objc_exception_extract(&_stack);\n";
1814*0a6a1f1dSLionel Sambuc     buf += " objc_exception_try_enter (&_stack);\n";
1815*0a6a1f1dSLionel Sambuc     buf += " if (_setjmp(_stack.buf))\n";
1816*0a6a1f1dSLionel Sambuc     buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1817*0a6a1f1dSLionel Sambuc     buf += " else { /* @catch continue */";
1818*0a6a1f1dSLionel Sambuc 
1819*0a6a1f1dSLionel Sambuc     InsertText(startLoc, buf);
1820*0a6a1f1dSLionel Sambuc   } else { /* no catch list */
1821*0a6a1f1dSLionel Sambuc     buf = "}\nelse {\n";
1822*0a6a1f1dSLionel Sambuc     buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1823*0a6a1f1dSLionel Sambuc     buf += "}";
1824*0a6a1f1dSLionel Sambuc     ReplaceText(lastCurlyLoc, 1, buf);
1825*0a6a1f1dSLionel Sambuc   }
1826*0a6a1f1dSLionel Sambuc   Stmt *lastCatchBody = nullptr;
1827*0a6a1f1dSLionel Sambuc   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1828*0a6a1f1dSLionel Sambuc     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1829*0a6a1f1dSLionel Sambuc     VarDecl *catchDecl = Catch->getCatchParamDecl();
1830*0a6a1f1dSLionel Sambuc 
1831*0a6a1f1dSLionel Sambuc     if (I == 0)
1832*0a6a1f1dSLionel Sambuc       buf = "if ("; // we are generating code for the first catch clause
1833*0a6a1f1dSLionel Sambuc     else
1834*0a6a1f1dSLionel Sambuc       buf = "else if (";
1835*0a6a1f1dSLionel Sambuc     startLoc = Catch->getLocStart();
1836*0a6a1f1dSLionel Sambuc     startBuf = SM->getCharacterData(startLoc);
1837*0a6a1f1dSLionel Sambuc 
1838*0a6a1f1dSLionel Sambuc     assert((*startBuf == '@') && "bogus @catch location");
1839*0a6a1f1dSLionel Sambuc 
1840*0a6a1f1dSLionel Sambuc     const char *lParenLoc = strchr(startBuf, '(');
1841*0a6a1f1dSLionel Sambuc 
1842*0a6a1f1dSLionel Sambuc     if (Catch->hasEllipsis()) {
1843*0a6a1f1dSLionel Sambuc       // Now rewrite the body...
1844*0a6a1f1dSLionel Sambuc       lastCatchBody = Catch->getCatchBody();
1845*0a6a1f1dSLionel Sambuc       SourceLocation bodyLoc = lastCatchBody->getLocStart();
1846*0a6a1f1dSLionel Sambuc       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1847*0a6a1f1dSLionel Sambuc       assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1848*0a6a1f1dSLionel Sambuc              "bogus @catch paren location");
1849*0a6a1f1dSLionel Sambuc       assert((*bodyBuf == '{') && "bogus @catch body location");
1850*0a6a1f1dSLionel Sambuc 
1851*0a6a1f1dSLionel Sambuc       buf += "1) { id _tmp = _caught;";
1852*0a6a1f1dSLionel Sambuc       Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1853*0a6a1f1dSLionel Sambuc     } else if (catchDecl) {
1854*0a6a1f1dSLionel Sambuc       QualType t = catchDecl->getType();
1855*0a6a1f1dSLionel Sambuc       if (t == Context->getObjCIdType()) {
1856*0a6a1f1dSLionel Sambuc         buf += "1) { ";
1857*0a6a1f1dSLionel Sambuc         ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1858*0a6a1f1dSLionel Sambuc       } else if (const ObjCObjectPointerType *Ptr =
1859*0a6a1f1dSLionel Sambuc                    t->getAs<ObjCObjectPointerType>()) {
1860*0a6a1f1dSLionel Sambuc         // Should be a pointer to a class.
1861*0a6a1f1dSLionel Sambuc         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1862*0a6a1f1dSLionel Sambuc         if (IDecl) {
1863*0a6a1f1dSLionel Sambuc           buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1864*0a6a1f1dSLionel Sambuc           buf += IDecl->getNameAsString();
1865*0a6a1f1dSLionel Sambuc           buf += "\"), (struct objc_object *)_caught)) { ";
1866*0a6a1f1dSLionel Sambuc           ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1867*0a6a1f1dSLionel Sambuc         }
1868*0a6a1f1dSLionel Sambuc       }
1869*0a6a1f1dSLionel Sambuc       // Now rewrite the body...
1870*0a6a1f1dSLionel Sambuc       lastCatchBody = Catch->getCatchBody();
1871*0a6a1f1dSLionel Sambuc       SourceLocation rParenLoc = Catch->getRParenLoc();
1872*0a6a1f1dSLionel Sambuc       SourceLocation bodyLoc = lastCatchBody->getLocStart();
1873*0a6a1f1dSLionel Sambuc       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1874*0a6a1f1dSLionel Sambuc       const char *rParenBuf = SM->getCharacterData(rParenLoc);
1875*0a6a1f1dSLionel Sambuc       assert((*rParenBuf == ')') && "bogus @catch paren location");
1876*0a6a1f1dSLionel Sambuc       assert((*bodyBuf == '{') && "bogus @catch body location");
1877*0a6a1f1dSLionel Sambuc 
1878*0a6a1f1dSLionel Sambuc       // Here we replace ") {" with "= _caught;" (which initializes and
1879*0a6a1f1dSLionel Sambuc       // declares the @catch parameter).
1880*0a6a1f1dSLionel Sambuc       ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1881*0a6a1f1dSLionel Sambuc     } else {
1882*0a6a1f1dSLionel Sambuc       llvm_unreachable("@catch rewrite bug");
1883*0a6a1f1dSLionel Sambuc     }
1884*0a6a1f1dSLionel Sambuc   }
1885*0a6a1f1dSLionel Sambuc   // Complete the catch list...
1886*0a6a1f1dSLionel Sambuc   if (lastCatchBody) {
1887*0a6a1f1dSLionel Sambuc     SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1888*0a6a1f1dSLionel Sambuc     assert(*SM->getCharacterData(bodyLoc) == '}' &&
1889*0a6a1f1dSLionel Sambuc            "bogus @catch body location");
1890*0a6a1f1dSLionel Sambuc 
1891*0a6a1f1dSLionel Sambuc     // Insert the last (implicit) else clause *before* the right curly brace.
1892*0a6a1f1dSLionel Sambuc     bodyLoc = bodyLoc.getLocWithOffset(-1);
1893*0a6a1f1dSLionel Sambuc     buf = "} /* last catch end */\n";
1894*0a6a1f1dSLionel Sambuc     buf += "else {\n";
1895*0a6a1f1dSLionel Sambuc     buf += " _rethrow = _caught;\n";
1896*0a6a1f1dSLionel Sambuc     buf += " objc_exception_try_exit(&_stack);\n";
1897*0a6a1f1dSLionel Sambuc     buf += "} } /* @catch end */\n";
1898*0a6a1f1dSLionel Sambuc     if (!S->getFinallyStmt())
1899*0a6a1f1dSLionel Sambuc       buf += "}\n";
1900*0a6a1f1dSLionel Sambuc     InsertText(bodyLoc, buf);
1901*0a6a1f1dSLionel Sambuc 
1902*0a6a1f1dSLionel Sambuc     // Set lastCurlyLoc
1903*0a6a1f1dSLionel Sambuc     lastCurlyLoc = lastCatchBody->getLocEnd();
1904*0a6a1f1dSLionel Sambuc   }
1905*0a6a1f1dSLionel Sambuc   if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1906*0a6a1f1dSLionel Sambuc     startLoc = finalStmt->getLocStart();
1907*0a6a1f1dSLionel Sambuc     startBuf = SM->getCharacterData(startLoc);
1908*0a6a1f1dSLionel Sambuc     assert((*startBuf == '@') && "bogus @finally start");
1909*0a6a1f1dSLionel Sambuc 
1910*0a6a1f1dSLionel Sambuc     ReplaceText(startLoc, 8, "/* @finally */");
1911*0a6a1f1dSLionel Sambuc 
1912*0a6a1f1dSLionel Sambuc     Stmt *body = finalStmt->getFinallyBody();
1913*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = body->getLocStart();
1914*0a6a1f1dSLionel Sambuc     SourceLocation endLoc = body->getLocEnd();
1915*0a6a1f1dSLionel Sambuc     assert(*SM->getCharacterData(startLoc) == '{' &&
1916*0a6a1f1dSLionel Sambuc            "bogus @finally body location");
1917*0a6a1f1dSLionel Sambuc     assert(*SM->getCharacterData(endLoc) == '}' &&
1918*0a6a1f1dSLionel Sambuc            "bogus @finally body location");
1919*0a6a1f1dSLionel Sambuc 
1920*0a6a1f1dSLionel Sambuc     startLoc = startLoc.getLocWithOffset(1);
1921*0a6a1f1dSLionel Sambuc     InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1922*0a6a1f1dSLionel Sambuc     endLoc = endLoc.getLocWithOffset(-1);
1923*0a6a1f1dSLionel Sambuc     InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1924*0a6a1f1dSLionel Sambuc 
1925*0a6a1f1dSLionel Sambuc     // Set lastCurlyLoc
1926*0a6a1f1dSLionel Sambuc     lastCurlyLoc = body->getLocEnd();
1927*0a6a1f1dSLionel Sambuc 
1928*0a6a1f1dSLionel Sambuc     // Now check for any return/continue/go statements within the @try.
1929*0a6a1f1dSLionel Sambuc     WarnAboutReturnGotoStmts(S->getTryBody());
1930*0a6a1f1dSLionel Sambuc   } else { /* no finally clause - make sure we synthesize an implicit one */
1931*0a6a1f1dSLionel Sambuc     buf = "{ /* implicit finally clause */\n";
1932*0a6a1f1dSLionel Sambuc     buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1933*0a6a1f1dSLionel Sambuc     buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1934*0a6a1f1dSLionel Sambuc     buf += "}";
1935*0a6a1f1dSLionel Sambuc     ReplaceText(lastCurlyLoc, 1, buf);
1936*0a6a1f1dSLionel Sambuc 
1937*0a6a1f1dSLionel Sambuc     // Now check for any return/continue/go statements within the @try.
1938*0a6a1f1dSLionel Sambuc     // The implicit finally clause won't called if the @try contains any
1939*0a6a1f1dSLionel Sambuc     // jump statements.
1940*0a6a1f1dSLionel Sambuc     bool hasReturns = false;
1941*0a6a1f1dSLionel Sambuc     HasReturnStmts(S->getTryBody(), hasReturns);
1942*0a6a1f1dSLionel Sambuc     if (hasReturns)
1943*0a6a1f1dSLionel Sambuc       RewriteTryReturnStmts(S->getTryBody());
1944*0a6a1f1dSLionel Sambuc   }
1945*0a6a1f1dSLionel Sambuc   // Now emit the final closing curly brace...
1946*0a6a1f1dSLionel Sambuc   lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1947*0a6a1f1dSLionel Sambuc   InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1948*0a6a1f1dSLionel Sambuc   return nullptr;
1949*0a6a1f1dSLionel Sambuc }
1950*0a6a1f1dSLionel Sambuc 
1951*0a6a1f1dSLionel Sambuc // This can't be done with ReplaceStmt(S, ThrowExpr), since
1952*0a6a1f1dSLionel Sambuc // the throw expression is typically a message expression that's already
1953*0a6a1f1dSLionel Sambuc // been rewritten! (which implies the SourceLocation's are invalid).
RewriteObjCThrowStmt(ObjCAtThrowStmt * S)1954*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1955*0a6a1f1dSLionel Sambuc   // Get the start location and compute the semi location.
1956*0a6a1f1dSLionel Sambuc   SourceLocation startLoc = S->getLocStart();
1957*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(startLoc);
1958*0a6a1f1dSLionel Sambuc 
1959*0a6a1f1dSLionel Sambuc   assert((*startBuf == '@') && "bogus @throw location");
1960*0a6a1f1dSLionel Sambuc 
1961*0a6a1f1dSLionel Sambuc   std::string buf;
1962*0a6a1f1dSLionel Sambuc   /* void objc_exception_throw(id) __attribute__((noreturn)); */
1963*0a6a1f1dSLionel Sambuc   if (S->getThrowExpr())
1964*0a6a1f1dSLionel Sambuc     buf = "objc_exception_throw(";
1965*0a6a1f1dSLionel Sambuc   else // add an implicit argument
1966*0a6a1f1dSLionel Sambuc     buf = "objc_exception_throw(_caught";
1967*0a6a1f1dSLionel Sambuc 
1968*0a6a1f1dSLionel Sambuc   // handle "@  throw" correctly.
1969*0a6a1f1dSLionel Sambuc   const char *wBuf = strchr(startBuf, 'w');
1970*0a6a1f1dSLionel Sambuc   assert((*wBuf == 'w') && "@throw: can't find 'w'");
1971*0a6a1f1dSLionel Sambuc   ReplaceText(startLoc, wBuf-startBuf+1, buf);
1972*0a6a1f1dSLionel Sambuc 
1973*0a6a1f1dSLionel Sambuc   const char *semiBuf = strchr(startBuf, ';');
1974*0a6a1f1dSLionel Sambuc   assert((*semiBuf == ';') && "@throw: can't find ';'");
1975*0a6a1f1dSLionel Sambuc   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1976*0a6a1f1dSLionel Sambuc   ReplaceText(semiLoc, 1, ");");
1977*0a6a1f1dSLionel Sambuc   return nullptr;
1978*0a6a1f1dSLionel Sambuc }
1979*0a6a1f1dSLionel Sambuc 
RewriteAtEncode(ObjCEncodeExpr * Exp)1980*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1981*0a6a1f1dSLionel Sambuc   // Create a new string expression.
1982*0a6a1f1dSLionel Sambuc   std::string StrEncoding;
1983*0a6a1f1dSLionel Sambuc   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1984*0a6a1f1dSLionel Sambuc   Expr *Replacement = getStringLiteral(StrEncoding);
1985*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, Replacement);
1986*0a6a1f1dSLionel Sambuc 
1987*0a6a1f1dSLionel Sambuc   // Replace this subexpr in the parent.
1988*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1989*0a6a1f1dSLionel Sambuc   return Replacement;
1990*0a6a1f1dSLionel Sambuc }
1991*0a6a1f1dSLionel Sambuc 
RewriteAtSelector(ObjCSelectorExpr * Exp)1992*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1993*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
1994*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
1995*0a6a1f1dSLionel Sambuc   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1996*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("selName").
1997*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> SelExprs;
1998*0a6a1f1dSLionel Sambuc   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
1999*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2000*0a6a1f1dSLionel Sambuc                                                  &SelExprs[0], SelExprs.size());
2001*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, SelExp);
2002*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2003*0a6a1f1dSLionel Sambuc   return SelExp;
2004*0a6a1f1dSLionel Sambuc }
2005*0a6a1f1dSLionel Sambuc 
SynthesizeCallToFunctionDecl(FunctionDecl * FD,Expr ** args,unsigned nargs,SourceLocation StartLoc,SourceLocation EndLoc)2006*0a6a1f1dSLionel Sambuc CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
2007*0a6a1f1dSLionel Sambuc   FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2008*0a6a1f1dSLionel Sambuc                                                     SourceLocation EndLoc) {
2009*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2010*0a6a1f1dSLionel Sambuc   QualType msgSendType = FD->getType();
2011*0a6a1f1dSLionel Sambuc 
2012*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2013*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2014*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
2015*0a6a1f1dSLionel Sambuc 
2016*0a6a1f1dSLionel Sambuc   // Now, we cast the reference to a pointer to the objc_msgSend type.
2017*0a6a1f1dSLionel Sambuc   QualType pToFunc = Context->getPointerType(msgSendType);
2018*0a6a1f1dSLionel Sambuc   ImplicitCastExpr *ICE =
2019*0a6a1f1dSLionel Sambuc     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2020*0a6a1f1dSLionel Sambuc                              DRE, nullptr, VK_RValue);
2021*0a6a1f1dSLionel Sambuc 
2022*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2023*0a6a1f1dSLionel Sambuc 
2024*0a6a1f1dSLionel Sambuc   CallExpr *Exp =
2025*0a6a1f1dSLionel Sambuc     new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
2026*0a6a1f1dSLionel Sambuc                            FT->getCallResultType(*Context),
2027*0a6a1f1dSLionel Sambuc                            VK_RValue, EndLoc);
2028*0a6a1f1dSLionel Sambuc   return Exp;
2029*0a6a1f1dSLionel Sambuc }
2030*0a6a1f1dSLionel Sambuc 
scanForProtocolRefs(const char * startBuf,const char * endBuf,const char * & startRef,const char * & endRef)2031*0a6a1f1dSLionel Sambuc static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2032*0a6a1f1dSLionel Sambuc                                 const char *&startRef, const char *&endRef) {
2033*0a6a1f1dSLionel Sambuc   while (startBuf < endBuf) {
2034*0a6a1f1dSLionel Sambuc     if (*startBuf == '<')
2035*0a6a1f1dSLionel Sambuc       startRef = startBuf; // mark the start.
2036*0a6a1f1dSLionel Sambuc     if (*startBuf == '>') {
2037*0a6a1f1dSLionel Sambuc       if (startRef && *startRef == '<') {
2038*0a6a1f1dSLionel Sambuc         endRef = startBuf; // mark the end.
2039*0a6a1f1dSLionel Sambuc         return true;
2040*0a6a1f1dSLionel Sambuc       }
2041*0a6a1f1dSLionel Sambuc       return false;
2042*0a6a1f1dSLionel Sambuc     }
2043*0a6a1f1dSLionel Sambuc     startBuf++;
2044*0a6a1f1dSLionel Sambuc   }
2045*0a6a1f1dSLionel Sambuc   return false;
2046*0a6a1f1dSLionel Sambuc }
2047*0a6a1f1dSLionel Sambuc 
scanToNextArgument(const char * & argRef)2048*0a6a1f1dSLionel Sambuc static void scanToNextArgument(const char *&argRef) {
2049*0a6a1f1dSLionel Sambuc   int angle = 0;
2050*0a6a1f1dSLionel Sambuc   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2051*0a6a1f1dSLionel Sambuc     if (*argRef == '<')
2052*0a6a1f1dSLionel Sambuc       angle++;
2053*0a6a1f1dSLionel Sambuc     else if (*argRef == '>')
2054*0a6a1f1dSLionel Sambuc       angle--;
2055*0a6a1f1dSLionel Sambuc     argRef++;
2056*0a6a1f1dSLionel Sambuc   }
2057*0a6a1f1dSLionel Sambuc   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2058*0a6a1f1dSLionel Sambuc }
2059*0a6a1f1dSLionel Sambuc 
needToScanForQualifiers(QualType T)2060*0a6a1f1dSLionel Sambuc bool RewriteObjC::needToScanForQualifiers(QualType T) {
2061*0a6a1f1dSLionel Sambuc   if (T->isObjCQualifiedIdType())
2062*0a6a1f1dSLionel Sambuc     return true;
2063*0a6a1f1dSLionel Sambuc   if (const PointerType *PT = T->getAs<PointerType>()) {
2064*0a6a1f1dSLionel Sambuc     if (PT->getPointeeType()->isObjCQualifiedIdType())
2065*0a6a1f1dSLionel Sambuc       return true;
2066*0a6a1f1dSLionel Sambuc   }
2067*0a6a1f1dSLionel Sambuc   if (T->isObjCObjectPointerType()) {
2068*0a6a1f1dSLionel Sambuc     T = T->getPointeeType();
2069*0a6a1f1dSLionel Sambuc     return T->isObjCQualifiedInterfaceType();
2070*0a6a1f1dSLionel Sambuc   }
2071*0a6a1f1dSLionel Sambuc   if (T->isArrayType()) {
2072*0a6a1f1dSLionel Sambuc     QualType ElemTy = Context->getBaseElementType(T);
2073*0a6a1f1dSLionel Sambuc     return needToScanForQualifiers(ElemTy);
2074*0a6a1f1dSLionel Sambuc   }
2075*0a6a1f1dSLionel Sambuc   return false;
2076*0a6a1f1dSLionel Sambuc }
2077*0a6a1f1dSLionel Sambuc 
RewriteObjCQualifiedInterfaceTypes(Expr * E)2078*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2079*0a6a1f1dSLionel Sambuc   QualType Type = E->getType();
2080*0a6a1f1dSLionel Sambuc   if (needToScanForQualifiers(Type)) {
2081*0a6a1f1dSLionel Sambuc     SourceLocation Loc, EndLoc;
2082*0a6a1f1dSLionel Sambuc 
2083*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2084*0a6a1f1dSLionel Sambuc       Loc = ECE->getLParenLoc();
2085*0a6a1f1dSLionel Sambuc       EndLoc = ECE->getRParenLoc();
2086*0a6a1f1dSLionel Sambuc     } else {
2087*0a6a1f1dSLionel Sambuc       Loc = E->getLocStart();
2088*0a6a1f1dSLionel Sambuc       EndLoc = E->getLocEnd();
2089*0a6a1f1dSLionel Sambuc     }
2090*0a6a1f1dSLionel Sambuc     // This will defend against trying to rewrite synthesized expressions.
2091*0a6a1f1dSLionel Sambuc     if (Loc.isInvalid() || EndLoc.isInvalid())
2092*0a6a1f1dSLionel Sambuc       return;
2093*0a6a1f1dSLionel Sambuc 
2094*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(Loc);
2095*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(EndLoc);
2096*0a6a1f1dSLionel Sambuc     const char *startRef = nullptr, *endRef = nullptr;
2097*0a6a1f1dSLionel Sambuc     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2098*0a6a1f1dSLionel Sambuc       // Get the locations of the startRef, endRef.
2099*0a6a1f1dSLionel Sambuc       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2100*0a6a1f1dSLionel Sambuc       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2101*0a6a1f1dSLionel Sambuc       // Comment out the protocol references.
2102*0a6a1f1dSLionel Sambuc       InsertText(LessLoc, "/*");
2103*0a6a1f1dSLionel Sambuc       InsertText(GreaterLoc, "*/");
2104*0a6a1f1dSLionel Sambuc     }
2105*0a6a1f1dSLionel Sambuc   }
2106*0a6a1f1dSLionel Sambuc }
2107*0a6a1f1dSLionel Sambuc 
RewriteObjCQualifiedInterfaceTypes(Decl * Dcl)2108*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2109*0a6a1f1dSLionel Sambuc   SourceLocation Loc;
2110*0a6a1f1dSLionel Sambuc   QualType Type;
2111*0a6a1f1dSLionel Sambuc   const FunctionProtoType *proto = nullptr;
2112*0a6a1f1dSLionel Sambuc   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2113*0a6a1f1dSLionel Sambuc     Loc = VD->getLocation();
2114*0a6a1f1dSLionel Sambuc     Type = VD->getType();
2115*0a6a1f1dSLionel Sambuc   }
2116*0a6a1f1dSLionel Sambuc   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2117*0a6a1f1dSLionel Sambuc     Loc = FD->getLocation();
2118*0a6a1f1dSLionel Sambuc     // Check for ObjC 'id' and class types that have been adorned with protocol
2119*0a6a1f1dSLionel Sambuc     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2120*0a6a1f1dSLionel Sambuc     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2121*0a6a1f1dSLionel Sambuc     assert(funcType && "missing function type");
2122*0a6a1f1dSLionel Sambuc     proto = dyn_cast<FunctionProtoType>(funcType);
2123*0a6a1f1dSLionel Sambuc     if (!proto)
2124*0a6a1f1dSLionel Sambuc       return;
2125*0a6a1f1dSLionel Sambuc     Type = proto->getReturnType();
2126*0a6a1f1dSLionel Sambuc   }
2127*0a6a1f1dSLionel Sambuc   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2128*0a6a1f1dSLionel Sambuc     Loc = FD->getLocation();
2129*0a6a1f1dSLionel Sambuc     Type = FD->getType();
2130*0a6a1f1dSLionel Sambuc   }
2131*0a6a1f1dSLionel Sambuc   else
2132*0a6a1f1dSLionel Sambuc     return;
2133*0a6a1f1dSLionel Sambuc 
2134*0a6a1f1dSLionel Sambuc   if (needToScanForQualifiers(Type)) {
2135*0a6a1f1dSLionel Sambuc     // Since types are unique, we need to scan the buffer.
2136*0a6a1f1dSLionel Sambuc 
2137*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(Loc);
2138*0a6a1f1dSLionel Sambuc     const char *startBuf = endBuf;
2139*0a6a1f1dSLionel Sambuc     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2140*0a6a1f1dSLionel Sambuc       startBuf--; // scan backward (from the decl location) for return type.
2141*0a6a1f1dSLionel Sambuc     const char *startRef = nullptr, *endRef = nullptr;
2142*0a6a1f1dSLionel Sambuc     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2143*0a6a1f1dSLionel Sambuc       // Get the locations of the startRef, endRef.
2144*0a6a1f1dSLionel Sambuc       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2145*0a6a1f1dSLionel Sambuc       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2146*0a6a1f1dSLionel Sambuc       // Comment out the protocol references.
2147*0a6a1f1dSLionel Sambuc       InsertText(LessLoc, "/*");
2148*0a6a1f1dSLionel Sambuc       InsertText(GreaterLoc, "*/");
2149*0a6a1f1dSLionel Sambuc     }
2150*0a6a1f1dSLionel Sambuc   }
2151*0a6a1f1dSLionel Sambuc   if (!proto)
2152*0a6a1f1dSLionel Sambuc       return; // most likely, was a variable
2153*0a6a1f1dSLionel Sambuc   // Now check arguments.
2154*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(Loc);
2155*0a6a1f1dSLionel Sambuc   const char *startFuncBuf = startBuf;
2156*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2157*0a6a1f1dSLionel Sambuc     if (needToScanForQualifiers(proto->getParamType(i))) {
2158*0a6a1f1dSLionel Sambuc       // Since types are unique, we need to scan the buffer.
2159*0a6a1f1dSLionel Sambuc 
2160*0a6a1f1dSLionel Sambuc       const char *endBuf = startBuf;
2161*0a6a1f1dSLionel Sambuc       // scan forward (from the decl location) for argument types.
2162*0a6a1f1dSLionel Sambuc       scanToNextArgument(endBuf);
2163*0a6a1f1dSLionel Sambuc       const char *startRef = nullptr, *endRef = nullptr;
2164*0a6a1f1dSLionel Sambuc       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2165*0a6a1f1dSLionel Sambuc         // Get the locations of the startRef, endRef.
2166*0a6a1f1dSLionel Sambuc         SourceLocation LessLoc =
2167*0a6a1f1dSLionel Sambuc           Loc.getLocWithOffset(startRef-startFuncBuf);
2168*0a6a1f1dSLionel Sambuc         SourceLocation GreaterLoc =
2169*0a6a1f1dSLionel Sambuc           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2170*0a6a1f1dSLionel Sambuc         // Comment out the protocol references.
2171*0a6a1f1dSLionel Sambuc         InsertText(LessLoc, "/*");
2172*0a6a1f1dSLionel Sambuc         InsertText(GreaterLoc, "*/");
2173*0a6a1f1dSLionel Sambuc       }
2174*0a6a1f1dSLionel Sambuc       startBuf = ++endBuf;
2175*0a6a1f1dSLionel Sambuc     }
2176*0a6a1f1dSLionel Sambuc     else {
2177*0a6a1f1dSLionel Sambuc       // If the function name is derived from a macro expansion, then the
2178*0a6a1f1dSLionel Sambuc       // argument buffer will not follow the name. Need to speak with Chris.
2179*0a6a1f1dSLionel Sambuc       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2180*0a6a1f1dSLionel Sambuc         startBuf++; // scan forward (from the decl location) for argument types.
2181*0a6a1f1dSLionel Sambuc       startBuf++;
2182*0a6a1f1dSLionel Sambuc     }
2183*0a6a1f1dSLionel Sambuc   }
2184*0a6a1f1dSLionel Sambuc }
2185*0a6a1f1dSLionel Sambuc 
RewriteTypeOfDecl(VarDecl * ND)2186*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2187*0a6a1f1dSLionel Sambuc   QualType QT = ND->getType();
2188*0a6a1f1dSLionel Sambuc   const Type* TypePtr = QT->getAs<Type>();
2189*0a6a1f1dSLionel Sambuc   if (!isa<TypeOfExprType>(TypePtr))
2190*0a6a1f1dSLionel Sambuc     return;
2191*0a6a1f1dSLionel Sambuc   while (isa<TypeOfExprType>(TypePtr)) {
2192*0a6a1f1dSLionel Sambuc     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2193*0a6a1f1dSLionel Sambuc     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2194*0a6a1f1dSLionel Sambuc     TypePtr = QT->getAs<Type>();
2195*0a6a1f1dSLionel Sambuc   }
2196*0a6a1f1dSLionel Sambuc   // FIXME. This will not work for multiple declarators; as in:
2197*0a6a1f1dSLionel Sambuc   // __typeof__(a) b,c,d;
2198*0a6a1f1dSLionel Sambuc   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2199*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2200*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
2201*0a6a1f1dSLionel Sambuc   if (ND->getInit()) {
2202*0a6a1f1dSLionel Sambuc     std::string Name(ND->getNameAsString());
2203*0a6a1f1dSLionel Sambuc     TypeAsString += " " + Name + " = ";
2204*0a6a1f1dSLionel Sambuc     Expr *E = ND->getInit();
2205*0a6a1f1dSLionel Sambuc     SourceLocation startLoc;
2206*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2207*0a6a1f1dSLionel Sambuc       startLoc = ECE->getLParenLoc();
2208*0a6a1f1dSLionel Sambuc     else
2209*0a6a1f1dSLionel Sambuc       startLoc = E->getLocStart();
2210*0a6a1f1dSLionel Sambuc     startLoc = SM->getExpansionLoc(startLoc);
2211*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(startLoc);
2212*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2213*0a6a1f1dSLionel Sambuc   }
2214*0a6a1f1dSLionel Sambuc   else {
2215*0a6a1f1dSLionel Sambuc     SourceLocation X = ND->getLocEnd();
2216*0a6a1f1dSLionel Sambuc     X = SM->getExpansionLoc(X);
2217*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(X);
2218*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2219*0a6a1f1dSLionel Sambuc   }
2220*0a6a1f1dSLionel Sambuc }
2221*0a6a1f1dSLionel Sambuc 
2222*0a6a1f1dSLionel Sambuc // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
SynthSelGetUidFunctionDecl()2223*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthSelGetUidFunctionDecl() {
2224*0a6a1f1dSLionel Sambuc   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2225*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2226*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2227*0a6a1f1dSLionel Sambuc   QualType getFuncType =
2228*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2229*0a6a1f1dSLionel Sambuc   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2230*0a6a1f1dSLionel Sambuc                                                SourceLocation(),
2231*0a6a1f1dSLionel Sambuc                                                SourceLocation(),
2232*0a6a1f1dSLionel Sambuc                                                SelGetUidIdent, getFuncType,
2233*0a6a1f1dSLionel Sambuc                                                nullptr, SC_Extern);
2234*0a6a1f1dSLionel Sambuc }
2235*0a6a1f1dSLionel Sambuc 
RewriteFunctionDecl(FunctionDecl * FD)2236*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2237*0a6a1f1dSLionel Sambuc   // declared in <objc/objc.h>
2238*0a6a1f1dSLionel Sambuc   if (FD->getIdentifier() &&
2239*0a6a1f1dSLionel Sambuc       FD->getName() == "sel_registerName") {
2240*0a6a1f1dSLionel Sambuc     SelGetUidFunctionDecl = FD;
2241*0a6a1f1dSLionel Sambuc     return;
2242*0a6a1f1dSLionel Sambuc   }
2243*0a6a1f1dSLionel Sambuc   RewriteObjCQualifiedInterfaceTypes(FD);
2244*0a6a1f1dSLionel Sambuc }
2245*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerType(std::string & Str,QualType Type)2246*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2247*0a6a1f1dSLionel Sambuc   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2248*0a6a1f1dSLionel Sambuc   const char *argPtr = TypeString.c_str();
2249*0a6a1f1dSLionel Sambuc   if (!strchr(argPtr, '^')) {
2250*0a6a1f1dSLionel Sambuc     Str += TypeString;
2251*0a6a1f1dSLionel Sambuc     return;
2252*0a6a1f1dSLionel Sambuc   }
2253*0a6a1f1dSLionel Sambuc   while (*argPtr) {
2254*0a6a1f1dSLionel Sambuc     Str += (*argPtr == '^' ? '*' : *argPtr);
2255*0a6a1f1dSLionel Sambuc     argPtr++;
2256*0a6a1f1dSLionel Sambuc   }
2257*0a6a1f1dSLionel Sambuc }
2258*0a6a1f1dSLionel Sambuc 
2259*0a6a1f1dSLionel Sambuc // FIXME. Consolidate this routine with RewriteBlockPointerType.
RewriteBlockPointerTypeVariable(std::string & Str,ValueDecl * VD)2260*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2261*0a6a1f1dSLionel Sambuc                                                   ValueDecl *VD) {
2262*0a6a1f1dSLionel Sambuc   QualType Type = VD->getType();
2263*0a6a1f1dSLionel Sambuc   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2264*0a6a1f1dSLionel Sambuc   const char *argPtr = TypeString.c_str();
2265*0a6a1f1dSLionel Sambuc   int paren = 0;
2266*0a6a1f1dSLionel Sambuc   while (*argPtr) {
2267*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
2268*0a6a1f1dSLionel Sambuc       case '(':
2269*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2270*0a6a1f1dSLionel Sambuc         paren++;
2271*0a6a1f1dSLionel Sambuc         break;
2272*0a6a1f1dSLionel Sambuc       case ')':
2273*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2274*0a6a1f1dSLionel Sambuc         paren--;
2275*0a6a1f1dSLionel Sambuc         break;
2276*0a6a1f1dSLionel Sambuc       case '^':
2277*0a6a1f1dSLionel Sambuc         Str += '*';
2278*0a6a1f1dSLionel Sambuc         if (paren == 1)
2279*0a6a1f1dSLionel Sambuc           Str += VD->getNameAsString();
2280*0a6a1f1dSLionel Sambuc         break;
2281*0a6a1f1dSLionel Sambuc       default:
2282*0a6a1f1dSLionel Sambuc         Str += *argPtr;
2283*0a6a1f1dSLionel Sambuc         break;
2284*0a6a1f1dSLionel Sambuc     }
2285*0a6a1f1dSLionel Sambuc     argPtr++;
2286*0a6a1f1dSLionel Sambuc   }
2287*0a6a1f1dSLionel Sambuc }
2288*0a6a1f1dSLionel Sambuc 
2289*0a6a1f1dSLionel Sambuc 
RewriteBlockLiteralFunctionDecl(FunctionDecl * FD)2290*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2291*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2292*0a6a1f1dSLionel Sambuc   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2293*0a6a1f1dSLionel Sambuc   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2294*0a6a1f1dSLionel Sambuc   if (!proto)
2295*0a6a1f1dSLionel Sambuc     return;
2296*0a6a1f1dSLionel Sambuc   QualType Type = proto->getReturnType();
2297*0a6a1f1dSLionel Sambuc   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2298*0a6a1f1dSLionel Sambuc   FdStr += " ";
2299*0a6a1f1dSLionel Sambuc   FdStr += FD->getName();
2300*0a6a1f1dSLionel Sambuc   FdStr +=  "(";
2301*0a6a1f1dSLionel Sambuc   unsigned numArgs = proto->getNumParams();
2302*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < numArgs; i++) {
2303*0a6a1f1dSLionel Sambuc     QualType ArgType = proto->getParamType(i);
2304*0a6a1f1dSLionel Sambuc     RewriteBlockPointerType(FdStr, ArgType);
2305*0a6a1f1dSLionel Sambuc     if (i+1 < numArgs)
2306*0a6a1f1dSLionel Sambuc       FdStr += ", ";
2307*0a6a1f1dSLionel Sambuc   }
2308*0a6a1f1dSLionel Sambuc   FdStr +=  ");\n";
2309*0a6a1f1dSLionel Sambuc   InsertText(FunLocStart, FdStr);
2310*0a6a1f1dSLionel Sambuc   CurFunctionDeclToDeclareForBlock = nullptr;
2311*0a6a1f1dSLionel Sambuc }
2312*0a6a1f1dSLionel Sambuc 
2313*0a6a1f1dSLionel Sambuc // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
SynthSuperConstructorFunctionDecl()2314*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2315*0a6a1f1dSLionel Sambuc   if (SuperConstructorFunctionDecl)
2316*0a6a1f1dSLionel Sambuc     return;
2317*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2318*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2319*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2320*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2321*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2322*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2323*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2324*0a6a1f1dSLionel Sambuc                                                ArgTys);
2325*0a6a1f1dSLionel Sambuc   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2326*0a6a1f1dSLionel Sambuc                                                      SourceLocation(),
2327*0a6a1f1dSLionel Sambuc                                                      SourceLocation(),
2328*0a6a1f1dSLionel Sambuc                                                      msgSendIdent, msgSendType,
2329*0a6a1f1dSLionel Sambuc                                                      nullptr, SC_Extern);
2330*0a6a1f1dSLionel Sambuc }
2331*0a6a1f1dSLionel Sambuc 
2332*0a6a1f1dSLionel Sambuc // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
SynthMsgSendFunctionDecl()2333*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthMsgSendFunctionDecl() {
2334*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2335*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2336*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2337*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2338*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2339*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2340*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2341*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2342*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2343*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2344*0a6a1f1dSLionel Sambuc   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2345*0a6a1f1dSLionel Sambuc                                              SourceLocation(),
2346*0a6a1f1dSLionel Sambuc                                              SourceLocation(),
2347*0a6a1f1dSLionel Sambuc                                              msgSendIdent, msgSendType,
2348*0a6a1f1dSLionel Sambuc                                              nullptr, SC_Extern);
2349*0a6a1f1dSLionel Sambuc }
2350*0a6a1f1dSLionel Sambuc 
2351*0a6a1f1dSLionel Sambuc // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
SynthMsgSendSuperFunctionDecl()2352*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2353*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2354*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2355*0a6a1f1dSLionel Sambuc   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2356*0a6a1f1dSLionel Sambuc                                       SourceLocation(), SourceLocation(),
2357*0a6a1f1dSLionel Sambuc                                       &Context->Idents.get("objc_super"));
2358*0a6a1f1dSLionel Sambuc   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2359*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2360*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2361*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2362*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2363*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2364*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2365*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2366*0a6a1f1dSLionel Sambuc   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2367*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2368*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2369*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2370*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2371*0a6a1f1dSLionel Sambuc }
2372*0a6a1f1dSLionel Sambuc 
2373*0a6a1f1dSLionel Sambuc // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
SynthMsgSendStretFunctionDecl()2374*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2375*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2376*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2377*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2378*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2379*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2380*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2381*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2382*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2383*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2384*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2385*0a6a1f1dSLionel Sambuc   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2386*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2387*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2388*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2389*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2390*0a6a1f1dSLionel Sambuc }
2391*0a6a1f1dSLionel Sambuc 
2392*0a6a1f1dSLionel Sambuc // SynthMsgSendSuperStretFunctionDecl -
2393*0a6a1f1dSLionel Sambuc // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
SynthMsgSendSuperStretFunctionDecl()2394*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2395*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent =
2396*0a6a1f1dSLionel Sambuc     &Context->Idents.get("objc_msgSendSuper_stret");
2397*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2398*0a6a1f1dSLionel Sambuc   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2399*0a6a1f1dSLionel Sambuc                                       SourceLocation(), SourceLocation(),
2400*0a6a1f1dSLionel Sambuc                                       &Context->Idents.get("objc_super"));
2401*0a6a1f1dSLionel Sambuc   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2402*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2403*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2404*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2405*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2406*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2407*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2408*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2409*0a6a1f1dSLionel Sambuc   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410*0a6a1f1dSLionel Sambuc                                                        SourceLocation(),
2411*0a6a1f1dSLionel Sambuc                                                        SourceLocation(),
2412*0a6a1f1dSLionel Sambuc                                                        msgSendIdent,
2413*0a6a1f1dSLionel Sambuc                                                        msgSendType, nullptr,
2414*0a6a1f1dSLionel Sambuc                                                        SC_Extern);
2415*0a6a1f1dSLionel Sambuc }
2416*0a6a1f1dSLionel Sambuc 
2417*0a6a1f1dSLionel Sambuc // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
SynthMsgSendFpretFunctionDecl()2418*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2419*0a6a1f1dSLionel Sambuc   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2420*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2421*0a6a1f1dSLionel Sambuc   QualType argT = Context->getObjCIdType();
2422*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'id' type");
2423*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2424*0a6a1f1dSLionel Sambuc   argT = Context->getObjCSelType();
2425*0a6a1f1dSLionel Sambuc   assert(!argT.isNull() && "Can't find 'SEL' type");
2426*0a6a1f1dSLionel Sambuc   ArgTys.push_back(argT);
2427*0a6a1f1dSLionel Sambuc   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2428*0a6a1f1dSLionel Sambuc                                                ArgTys, /*isVariadic=*/true);
2429*0a6a1f1dSLionel Sambuc   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2431*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2432*0a6a1f1dSLionel Sambuc                                                   msgSendIdent, msgSendType,
2433*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2434*0a6a1f1dSLionel Sambuc }
2435*0a6a1f1dSLionel Sambuc 
2436*0a6a1f1dSLionel Sambuc // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
SynthGetClassFunctionDecl()2437*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthGetClassFunctionDecl() {
2438*0a6a1f1dSLionel Sambuc   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2439*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2440*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2441*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2442*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2443*0a6a1f1dSLionel Sambuc   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2444*0a6a1f1dSLionel Sambuc                                               SourceLocation(),
2445*0a6a1f1dSLionel Sambuc                                               SourceLocation(),
2446*0a6a1f1dSLionel Sambuc                                               getClassIdent, getClassType,
2447*0a6a1f1dSLionel Sambuc                                               nullptr, SC_Extern);
2448*0a6a1f1dSLionel Sambuc }
2449*0a6a1f1dSLionel Sambuc 
2450*0a6a1f1dSLionel Sambuc // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
SynthGetSuperClassFunctionDecl()2451*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2452*0a6a1f1dSLionel Sambuc   IdentifierInfo *getSuperClassIdent =
2453*0a6a1f1dSLionel Sambuc     &Context->Idents.get("class_getSuperclass");
2454*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2455*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getObjCClassType());
2456*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2457*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2458*0a6a1f1dSLionel Sambuc   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2459*0a6a1f1dSLionel Sambuc                                                    SourceLocation(),
2460*0a6a1f1dSLionel Sambuc                                                    SourceLocation(),
2461*0a6a1f1dSLionel Sambuc                                                    getSuperClassIdent,
2462*0a6a1f1dSLionel Sambuc                                                    getClassType, nullptr,
2463*0a6a1f1dSLionel Sambuc                                                    SC_Extern);
2464*0a6a1f1dSLionel Sambuc }
2465*0a6a1f1dSLionel Sambuc 
2466*0a6a1f1dSLionel Sambuc // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
SynthGetMetaClassFunctionDecl()2467*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2468*0a6a1f1dSLionel Sambuc   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2469*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 16> ArgTys;
2470*0a6a1f1dSLionel Sambuc   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2471*0a6a1f1dSLionel Sambuc   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2472*0a6a1f1dSLionel Sambuc                                                 ArgTys);
2473*0a6a1f1dSLionel Sambuc   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2474*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2475*0a6a1f1dSLionel Sambuc                                                   SourceLocation(),
2476*0a6a1f1dSLionel Sambuc                                                   getClassIdent, getClassType,
2477*0a6a1f1dSLionel Sambuc                                                   nullptr, SC_Extern);
2478*0a6a1f1dSLionel Sambuc }
2479*0a6a1f1dSLionel Sambuc 
RewriteObjCStringLiteral(ObjCStringLiteral * Exp)2480*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2481*0a6a1f1dSLionel Sambuc   assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2482*0a6a1f1dSLionel Sambuc   QualType strType = getConstantStringStructType();
2483*0a6a1f1dSLionel Sambuc 
2484*0a6a1f1dSLionel Sambuc   std::string S = "__NSConstantStringImpl_";
2485*0a6a1f1dSLionel Sambuc 
2486*0a6a1f1dSLionel Sambuc   std::string tmpName = InFileName;
2487*0a6a1f1dSLionel Sambuc   unsigned i;
2488*0a6a1f1dSLionel Sambuc   for (i=0; i < tmpName.length(); i++) {
2489*0a6a1f1dSLionel Sambuc     char c = tmpName.at(i);
2490*0a6a1f1dSLionel Sambuc     // replace any non-alphanumeric characters with '_'.
2491*0a6a1f1dSLionel Sambuc     if (!isAlphanumeric(c))
2492*0a6a1f1dSLionel Sambuc       tmpName[i] = '_';
2493*0a6a1f1dSLionel Sambuc   }
2494*0a6a1f1dSLionel Sambuc   S += tmpName;
2495*0a6a1f1dSLionel Sambuc   S += "_";
2496*0a6a1f1dSLionel Sambuc   S += utostr(NumObjCStringLiterals++);
2497*0a6a1f1dSLionel Sambuc 
2498*0a6a1f1dSLionel Sambuc   Preamble += "static __NSConstantStringImpl " + S;
2499*0a6a1f1dSLionel Sambuc   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2500*0a6a1f1dSLionel Sambuc   Preamble += "0x000007c8,"; // utf8_str
2501*0a6a1f1dSLionel Sambuc   // The pretty printer for StringLiteral handles escape characters properly.
2502*0a6a1f1dSLionel Sambuc   std::string prettyBufS;
2503*0a6a1f1dSLionel Sambuc   llvm::raw_string_ostream prettyBuf(prettyBufS);
2504*0a6a1f1dSLionel Sambuc   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2505*0a6a1f1dSLionel Sambuc   Preamble += prettyBuf.str();
2506*0a6a1f1dSLionel Sambuc   Preamble += ",";
2507*0a6a1f1dSLionel Sambuc   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2508*0a6a1f1dSLionel Sambuc 
2509*0a6a1f1dSLionel Sambuc   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2510*0a6a1f1dSLionel Sambuc                                    SourceLocation(), &Context->Idents.get(S),
2511*0a6a1f1dSLionel Sambuc                                    strType, nullptr, SC_Static);
2512*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2513*0a6a1f1dSLionel Sambuc                                                SourceLocation());
2514*0a6a1f1dSLionel Sambuc   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2515*0a6a1f1dSLionel Sambuc                                  Context->getPointerType(DRE->getType()),
2516*0a6a1f1dSLionel Sambuc                                            VK_RValue, OK_Ordinary,
2517*0a6a1f1dSLionel Sambuc                                            SourceLocation());
2518*0a6a1f1dSLionel Sambuc   // cast to NSConstantString *
2519*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2520*0a6a1f1dSLionel Sambuc                                             CK_CPointerToObjCPointerCast, Unop);
2521*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, cast);
2522*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2523*0a6a1f1dSLionel Sambuc   return cast;
2524*0a6a1f1dSLionel Sambuc }
2525*0a6a1f1dSLionel Sambuc 
2526*0a6a1f1dSLionel Sambuc // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
getSuperStructType()2527*0a6a1f1dSLionel Sambuc QualType RewriteObjC::getSuperStructType() {
2528*0a6a1f1dSLionel Sambuc   if (!SuperStructDecl) {
2529*0a6a1f1dSLionel Sambuc     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2530*0a6a1f1dSLionel Sambuc                                          SourceLocation(), SourceLocation(),
2531*0a6a1f1dSLionel Sambuc                                          &Context->Idents.get("objc_super"));
2532*0a6a1f1dSLionel Sambuc     QualType FieldTypes[2];
2533*0a6a1f1dSLionel Sambuc 
2534*0a6a1f1dSLionel Sambuc     // struct objc_object *receiver;
2535*0a6a1f1dSLionel Sambuc     FieldTypes[0] = Context->getObjCIdType();
2536*0a6a1f1dSLionel Sambuc     // struct objc_class *super;
2537*0a6a1f1dSLionel Sambuc     FieldTypes[1] = Context->getObjCClassType();
2538*0a6a1f1dSLionel Sambuc 
2539*0a6a1f1dSLionel Sambuc     // Create fields
2540*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < 2; ++i) {
2541*0a6a1f1dSLionel Sambuc       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2542*0a6a1f1dSLionel Sambuc                                                  SourceLocation(),
2543*0a6a1f1dSLionel Sambuc                                                  SourceLocation(), nullptr,
2544*0a6a1f1dSLionel Sambuc                                                  FieldTypes[i], nullptr,
2545*0a6a1f1dSLionel Sambuc                                                  /*BitWidth=*/nullptr,
2546*0a6a1f1dSLionel Sambuc                                                  /*Mutable=*/false,
2547*0a6a1f1dSLionel Sambuc                                                  ICIS_NoInit));
2548*0a6a1f1dSLionel Sambuc     }
2549*0a6a1f1dSLionel Sambuc 
2550*0a6a1f1dSLionel Sambuc     SuperStructDecl->completeDefinition();
2551*0a6a1f1dSLionel Sambuc   }
2552*0a6a1f1dSLionel Sambuc   return Context->getTagDeclType(SuperStructDecl);
2553*0a6a1f1dSLionel Sambuc }
2554*0a6a1f1dSLionel Sambuc 
getConstantStringStructType()2555*0a6a1f1dSLionel Sambuc QualType RewriteObjC::getConstantStringStructType() {
2556*0a6a1f1dSLionel Sambuc   if (!ConstantStringDecl) {
2557*0a6a1f1dSLionel Sambuc     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2558*0a6a1f1dSLionel Sambuc                                             SourceLocation(), SourceLocation(),
2559*0a6a1f1dSLionel Sambuc                          &Context->Idents.get("__NSConstantStringImpl"));
2560*0a6a1f1dSLionel Sambuc     QualType FieldTypes[4];
2561*0a6a1f1dSLionel Sambuc 
2562*0a6a1f1dSLionel Sambuc     // struct objc_object *receiver;
2563*0a6a1f1dSLionel Sambuc     FieldTypes[0] = Context->getObjCIdType();
2564*0a6a1f1dSLionel Sambuc     // int flags;
2565*0a6a1f1dSLionel Sambuc     FieldTypes[1] = Context->IntTy;
2566*0a6a1f1dSLionel Sambuc     // char *str;
2567*0a6a1f1dSLionel Sambuc     FieldTypes[2] = Context->getPointerType(Context->CharTy);
2568*0a6a1f1dSLionel Sambuc     // long length;
2569*0a6a1f1dSLionel Sambuc     FieldTypes[3] = Context->LongTy;
2570*0a6a1f1dSLionel Sambuc 
2571*0a6a1f1dSLionel Sambuc     // Create fields
2572*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < 4; ++i) {
2573*0a6a1f1dSLionel Sambuc       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2574*0a6a1f1dSLionel Sambuc                                                     ConstantStringDecl,
2575*0a6a1f1dSLionel Sambuc                                                     SourceLocation(),
2576*0a6a1f1dSLionel Sambuc                                                     SourceLocation(), nullptr,
2577*0a6a1f1dSLionel Sambuc                                                     FieldTypes[i], nullptr,
2578*0a6a1f1dSLionel Sambuc                                                     /*BitWidth=*/nullptr,
2579*0a6a1f1dSLionel Sambuc                                                     /*Mutable=*/true,
2580*0a6a1f1dSLionel Sambuc                                                     ICIS_NoInit));
2581*0a6a1f1dSLionel Sambuc     }
2582*0a6a1f1dSLionel Sambuc 
2583*0a6a1f1dSLionel Sambuc     ConstantStringDecl->completeDefinition();
2584*0a6a1f1dSLionel Sambuc   }
2585*0a6a1f1dSLionel Sambuc   return Context->getTagDeclType(ConstantStringDecl);
2586*0a6a1f1dSLionel Sambuc }
2587*0a6a1f1dSLionel Sambuc 
SynthMsgSendStretCallExpr(FunctionDecl * MsgSendStretFlavor,QualType msgSendType,QualType returnType,SmallVectorImpl<QualType> & ArgTypes,SmallVectorImpl<Expr * > & MsgExprs,ObjCMethodDecl * Method)2588*0a6a1f1dSLionel Sambuc CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2589*0a6a1f1dSLionel Sambuc                                                 QualType msgSendType,
2590*0a6a1f1dSLionel Sambuc                                                 QualType returnType,
2591*0a6a1f1dSLionel Sambuc                                                 SmallVectorImpl<QualType> &ArgTypes,
2592*0a6a1f1dSLionel Sambuc                                                 SmallVectorImpl<Expr*> &MsgExprs,
2593*0a6a1f1dSLionel Sambuc                                                 ObjCMethodDecl *Method) {
2594*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend_stret() declaration.
2595*0a6a1f1dSLionel Sambuc   DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2596*0a6a1f1dSLionel Sambuc                                                  false, msgSendType,
2597*0a6a1f1dSLionel Sambuc                                                  VK_LValue, SourceLocation());
2598*0a6a1f1dSLionel Sambuc   // Need to cast objc_msgSend_stret to "void *" (see above comment).
2599*0a6a1f1dSLionel Sambuc   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2600*0a6a1f1dSLionel Sambuc                                   Context->getPointerType(Context->VoidTy),
2601*0a6a1f1dSLionel Sambuc                                   CK_BitCast, STDRE);
2602*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
2603*0a6a1f1dSLionel Sambuc   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2604*0a6a1f1dSLionel Sambuc                                             Method ? Method->isVariadic()
2605*0a6a1f1dSLionel Sambuc                                                    : false);
2606*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
2607*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2608*0a6a1f1dSLionel Sambuc                                             cast);
2609*0a6a1f1dSLionel Sambuc 
2610*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
2611*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2612*0a6a1f1dSLionel Sambuc 
2613*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2614*0a6a1f1dSLionel Sambuc   CallExpr *STCE = new (Context) CallExpr(
2615*0a6a1f1dSLionel Sambuc       *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
2616*0a6a1f1dSLionel Sambuc   return STCE;
2617*0a6a1f1dSLionel Sambuc 
2618*0a6a1f1dSLionel Sambuc }
2619*0a6a1f1dSLionel Sambuc 
2620*0a6a1f1dSLionel Sambuc 
SynthMessageExpr(ObjCMessageExpr * Exp,SourceLocation StartLoc,SourceLocation EndLoc)2621*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2622*0a6a1f1dSLionel Sambuc                                     SourceLocation StartLoc,
2623*0a6a1f1dSLionel Sambuc                                     SourceLocation EndLoc) {
2624*0a6a1f1dSLionel Sambuc   if (!SelGetUidFunctionDecl)
2625*0a6a1f1dSLionel Sambuc     SynthSelGetUidFunctionDecl();
2626*0a6a1f1dSLionel Sambuc   if (!MsgSendFunctionDecl)
2627*0a6a1f1dSLionel Sambuc     SynthMsgSendFunctionDecl();
2628*0a6a1f1dSLionel Sambuc   if (!MsgSendSuperFunctionDecl)
2629*0a6a1f1dSLionel Sambuc     SynthMsgSendSuperFunctionDecl();
2630*0a6a1f1dSLionel Sambuc   if (!MsgSendStretFunctionDecl)
2631*0a6a1f1dSLionel Sambuc     SynthMsgSendStretFunctionDecl();
2632*0a6a1f1dSLionel Sambuc   if (!MsgSendSuperStretFunctionDecl)
2633*0a6a1f1dSLionel Sambuc     SynthMsgSendSuperStretFunctionDecl();
2634*0a6a1f1dSLionel Sambuc   if (!MsgSendFpretFunctionDecl)
2635*0a6a1f1dSLionel Sambuc     SynthMsgSendFpretFunctionDecl();
2636*0a6a1f1dSLionel Sambuc   if (!GetClassFunctionDecl)
2637*0a6a1f1dSLionel Sambuc     SynthGetClassFunctionDecl();
2638*0a6a1f1dSLionel Sambuc   if (!GetSuperClassFunctionDecl)
2639*0a6a1f1dSLionel Sambuc     SynthGetSuperClassFunctionDecl();
2640*0a6a1f1dSLionel Sambuc   if (!GetMetaClassFunctionDecl)
2641*0a6a1f1dSLionel Sambuc     SynthGetMetaClassFunctionDecl();
2642*0a6a1f1dSLionel Sambuc 
2643*0a6a1f1dSLionel Sambuc   // default to objc_msgSend().
2644*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2645*0a6a1f1dSLionel Sambuc   // May need to use objc_msgSend_stret() as well.
2646*0a6a1f1dSLionel Sambuc   FunctionDecl *MsgSendStretFlavor = nullptr;
2647*0a6a1f1dSLionel Sambuc   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2648*0a6a1f1dSLionel Sambuc     QualType resultType = mDecl->getReturnType();
2649*0a6a1f1dSLionel Sambuc     if (resultType->isRecordType())
2650*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendStretFunctionDecl;
2651*0a6a1f1dSLionel Sambuc     else if (resultType->isRealFloatingType())
2652*0a6a1f1dSLionel Sambuc       MsgSendFlavor = MsgSendFpretFunctionDecl;
2653*0a6a1f1dSLionel Sambuc   }
2654*0a6a1f1dSLionel Sambuc 
2655*0a6a1f1dSLionel Sambuc   // Synthesize a call to objc_msgSend().
2656*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> MsgExprs;
2657*0a6a1f1dSLionel Sambuc   switch (Exp->getReceiverKind()) {
2658*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperClass: {
2659*0a6a1f1dSLionel Sambuc     MsgSendFlavor = MsgSendSuperFunctionDecl;
2660*0a6a1f1dSLionel Sambuc     if (MsgSendStretFlavor)
2661*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2662*0a6a1f1dSLionel Sambuc     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2663*0a6a1f1dSLionel Sambuc 
2664*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2665*0a6a1f1dSLionel Sambuc 
2666*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 4> InitExprs;
2667*0a6a1f1dSLionel Sambuc 
2668*0a6a1f1dSLionel Sambuc     // set the receiver to self, the first argument to all methods.
2669*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
2670*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2671*0a6a1f1dSLionel Sambuc                                CK_BitCast,
2672*0a6a1f1dSLionel Sambuc                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2673*0a6a1f1dSLionel Sambuc                                              false,
2674*0a6a1f1dSLionel Sambuc                                              Context->getObjCIdType(),
2675*0a6a1f1dSLionel Sambuc                                              VK_RValue,
2676*0a6a1f1dSLionel Sambuc                                              SourceLocation()))
2677*0a6a1f1dSLionel Sambuc                         ); // set the 'receiver'.
2678*0a6a1f1dSLionel Sambuc 
2679*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2680*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
2681*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2682*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
2684*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
2685*0a6a1f1dSLionel Sambuc                                                  StartLoc,
2686*0a6a1f1dSLionel Sambuc                                                  EndLoc);
2687*0a6a1f1dSLionel Sambuc     // (Class)objc_getClass("CurrentClass")
2688*0a6a1f1dSLionel Sambuc     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2689*0a6a1f1dSLionel Sambuc                                              Context->getObjCClassType(),
2690*0a6a1f1dSLionel Sambuc                                              CK_BitCast, Cls);
2691*0a6a1f1dSLionel Sambuc     ClsExprs.clear();
2692*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(ArgExpr);
2693*0a6a1f1dSLionel Sambuc     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2694*0a6a1f1dSLionel Sambuc                                        &ClsExprs[0], ClsExprs.size(),
2695*0a6a1f1dSLionel Sambuc                                        StartLoc, EndLoc);
2696*0a6a1f1dSLionel Sambuc 
2697*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2698*0a6a1f1dSLionel Sambuc     // To turn off a warning, type-cast to 'id'
2699*0a6a1f1dSLionel Sambuc     InitExprs.push_back( // set 'super class', using class_getSuperclass().
2700*0a6a1f1dSLionel Sambuc                         NoTypeInfoCStyleCastExpr(Context,
2701*0a6a1f1dSLionel Sambuc                                                  Context->getObjCIdType(),
2702*0a6a1f1dSLionel Sambuc                                                  CK_BitCast, Cls));
2703*0a6a1f1dSLionel Sambuc     // struct objc_super
2704*0a6a1f1dSLionel Sambuc     QualType superType = getSuperStructType();
2705*0a6a1f1dSLionel Sambuc     Expr *SuperRep;
2706*0a6a1f1dSLionel Sambuc 
2707*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt) {
2708*0a6a1f1dSLionel Sambuc       SynthSuperConstructorFunctionDecl();
2709*0a6a1f1dSLionel Sambuc       // Simulate a constructor call...
2710*0a6a1f1dSLionel Sambuc       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2711*0a6a1f1dSLionel Sambuc                                                    false, superType, VK_LValue,
2712*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
2713*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2714*0a6a1f1dSLionel Sambuc                                         superType, VK_LValue,
2715*0a6a1f1dSLionel Sambuc                                         SourceLocation());
2716*0a6a1f1dSLionel Sambuc       // The code for super is a little tricky to prevent collision with
2717*0a6a1f1dSLionel Sambuc       // the structure definition in the header. The rewriter has it's own
2718*0a6a1f1dSLionel Sambuc       // internal definition (__rw_objc_super) that is uses. This is why
2719*0a6a1f1dSLionel Sambuc       // we need the cast below. For example:
2720*0a6a1f1dSLionel Sambuc       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2721*0a6a1f1dSLionel Sambuc       //
2722*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2723*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
2724*0a6a1f1dSLionel Sambuc                                              VK_RValue, OK_Ordinary,
2725*0a6a1f1dSLionel Sambuc                                              SourceLocation());
2726*0a6a1f1dSLionel Sambuc       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2727*0a6a1f1dSLionel Sambuc                                           Context->getPointerType(superType),
2728*0a6a1f1dSLionel Sambuc                                           CK_BitCast, SuperRep);
2729*0a6a1f1dSLionel Sambuc     } else {
2730*0a6a1f1dSLionel Sambuc       // (struct objc_super) { <exprs from above> }
2731*0a6a1f1dSLionel Sambuc       InitListExpr *ILE =
2732*0a6a1f1dSLionel Sambuc         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2733*0a6a1f1dSLionel Sambuc                                    SourceLocation());
2734*0a6a1f1dSLionel Sambuc       TypeSourceInfo *superTInfo
2735*0a6a1f1dSLionel Sambuc         = Context->getTrivialTypeSourceInfo(superType);
2736*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2737*0a6a1f1dSLionel Sambuc                                                    superType, VK_LValue,
2738*0a6a1f1dSLionel Sambuc                                                    ILE, false);
2739*0a6a1f1dSLionel Sambuc       // struct objc_super *
2740*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2741*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
2742*0a6a1f1dSLionel Sambuc                                              VK_RValue, OK_Ordinary,
2743*0a6a1f1dSLionel Sambuc                                              SourceLocation());
2744*0a6a1f1dSLionel Sambuc     }
2745*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(SuperRep);
2746*0a6a1f1dSLionel Sambuc     break;
2747*0a6a1f1dSLionel Sambuc   }
2748*0a6a1f1dSLionel Sambuc 
2749*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Class: {
2750*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
2751*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *Class
2752*0a6a1f1dSLionel Sambuc       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2753*0a6a1f1dSLionel Sambuc     IdentifierInfo *clsName = Class->getIdentifier();
2754*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(clsName->getName()));
2755*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2756*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
2757*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
2758*0a6a1f1dSLionel Sambuc                                                  StartLoc, EndLoc);
2759*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(Cls);
2760*0a6a1f1dSLionel Sambuc     break;
2761*0a6a1f1dSLionel Sambuc   }
2762*0a6a1f1dSLionel Sambuc 
2763*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::SuperInstance:{
2764*0a6a1f1dSLionel Sambuc     MsgSendFlavor = MsgSendSuperFunctionDecl;
2765*0a6a1f1dSLionel Sambuc     if (MsgSendStretFlavor)
2766*0a6a1f1dSLionel Sambuc       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2767*0a6a1f1dSLionel Sambuc     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2768*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2769*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 4> InitExprs;
2770*0a6a1f1dSLionel Sambuc 
2771*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
2772*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2773*0a6a1f1dSLionel Sambuc                                CK_BitCast,
2774*0a6a1f1dSLionel Sambuc                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2775*0a6a1f1dSLionel Sambuc                                              false,
2776*0a6a1f1dSLionel Sambuc                                              Context->getObjCIdType(),
2777*0a6a1f1dSLionel Sambuc                                              VK_RValue, SourceLocation()))
2778*0a6a1f1dSLionel Sambuc                         ); // set the 'receiver'.
2779*0a6a1f1dSLionel Sambuc 
2780*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2781*0a6a1f1dSLionel Sambuc     SmallVector<Expr*, 8> ClsExprs;
2782*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2783*0a6a1f1dSLionel Sambuc     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2784*0a6a1f1dSLionel Sambuc                                                  &ClsExprs[0],
2785*0a6a1f1dSLionel Sambuc                                                  ClsExprs.size(),
2786*0a6a1f1dSLionel Sambuc                                                  StartLoc, EndLoc);
2787*0a6a1f1dSLionel Sambuc     // (Class)objc_getClass("CurrentClass")
2788*0a6a1f1dSLionel Sambuc     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2789*0a6a1f1dSLionel Sambuc                                                  Context->getObjCClassType(),
2790*0a6a1f1dSLionel Sambuc                                                  CK_BitCast, Cls);
2791*0a6a1f1dSLionel Sambuc     ClsExprs.clear();
2792*0a6a1f1dSLionel Sambuc     ClsExprs.push_back(ArgExpr);
2793*0a6a1f1dSLionel Sambuc     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2794*0a6a1f1dSLionel Sambuc                                        &ClsExprs[0], ClsExprs.size(),
2795*0a6a1f1dSLionel Sambuc                                        StartLoc, EndLoc);
2796*0a6a1f1dSLionel Sambuc 
2797*0a6a1f1dSLionel Sambuc     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2798*0a6a1f1dSLionel Sambuc     // To turn off a warning, type-cast to 'id'
2799*0a6a1f1dSLionel Sambuc     InitExprs.push_back(
2800*0a6a1f1dSLionel Sambuc       // set 'super class', using class_getSuperclass().
2801*0a6a1f1dSLionel Sambuc       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2802*0a6a1f1dSLionel Sambuc                                CK_BitCast, Cls));
2803*0a6a1f1dSLionel Sambuc     // struct objc_super
2804*0a6a1f1dSLionel Sambuc     QualType superType = getSuperStructType();
2805*0a6a1f1dSLionel Sambuc     Expr *SuperRep;
2806*0a6a1f1dSLionel Sambuc 
2807*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt) {
2808*0a6a1f1dSLionel Sambuc       SynthSuperConstructorFunctionDecl();
2809*0a6a1f1dSLionel Sambuc       // Simulate a constructor call...
2810*0a6a1f1dSLionel Sambuc       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2811*0a6a1f1dSLionel Sambuc                                                    false, superType, VK_LValue,
2812*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
2813*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2814*0a6a1f1dSLionel Sambuc                                         superType, VK_LValue, SourceLocation());
2815*0a6a1f1dSLionel Sambuc       // The code for super is a little tricky to prevent collision with
2816*0a6a1f1dSLionel Sambuc       // the structure definition in the header. The rewriter has it's own
2817*0a6a1f1dSLionel Sambuc       // internal definition (__rw_objc_super) that is uses. This is why
2818*0a6a1f1dSLionel Sambuc       // we need the cast below. For example:
2819*0a6a1f1dSLionel Sambuc       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2820*0a6a1f1dSLionel Sambuc       //
2821*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2822*0a6a1f1dSLionel Sambuc                                Context->getPointerType(SuperRep->getType()),
2823*0a6a1f1dSLionel Sambuc                                VK_RValue, OK_Ordinary,
2824*0a6a1f1dSLionel Sambuc                                SourceLocation());
2825*0a6a1f1dSLionel Sambuc       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2826*0a6a1f1dSLionel Sambuc                                Context->getPointerType(superType),
2827*0a6a1f1dSLionel Sambuc                                CK_BitCast, SuperRep);
2828*0a6a1f1dSLionel Sambuc     } else {
2829*0a6a1f1dSLionel Sambuc       // (struct objc_super) { <exprs from above> }
2830*0a6a1f1dSLionel Sambuc       InitListExpr *ILE =
2831*0a6a1f1dSLionel Sambuc         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2832*0a6a1f1dSLionel Sambuc                                    SourceLocation());
2833*0a6a1f1dSLionel Sambuc       TypeSourceInfo *superTInfo
2834*0a6a1f1dSLionel Sambuc         = Context->getTrivialTypeSourceInfo(superType);
2835*0a6a1f1dSLionel Sambuc       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2836*0a6a1f1dSLionel Sambuc                                                    superType, VK_RValue, ILE,
2837*0a6a1f1dSLionel Sambuc                                                    false);
2838*0a6a1f1dSLionel Sambuc     }
2839*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(SuperRep);
2840*0a6a1f1dSLionel Sambuc     break;
2841*0a6a1f1dSLionel Sambuc   }
2842*0a6a1f1dSLionel Sambuc 
2843*0a6a1f1dSLionel Sambuc   case ObjCMessageExpr::Instance: {
2844*0a6a1f1dSLionel Sambuc     // Remove all type-casts because it may contain objc-style types; e.g.
2845*0a6a1f1dSLionel Sambuc     // Foo<Proto> *.
2846*0a6a1f1dSLionel Sambuc     Expr *recExpr = Exp->getInstanceReceiver();
2847*0a6a1f1dSLionel Sambuc     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2848*0a6a1f1dSLionel Sambuc       recExpr = CE->getSubExpr();
2849*0a6a1f1dSLionel Sambuc     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2850*0a6a1f1dSLionel Sambuc                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2851*0a6a1f1dSLionel Sambuc                                      ? CK_BlockPointerToObjCPointerCast
2852*0a6a1f1dSLionel Sambuc                                      : CK_CPointerToObjCPointerCast;
2853*0a6a1f1dSLionel Sambuc 
2854*0a6a1f1dSLionel Sambuc     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2855*0a6a1f1dSLionel Sambuc                                        CK, recExpr);
2856*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(recExpr);
2857*0a6a1f1dSLionel Sambuc     break;
2858*0a6a1f1dSLionel Sambuc   }
2859*0a6a1f1dSLionel Sambuc   }
2860*0a6a1f1dSLionel Sambuc 
2861*0a6a1f1dSLionel Sambuc   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2862*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> SelExprs;
2863*0a6a1f1dSLionel Sambuc   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2864*0a6a1f1dSLionel Sambuc   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2865*0a6a1f1dSLionel Sambuc                                                  &SelExprs[0], SelExprs.size(),
2866*0a6a1f1dSLionel Sambuc                                                   StartLoc,
2867*0a6a1f1dSLionel Sambuc                                                   EndLoc);
2868*0a6a1f1dSLionel Sambuc   MsgExprs.push_back(SelExp);
2869*0a6a1f1dSLionel Sambuc 
2870*0a6a1f1dSLionel Sambuc   // Now push any user supplied arguments.
2871*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2872*0a6a1f1dSLionel Sambuc     Expr *userExpr = Exp->getArg(i);
2873*0a6a1f1dSLionel Sambuc     // Make all implicit casts explicit...ICE comes in handy:-)
2874*0a6a1f1dSLionel Sambuc     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2875*0a6a1f1dSLionel Sambuc       // Reuse the ICE type, it is exactly what the doctor ordered.
2876*0a6a1f1dSLionel Sambuc       QualType type = ICE->getType();
2877*0a6a1f1dSLionel Sambuc       if (needToScanForQualifiers(type))
2878*0a6a1f1dSLionel Sambuc         type = Context->getObjCIdType();
2879*0a6a1f1dSLionel Sambuc       // Make sure we convert "type (^)(...)" to "type (*)(...)".
2880*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(type);
2881*0a6a1f1dSLionel Sambuc       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2882*0a6a1f1dSLionel Sambuc       CastKind CK;
2883*0a6a1f1dSLionel Sambuc       if (SubExpr->getType()->isIntegralType(*Context) &&
2884*0a6a1f1dSLionel Sambuc           type->isBooleanType()) {
2885*0a6a1f1dSLionel Sambuc         CK = CK_IntegralToBoolean;
2886*0a6a1f1dSLionel Sambuc       } else if (type->isObjCObjectPointerType()) {
2887*0a6a1f1dSLionel Sambuc         if (SubExpr->getType()->isBlockPointerType()) {
2888*0a6a1f1dSLionel Sambuc           CK = CK_BlockPointerToObjCPointerCast;
2889*0a6a1f1dSLionel Sambuc         } else if (SubExpr->getType()->isPointerType()) {
2890*0a6a1f1dSLionel Sambuc           CK = CK_CPointerToObjCPointerCast;
2891*0a6a1f1dSLionel Sambuc         } else {
2892*0a6a1f1dSLionel Sambuc           CK = CK_BitCast;
2893*0a6a1f1dSLionel Sambuc         }
2894*0a6a1f1dSLionel Sambuc       } else {
2895*0a6a1f1dSLionel Sambuc         CK = CK_BitCast;
2896*0a6a1f1dSLionel Sambuc       }
2897*0a6a1f1dSLionel Sambuc 
2898*0a6a1f1dSLionel Sambuc       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2899*0a6a1f1dSLionel Sambuc     }
2900*0a6a1f1dSLionel Sambuc     // Make id<P...> cast into an 'id' cast.
2901*0a6a1f1dSLionel Sambuc     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2902*0a6a1f1dSLionel Sambuc       if (CE->getType()->isObjCQualifiedIdType()) {
2903*0a6a1f1dSLionel Sambuc         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2904*0a6a1f1dSLionel Sambuc           userExpr = CE->getSubExpr();
2905*0a6a1f1dSLionel Sambuc         CastKind CK;
2906*0a6a1f1dSLionel Sambuc         if (userExpr->getType()->isIntegralType(*Context)) {
2907*0a6a1f1dSLionel Sambuc           CK = CK_IntegralToPointer;
2908*0a6a1f1dSLionel Sambuc         } else if (userExpr->getType()->isBlockPointerType()) {
2909*0a6a1f1dSLionel Sambuc           CK = CK_BlockPointerToObjCPointerCast;
2910*0a6a1f1dSLionel Sambuc         } else if (userExpr->getType()->isPointerType()) {
2911*0a6a1f1dSLionel Sambuc           CK = CK_CPointerToObjCPointerCast;
2912*0a6a1f1dSLionel Sambuc         } else {
2913*0a6a1f1dSLionel Sambuc           CK = CK_BitCast;
2914*0a6a1f1dSLionel Sambuc         }
2915*0a6a1f1dSLionel Sambuc         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2916*0a6a1f1dSLionel Sambuc                                             CK, userExpr);
2917*0a6a1f1dSLionel Sambuc       }
2918*0a6a1f1dSLionel Sambuc     }
2919*0a6a1f1dSLionel Sambuc     MsgExprs.push_back(userExpr);
2920*0a6a1f1dSLionel Sambuc     // We've transferred the ownership to MsgExprs. For now, we *don't* null
2921*0a6a1f1dSLionel Sambuc     // out the argument in the original expression (since we aren't deleting
2922*0a6a1f1dSLionel Sambuc     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2923*0a6a1f1dSLionel Sambuc     //Exp->setArg(i, 0);
2924*0a6a1f1dSLionel Sambuc   }
2925*0a6a1f1dSLionel Sambuc   // Generate the funky cast.
2926*0a6a1f1dSLionel Sambuc   CastExpr *cast;
2927*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
2928*0a6a1f1dSLionel Sambuc   QualType returnType;
2929*0a6a1f1dSLionel Sambuc 
2930*0a6a1f1dSLionel Sambuc   // Push 'id' and 'SEL', the 2 implicit arguments.
2931*0a6a1f1dSLionel Sambuc   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2932*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2933*0a6a1f1dSLionel Sambuc   else
2934*0a6a1f1dSLionel Sambuc     ArgTypes.push_back(Context->getObjCIdType());
2935*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(Context->getObjCSelType());
2936*0a6a1f1dSLionel Sambuc   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2937*0a6a1f1dSLionel Sambuc     // Push any user argument types.
2938*0a6a1f1dSLionel Sambuc     for (const auto *PI : OMD->params()) {
2939*0a6a1f1dSLionel Sambuc       QualType t = PI->getType()->isObjCQualifiedIdType()
2940*0a6a1f1dSLionel Sambuc                      ? Context->getObjCIdType()
2941*0a6a1f1dSLionel Sambuc                      : PI->getType();
2942*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
2943*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(t);
2944*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
2945*0a6a1f1dSLionel Sambuc     }
2946*0a6a1f1dSLionel Sambuc     returnType = Exp->getType();
2947*0a6a1f1dSLionel Sambuc     convertToUnqualifiedObjCType(returnType);
2948*0a6a1f1dSLionel Sambuc     (void)convertBlockPointerToFunctionPointer(returnType);
2949*0a6a1f1dSLionel Sambuc   } else {
2950*0a6a1f1dSLionel Sambuc     returnType = Context->getObjCIdType();
2951*0a6a1f1dSLionel Sambuc   }
2952*0a6a1f1dSLionel Sambuc   // Get the type, we will need to reference it in a couple spots.
2953*0a6a1f1dSLionel Sambuc   QualType msgSendType = MsgSendFlavor->getType();
2954*0a6a1f1dSLionel Sambuc 
2955*0a6a1f1dSLionel Sambuc   // Create a reference to the objc_msgSend() declaration.
2956*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2957*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
2958*0a6a1f1dSLionel Sambuc 
2959*0a6a1f1dSLionel Sambuc   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2960*0a6a1f1dSLionel Sambuc   // If we don't do this cast, we get the following bizarre warning/note:
2961*0a6a1f1dSLionel Sambuc   // xx.m:13: warning: function called through a non-compatible type
2962*0a6a1f1dSLionel Sambuc   // xx.m:13: note: if this code is reached, the program will abort
2963*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context,
2964*0a6a1f1dSLionel Sambuc                                   Context->getPointerType(Context->VoidTy),
2965*0a6a1f1dSLionel Sambuc                                   CK_BitCast, DRE);
2966*0a6a1f1dSLionel Sambuc 
2967*0a6a1f1dSLionel Sambuc   // Now do the "normal" pointer to function cast.
2968*0a6a1f1dSLionel Sambuc   // If we don't have a method decl, force a variadic cast.
2969*0a6a1f1dSLionel Sambuc   const ObjCMethodDecl *MD = Exp->getMethodDecl();
2970*0a6a1f1dSLionel Sambuc   QualType castType =
2971*0a6a1f1dSLionel Sambuc     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
2972*0a6a1f1dSLionel Sambuc   castType = Context->getPointerType(castType);
2973*0a6a1f1dSLionel Sambuc   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2974*0a6a1f1dSLionel Sambuc                                   cast);
2975*0a6a1f1dSLionel Sambuc 
2976*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
2977*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2978*0a6a1f1dSLionel Sambuc 
2979*0a6a1f1dSLionel Sambuc   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2980*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context)
2981*0a6a1f1dSLionel Sambuc       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2982*0a6a1f1dSLionel Sambuc   Stmt *ReplacingStmt = CE;
2983*0a6a1f1dSLionel Sambuc   if (MsgSendStretFlavor) {
2984*0a6a1f1dSLionel Sambuc     // We have the method which returns a struct/union. Must also generate
2985*0a6a1f1dSLionel Sambuc     // call to objc_msgSend_stret and hang both varieties on a conditional
2986*0a6a1f1dSLionel Sambuc     // expression which dictate which one to envoke depending on size of
2987*0a6a1f1dSLionel Sambuc     // method's return type.
2988*0a6a1f1dSLionel Sambuc 
2989*0a6a1f1dSLionel Sambuc     CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2990*0a6a1f1dSLionel Sambuc                                                msgSendType, returnType,
2991*0a6a1f1dSLionel Sambuc                                                ArgTypes, MsgExprs,
2992*0a6a1f1dSLionel Sambuc                                                Exp->getMethodDecl());
2993*0a6a1f1dSLionel Sambuc 
2994*0a6a1f1dSLionel Sambuc     // Build sizeof(returnType)
2995*0a6a1f1dSLionel Sambuc     UnaryExprOrTypeTraitExpr *sizeofExpr =
2996*0a6a1f1dSLionel Sambuc        new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2997*0a6a1f1dSLionel Sambuc                                  Context->getTrivialTypeSourceInfo(returnType),
2998*0a6a1f1dSLionel Sambuc                                  Context->getSizeType(), SourceLocation(),
2999*0a6a1f1dSLionel Sambuc                                  SourceLocation());
3000*0a6a1f1dSLionel Sambuc     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3001*0a6a1f1dSLionel Sambuc     // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3002*0a6a1f1dSLionel Sambuc     // For X86 it is more complicated and some kind of target specific routine
3003*0a6a1f1dSLionel Sambuc     // is needed to decide what to do.
3004*0a6a1f1dSLionel Sambuc     unsigned IntSize =
3005*0a6a1f1dSLionel Sambuc       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3006*0a6a1f1dSLionel Sambuc     IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3007*0a6a1f1dSLionel Sambuc                                                    llvm::APInt(IntSize, 8),
3008*0a6a1f1dSLionel Sambuc                                                    Context->IntTy,
3009*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
3010*0a6a1f1dSLionel Sambuc     BinaryOperator *lessThanExpr =
3011*0a6a1f1dSLionel Sambuc       new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3012*0a6a1f1dSLionel Sambuc                                    VK_RValue, OK_Ordinary, SourceLocation(),
3013*0a6a1f1dSLionel Sambuc                                    false);
3014*0a6a1f1dSLionel Sambuc     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3015*0a6a1f1dSLionel Sambuc     ConditionalOperator *CondExpr =
3016*0a6a1f1dSLionel Sambuc       new (Context) ConditionalOperator(lessThanExpr,
3017*0a6a1f1dSLionel Sambuc                                         SourceLocation(), CE,
3018*0a6a1f1dSLionel Sambuc                                         SourceLocation(), STCE,
3019*0a6a1f1dSLionel Sambuc                                         returnType, VK_RValue, OK_Ordinary);
3020*0a6a1f1dSLionel Sambuc     ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3021*0a6a1f1dSLionel Sambuc                                             CondExpr);
3022*0a6a1f1dSLionel Sambuc   }
3023*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3024*0a6a1f1dSLionel Sambuc   return ReplacingStmt;
3025*0a6a1f1dSLionel Sambuc }
3026*0a6a1f1dSLionel Sambuc 
RewriteMessageExpr(ObjCMessageExpr * Exp)3027*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3028*0a6a1f1dSLionel Sambuc   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3029*0a6a1f1dSLionel Sambuc                                          Exp->getLocEnd());
3030*0a6a1f1dSLionel Sambuc 
3031*0a6a1f1dSLionel Sambuc   // Now do the actual rewrite.
3032*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, ReplacingStmt);
3033*0a6a1f1dSLionel Sambuc 
3034*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3035*0a6a1f1dSLionel Sambuc   return ReplacingStmt;
3036*0a6a1f1dSLionel Sambuc }
3037*0a6a1f1dSLionel Sambuc 
3038*0a6a1f1dSLionel Sambuc // typedef struct objc_object Protocol;
getProtocolType()3039*0a6a1f1dSLionel Sambuc QualType RewriteObjC::getProtocolType() {
3040*0a6a1f1dSLionel Sambuc   if (!ProtocolTypeDecl) {
3041*0a6a1f1dSLionel Sambuc     TypeSourceInfo *TInfo
3042*0a6a1f1dSLionel Sambuc       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3043*0a6a1f1dSLionel Sambuc     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3044*0a6a1f1dSLionel Sambuc                                            SourceLocation(), SourceLocation(),
3045*0a6a1f1dSLionel Sambuc                                            &Context->Idents.get("Protocol"),
3046*0a6a1f1dSLionel Sambuc                                            TInfo);
3047*0a6a1f1dSLionel Sambuc   }
3048*0a6a1f1dSLionel Sambuc   return Context->getTypeDeclType(ProtocolTypeDecl);
3049*0a6a1f1dSLionel Sambuc }
3050*0a6a1f1dSLionel Sambuc 
3051*0a6a1f1dSLionel Sambuc /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3052*0a6a1f1dSLionel Sambuc /// a synthesized/forward data reference (to the protocol's metadata).
3053*0a6a1f1dSLionel Sambuc /// The forward references (and metadata) are generated in
3054*0a6a1f1dSLionel Sambuc /// RewriteObjC::HandleTranslationUnit().
RewriteObjCProtocolExpr(ObjCProtocolExpr * Exp)3055*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3056*0a6a1f1dSLionel Sambuc   std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3057*0a6a1f1dSLionel Sambuc   IdentifierInfo *ID = &Context->Idents.get(Name);
3058*0a6a1f1dSLionel Sambuc   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3059*0a6a1f1dSLionel Sambuc                                 SourceLocation(), ID, getProtocolType(),
3060*0a6a1f1dSLionel Sambuc                                 nullptr, SC_Extern);
3061*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3062*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
3063*0a6a1f1dSLionel Sambuc   Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3064*0a6a1f1dSLionel Sambuc                              Context->getPointerType(DRE->getType()),
3065*0a6a1f1dSLionel Sambuc                              VK_RValue, OK_Ordinary, SourceLocation());
3066*0a6a1f1dSLionel Sambuc   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3067*0a6a1f1dSLionel Sambuc                                                 CK_BitCast,
3068*0a6a1f1dSLionel Sambuc                                                 DerefExpr);
3069*0a6a1f1dSLionel Sambuc   ReplaceStmt(Exp, castExpr);
3070*0a6a1f1dSLionel Sambuc   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3071*0a6a1f1dSLionel Sambuc   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3072*0a6a1f1dSLionel Sambuc   return castExpr;
3073*0a6a1f1dSLionel Sambuc 
3074*0a6a1f1dSLionel Sambuc }
3075*0a6a1f1dSLionel Sambuc 
BufferContainsPPDirectives(const char * startBuf,const char * endBuf)3076*0a6a1f1dSLionel Sambuc bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3077*0a6a1f1dSLionel Sambuc                                              const char *endBuf) {
3078*0a6a1f1dSLionel Sambuc   while (startBuf < endBuf) {
3079*0a6a1f1dSLionel Sambuc     if (*startBuf == '#') {
3080*0a6a1f1dSLionel Sambuc       // Skip whitespace.
3081*0a6a1f1dSLionel Sambuc       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3082*0a6a1f1dSLionel Sambuc         ;
3083*0a6a1f1dSLionel Sambuc       if (!strncmp(startBuf, "if", strlen("if")) ||
3084*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3085*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3086*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "define", strlen("define")) ||
3087*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "undef", strlen("undef")) ||
3088*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "else", strlen("else")) ||
3089*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "elif", strlen("elif")) ||
3090*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "endif", strlen("endif")) ||
3091*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "pragma", strlen("pragma")) ||
3092*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "include", strlen("include")) ||
3093*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "import", strlen("import")) ||
3094*0a6a1f1dSLionel Sambuc           !strncmp(startBuf, "include_next", strlen("include_next")))
3095*0a6a1f1dSLionel Sambuc         return true;
3096*0a6a1f1dSLionel Sambuc     }
3097*0a6a1f1dSLionel Sambuc     startBuf++;
3098*0a6a1f1dSLionel Sambuc   }
3099*0a6a1f1dSLionel Sambuc   return false;
3100*0a6a1f1dSLionel Sambuc }
3101*0a6a1f1dSLionel Sambuc 
3102*0a6a1f1dSLionel Sambuc /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3103*0a6a1f1dSLionel Sambuc /// an objective-c class with ivars.
RewriteObjCInternalStruct(ObjCInterfaceDecl * CDecl,std::string & Result)3104*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3105*0a6a1f1dSLionel Sambuc                                                std::string &Result) {
3106*0a6a1f1dSLionel Sambuc   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3107*0a6a1f1dSLionel Sambuc   assert(CDecl->getName() != "" &&
3108*0a6a1f1dSLionel Sambuc          "Name missing in SynthesizeObjCInternalStruct");
3109*0a6a1f1dSLionel Sambuc   // Do not synthesize more than once.
3110*0a6a1f1dSLionel Sambuc   if (ObjCSynthesizedStructs.count(CDecl))
3111*0a6a1f1dSLionel Sambuc     return;
3112*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3113*0a6a1f1dSLionel Sambuc   int NumIvars = CDecl->ivar_size();
3114*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CDecl->getLocStart();
3115*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3116*0a6a1f1dSLionel Sambuc 
3117*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
3118*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
3119*0a6a1f1dSLionel Sambuc 
3120*0a6a1f1dSLionel Sambuc   // If no ivars and no root or if its root, directly or indirectly,
3121*0a6a1f1dSLionel Sambuc   // have no ivars (thus not synthesized) then no need to synthesize this class.
3122*0a6a1f1dSLionel Sambuc   if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3123*0a6a1f1dSLionel Sambuc       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3124*0a6a1f1dSLionel Sambuc     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3125*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, Result);
3126*0a6a1f1dSLionel Sambuc     return;
3127*0a6a1f1dSLionel Sambuc   }
3128*0a6a1f1dSLionel Sambuc 
3129*0a6a1f1dSLionel Sambuc   // FIXME: This has potential of causing problem. If
3130*0a6a1f1dSLionel Sambuc   // SynthesizeObjCInternalStruct is ever called recursively.
3131*0a6a1f1dSLionel Sambuc   Result += "\nstruct ";
3132*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
3133*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt)
3134*0a6a1f1dSLionel Sambuc     Result += "_IMPL";
3135*0a6a1f1dSLionel Sambuc 
3136*0a6a1f1dSLionel Sambuc   if (NumIvars > 0) {
3137*0a6a1f1dSLionel Sambuc     const char *cursor = strchr(startBuf, '{');
3138*0a6a1f1dSLionel Sambuc     assert((cursor && endBuf)
3139*0a6a1f1dSLionel Sambuc            && "SynthesizeObjCInternalStruct - malformed @interface");
3140*0a6a1f1dSLionel Sambuc     // If the buffer contains preprocessor directives, we do more fine-grained
3141*0a6a1f1dSLionel Sambuc     // rewrites. This is intended to fix code that looks like (which occurs in
3142*0a6a1f1dSLionel Sambuc     // NSURL.h, for example):
3143*0a6a1f1dSLionel Sambuc     //
3144*0a6a1f1dSLionel Sambuc     // #ifdef XYZ
3145*0a6a1f1dSLionel Sambuc     // @interface Foo : NSObject
3146*0a6a1f1dSLionel Sambuc     // #else
3147*0a6a1f1dSLionel Sambuc     // @interface FooBar : NSObject
3148*0a6a1f1dSLionel Sambuc     // #endif
3149*0a6a1f1dSLionel Sambuc     // {
3150*0a6a1f1dSLionel Sambuc     //    int i;
3151*0a6a1f1dSLionel Sambuc     // }
3152*0a6a1f1dSLionel Sambuc     // @end
3153*0a6a1f1dSLionel Sambuc     //
3154*0a6a1f1dSLionel Sambuc     // This clause is segregated to avoid breaking the common case.
3155*0a6a1f1dSLionel Sambuc     if (BufferContainsPPDirectives(startBuf, cursor)) {
3156*0a6a1f1dSLionel Sambuc       SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3157*0a6a1f1dSLionel Sambuc                                   CDecl->getAtStartLoc();
3158*0a6a1f1dSLionel Sambuc       const char *endHeader = SM->getCharacterData(L);
3159*0a6a1f1dSLionel Sambuc       endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3160*0a6a1f1dSLionel Sambuc 
3161*0a6a1f1dSLionel Sambuc       if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3162*0a6a1f1dSLionel Sambuc         // advance to the end of the referenced protocols.
3163*0a6a1f1dSLionel Sambuc         while (endHeader < cursor && *endHeader != '>') endHeader++;
3164*0a6a1f1dSLionel Sambuc         endHeader++;
3165*0a6a1f1dSLionel Sambuc       }
3166*0a6a1f1dSLionel Sambuc       // rewrite the original header
3167*0a6a1f1dSLionel Sambuc       ReplaceText(LocStart, endHeader-startBuf, Result);
3168*0a6a1f1dSLionel Sambuc     } else {
3169*0a6a1f1dSLionel Sambuc       // rewrite the original header *without* disturbing the '{'
3170*0a6a1f1dSLionel Sambuc       ReplaceText(LocStart, cursor-startBuf, Result);
3171*0a6a1f1dSLionel Sambuc     }
3172*0a6a1f1dSLionel Sambuc     if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3173*0a6a1f1dSLionel Sambuc       Result = "\n    struct ";
3174*0a6a1f1dSLionel Sambuc       Result += RCDecl->getNameAsString();
3175*0a6a1f1dSLionel Sambuc       Result += "_IMPL ";
3176*0a6a1f1dSLionel Sambuc       Result += RCDecl->getNameAsString();
3177*0a6a1f1dSLionel Sambuc       Result += "_IVARS;\n";
3178*0a6a1f1dSLionel Sambuc 
3179*0a6a1f1dSLionel Sambuc       // insert the super class structure definition.
3180*0a6a1f1dSLionel Sambuc       SourceLocation OnePastCurly =
3181*0a6a1f1dSLionel Sambuc         LocStart.getLocWithOffset(cursor-startBuf+1);
3182*0a6a1f1dSLionel Sambuc       InsertText(OnePastCurly, Result);
3183*0a6a1f1dSLionel Sambuc     }
3184*0a6a1f1dSLionel Sambuc     cursor++; // past '{'
3185*0a6a1f1dSLionel Sambuc 
3186*0a6a1f1dSLionel Sambuc     // Now comment out any visibility specifiers.
3187*0a6a1f1dSLionel Sambuc     while (cursor < endBuf) {
3188*0a6a1f1dSLionel Sambuc       if (*cursor == '@') {
3189*0a6a1f1dSLionel Sambuc         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3190*0a6a1f1dSLionel Sambuc         // Skip whitespace.
3191*0a6a1f1dSLionel Sambuc         for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3192*0a6a1f1dSLionel Sambuc           /*scan*/;
3193*0a6a1f1dSLionel Sambuc 
3194*0a6a1f1dSLionel Sambuc         // FIXME: presence of @public, etc. inside comment results in
3195*0a6a1f1dSLionel Sambuc         // this transformation as well, which is still correct c-code.
3196*0a6a1f1dSLionel Sambuc         if (!strncmp(cursor, "public", strlen("public")) ||
3197*0a6a1f1dSLionel Sambuc             !strncmp(cursor, "private", strlen("private")) ||
3198*0a6a1f1dSLionel Sambuc             !strncmp(cursor, "package", strlen("package")) ||
3199*0a6a1f1dSLionel Sambuc             !strncmp(cursor, "protected", strlen("protected")))
3200*0a6a1f1dSLionel Sambuc           InsertText(atLoc, "// ");
3201*0a6a1f1dSLionel Sambuc       }
3202*0a6a1f1dSLionel Sambuc       // FIXME: If there are cases where '<' is used in ivar declaration part
3203*0a6a1f1dSLionel Sambuc       // of user code, then scan the ivar list and use needToScanForQualifiers
3204*0a6a1f1dSLionel Sambuc       // for type checking.
3205*0a6a1f1dSLionel Sambuc       else if (*cursor == '<') {
3206*0a6a1f1dSLionel Sambuc         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3207*0a6a1f1dSLionel Sambuc         InsertText(atLoc, "/* ");
3208*0a6a1f1dSLionel Sambuc         cursor = strchr(cursor, '>');
3209*0a6a1f1dSLionel Sambuc         cursor++;
3210*0a6a1f1dSLionel Sambuc         atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3211*0a6a1f1dSLionel Sambuc         InsertText(atLoc, " */");
3212*0a6a1f1dSLionel Sambuc       } else if (*cursor == '^') { // rewrite block specifier.
3213*0a6a1f1dSLionel Sambuc         SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3214*0a6a1f1dSLionel Sambuc         ReplaceText(caretLoc, 1, "*");
3215*0a6a1f1dSLionel Sambuc       }
3216*0a6a1f1dSLionel Sambuc       cursor++;
3217*0a6a1f1dSLionel Sambuc     }
3218*0a6a1f1dSLionel Sambuc     // Don't forget to add a ';'!!
3219*0a6a1f1dSLionel Sambuc     InsertText(LocEnd.getLocWithOffset(1), ";");
3220*0a6a1f1dSLionel Sambuc   } else { // we don't have any instance variables - insert super struct.
3221*0a6a1f1dSLionel Sambuc     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3222*0a6a1f1dSLionel Sambuc     Result += " {\n    struct ";
3223*0a6a1f1dSLionel Sambuc     Result += RCDecl->getNameAsString();
3224*0a6a1f1dSLionel Sambuc     Result += "_IMPL ";
3225*0a6a1f1dSLionel Sambuc     Result += RCDecl->getNameAsString();
3226*0a6a1f1dSLionel Sambuc     Result += "_IVARS;\n};\n";
3227*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf, Result);
3228*0a6a1f1dSLionel Sambuc   }
3229*0a6a1f1dSLionel Sambuc   // Mark this struct as having been generated.
3230*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3231*0a6a1f1dSLionel Sambuc     llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3232*0a6a1f1dSLionel Sambuc }
3233*0a6a1f1dSLionel Sambuc 
3234*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
3235*0a6a1f1dSLionel Sambuc // Meta Data Emission
3236*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
3237*0a6a1f1dSLionel Sambuc 
3238*0a6a1f1dSLionel Sambuc 
3239*0a6a1f1dSLionel Sambuc /// RewriteImplementations - This routine rewrites all method implementations
3240*0a6a1f1dSLionel Sambuc /// and emits meta-data.
3241*0a6a1f1dSLionel Sambuc 
RewriteImplementations()3242*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteImplementations() {
3243*0a6a1f1dSLionel Sambuc   int ClsDefCount = ClassImplementation.size();
3244*0a6a1f1dSLionel Sambuc   int CatDefCount = CategoryImplementation.size();
3245*0a6a1f1dSLionel Sambuc 
3246*0a6a1f1dSLionel Sambuc   // Rewrite implemented methods
3247*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++)
3248*0a6a1f1dSLionel Sambuc     RewriteImplementationDecl(ClassImplementation[i]);
3249*0a6a1f1dSLionel Sambuc 
3250*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++)
3251*0a6a1f1dSLionel Sambuc     RewriteImplementationDecl(CategoryImplementation[i]);
3252*0a6a1f1dSLionel Sambuc }
3253*0a6a1f1dSLionel Sambuc 
RewriteByRefString(std::string & ResultStr,const std::string & Name,ValueDecl * VD,bool def)3254*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3255*0a6a1f1dSLionel Sambuc                                      const std::string &Name,
3256*0a6a1f1dSLionel Sambuc                                      ValueDecl *VD, bool def) {
3257*0a6a1f1dSLionel Sambuc   assert(BlockByRefDeclNo.count(VD) &&
3258*0a6a1f1dSLionel Sambuc          "RewriteByRefString: ByRef decl missing");
3259*0a6a1f1dSLionel Sambuc   if (def)
3260*0a6a1f1dSLionel Sambuc     ResultStr += "struct ";
3261*0a6a1f1dSLionel Sambuc   ResultStr += "__Block_byref_" + Name +
3262*0a6a1f1dSLionel Sambuc     "_" + utostr(BlockByRefDeclNo[VD]) ;
3263*0a6a1f1dSLionel Sambuc }
3264*0a6a1f1dSLionel Sambuc 
HasLocalVariableExternalStorage(ValueDecl * VD)3265*0a6a1f1dSLionel Sambuc static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3266*0a6a1f1dSLionel Sambuc   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3267*0a6a1f1dSLionel Sambuc     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3268*0a6a1f1dSLionel Sambuc   return false;
3269*0a6a1f1dSLionel Sambuc }
3270*0a6a1f1dSLionel Sambuc 
SynthesizeBlockFunc(BlockExpr * CE,int i,StringRef funcName,std::string Tag)3271*0a6a1f1dSLionel Sambuc std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3272*0a6a1f1dSLionel Sambuc                                                    StringRef funcName,
3273*0a6a1f1dSLionel Sambuc                                                    std::string Tag) {
3274*0a6a1f1dSLionel Sambuc   const FunctionType *AFT = CE->getFunctionType();
3275*0a6a1f1dSLionel Sambuc   QualType RT = AFT->getReturnType();
3276*0a6a1f1dSLionel Sambuc   std::string StructRef = "struct " + Tag;
3277*0a6a1f1dSLionel Sambuc   std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3278*0a6a1f1dSLionel Sambuc                   funcName.str() + "_" + "block_func_" + utostr(i);
3279*0a6a1f1dSLionel Sambuc 
3280*0a6a1f1dSLionel Sambuc   BlockDecl *BD = CE->getBlockDecl();
3281*0a6a1f1dSLionel Sambuc 
3282*0a6a1f1dSLionel Sambuc   if (isa<FunctionNoProtoType>(AFT)) {
3283*0a6a1f1dSLionel Sambuc     // No user-supplied arguments. Still need to pass in a pointer to the
3284*0a6a1f1dSLionel Sambuc     // block (to reference imported block decl refs).
3285*0a6a1f1dSLionel Sambuc     S += "(" + StructRef + " *__cself)";
3286*0a6a1f1dSLionel Sambuc   } else if (BD->param_empty()) {
3287*0a6a1f1dSLionel Sambuc     S += "(" + StructRef + " *__cself)";
3288*0a6a1f1dSLionel Sambuc   } else {
3289*0a6a1f1dSLionel Sambuc     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3290*0a6a1f1dSLionel Sambuc     assert(FT && "SynthesizeBlockFunc: No function proto");
3291*0a6a1f1dSLionel Sambuc     S += '(';
3292*0a6a1f1dSLionel Sambuc     // first add the implicit argument.
3293*0a6a1f1dSLionel Sambuc     S += StructRef + " *__cself, ";
3294*0a6a1f1dSLionel Sambuc     std::string ParamStr;
3295*0a6a1f1dSLionel Sambuc     for (BlockDecl::param_iterator AI = BD->param_begin(),
3296*0a6a1f1dSLionel Sambuc          E = BD->param_end(); AI != E; ++AI) {
3297*0a6a1f1dSLionel Sambuc       if (AI != BD->param_begin()) S += ", ";
3298*0a6a1f1dSLionel Sambuc       ParamStr = (*AI)->getNameAsString();
3299*0a6a1f1dSLionel Sambuc       QualType QT = (*AI)->getType();
3300*0a6a1f1dSLionel Sambuc       (void)convertBlockPointerToFunctionPointer(QT);
3301*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3302*0a6a1f1dSLionel Sambuc       S += ParamStr;
3303*0a6a1f1dSLionel Sambuc     }
3304*0a6a1f1dSLionel Sambuc     if (FT->isVariadic()) {
3305*0a6a1f1dSLionel Sambuc       if (!BD->param_empty()) S += ", ";
3306*0a6a1f1dSLionel Sambuc       S += "...";
3307*0a6a1f1dSLionel Sambuc     }
3308*0a6a1f1dSLionel Sambuc     S += ')';
3309*0a6a1f1dSLionel Sambuc   }
3310*0a6a1f1dSLionel Sambuc   S += " {\n";
3311*0a6a1f1dSLionel Sambuc 
3312*0a6a1f1dSLionel Sambuc   // Create local declarations to avoid rewriting all closure decl ref exprs.
3313*0a6a1f1dSLionel Sambuc   // First, emit a declaration for all "by ref" decls.
3314*0a6a1f1dSLionel Sambuc   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3315*0a6a1f1dSLionel Sambuc        E = BlockByRefDecls.end(); I != E; ++I) {
3316*0a6a1f1dSLionel Sambuc     S += "  ";
3317*0a6a1f1dSLionel Sambuc     std::string Name = (*I)->getNameAsString();
3318*0a6a1f1dSLionel Sambuc     std::string TypeString;
3319*0a6a1f1dSLionel Sambuc     RewriteByRefString(TypeString, Name, (*I));
3320*0a6a1f1dSLionel Sambuc     TypeString += " *";
3321*0a6a1f1dSLionel Sambuc     Name = TypeString + Name;
3322*0a6a1f1dSLionel Sambuc     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3323*0a6a1f1dSLionel Sambuc   }
3324*0a6a1f1dSLionel Sambuc   // Next, emit a declaration for all "by copy" declarations.
3325*0a6a1f1dSLionel Sambuc   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3326*0a6a1f1dSLionel Sambuc        E = BlockByCopyDecls.end(); I != E; ++I) {
3327*0a6a1f1dSLionel Sambuc     S += "  ";
3328*0a6a1f1dSLionel Sambuc     // Handle nested closure invocation. For example:
3329*0a6a1f1dSLionel Sambuc     //
3330*0a6a1f1dSLionel Sambuc     //   void (^myImportedClosure)(void);
3331*0a6a1f1dSLionel Sambuc     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3332*0a6a1f1dSLionel Sambuc     //
3333*0a6a1f1dSLionel Sambuc     //   void (^anotherClosure)(void);
3334*0a6a1f1dSLionel Sambuc     //   anotherClosure = ^(void) {
3335*0a6a1f1dSLionel Sambuc     //     myImportedClosure(); // import and invoke the closure
3336*0a6a1f1dSLionel Sambuc     //   };
3337*0a6a1f1dSLionel Sambuc     //
3338*0a6a1f1dSLionel Sambuc     if (isTopLevelBlockPointerType((*I)->getType())) {
3339*0a6a1f1dSLionel Sambuc       RewriteBlockPointerTypeVariable(S, (*I));
3340*0a6a1f1dSLionel Sambuc       S += " = (";
3341*0a6a1f1dSLionel Sambuc       RewriteBlockPointerType(S, (*I)->getType());
3342*0a6a1f1dSLionel Sambuc       S += ")";
3343*0a6a1f1dSLionel Sambuc       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3344*0a6a1f1dSLionel Sambuc     }
3345*0a6a1f1dSLionel Sambuc     else {
3346*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
3347*0a6a1f1dSLionel Sambuc       QualType QT = (*I)->getType();
3348*0a6a1f1dSLionel Sambuc       if (HasLocalVariableExternalStorage(*I))
3349*0a6a1f1dSLionel Sambuc         QT = Context->getPointerType(QT);
3350*0a6a1f1dSLionel Sambuc       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3351*0a6a1f1dSLionel Sambuc       S += Name + " = __cself->" +
3352*0a6a1f1dSLionel Sambuc                               (*I)->getNameAsString() + "; // bound by copy\n";
3353*0a6a1f1dSLionel Sambuc     }
3354*0a6a1f1dSLionel Sambuc   }
3355*0a6a1f1dSLionel Sambuc   std::string RewrittenStr = RewrittenBlockExprs[CE];
3356*0a6a1f1dSLionel Sambuc   const char *cstr = RewrittenStr.c_str();
3357*0a6a1f1dSLionel Sambuc   while (*cstr++ != '{') ;
3358*0a6a1f1dSLionel Sambuc   S += cstr;
3359*0a6a1f1dSLionel Sambuc   S += "\n";
3360*0a6a1f1dSLionel Sambuc   return S;
3361*0a6a1f1dSLionel Sambuc }
3362*0a6a1f1dSLionel Sambuc 
SynthesizeBlockHelperFuncs(BlockExpr * CE,int i,StringRef funcName,std::string Tag)3363*0a6a1f1dSLionel Sambuc std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3364*0a6a1f1dSLionel Sambuc                                                    StringRef funcName,
3365*0a6a1f1dSLionel Sambuc                                                    std::string Tag) {
3366*0a6a1f1dSLionel Sambuc   std::string StructRef = "struct " + Tag;
3367*0a6a1f1dSLionel Sambuc   std::string S = "static void __";
3368*0a6a1f1dSLionel Sambuc 
3369*0a6a1f1dSLionel Sambuc   S += funcName;
3370*0a6a1f1dSLionel Sambuc   S += "_block_copy_" + utostr(i);
3371*0a6a1f1dSLionel Sambuc   S += "(" + StructRef;
3372*0a6a1f1dSLionel Sambuc   S += "*dst, " + StructRef;
3373*0a6a1f1dSLionel Sambuc   S += "*src) {";
3374*0a6a1f1dSLionel Sambuc   for (ValueDecl *VD : ImportedBlockDecls) {
3375*0a6a1f1dSLionel Sambuc     S += "_Block_object_assign((void*)&dst->";
3376*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
3377*0a6a1f1dSLionel Sambuc     S += ", (void*)src->";
3378*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
3379*0a6a1f1dSLionel Sambuc     if (BlockByRefDeclsPtrSet.count(VD))
3380*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3381*0a6a1f1dSLionel Sambuc     else if (VD->getType()->isBlockPointerType())
3382*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3383*0a6a1f1dSLionel Sambuc     else
3384*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3385*0a6a1f1dSLionel Sambuc   }
3386*0a6a1f1dSLionel Sambuc   S += "}\n";
3387*0a6a1f1dSLionel Sambuc 
3388*0a6a1f1dSLionel Sambuc   S += "\nstatic void __";
3389*0a6a1f1dSLionel Sambuc   S += funcName;
3390*0a6a1f1dSLionel Sambuc   S += "_block_dispose_" + utostr(i);
3391*0a6a1f1dSLionel Sambuc   S += "(" + StructRef;
3392*0a6a1f1dSLionel Sambuc   S += "*src) {";
3393*0a6a1f1dSLionel Sambuc   for (ValueDecl *VD : ImportedBlockDecls) {
3394*0a6a1f1dSLionel Sambuc     S += "_Block_object_dispose((void*)src->";
3395*0a6a1f1dSLionel Sambuc     S += VD->getNameAsString();
3396*0a6a1f1dSLionel Sambuc     if (BlockByRefDeclsPtrSet.count(VD))
3397*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3398*0a6a1f1dSLionel Sambuc     else if (VD->getType()->isBlockPointerType())
3399*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3400*0a6a1f1dSLionel Sambuc     else
3401*0a6a1f1dSLionel Sambuc       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3402*0a6a1f1dSLionel Sambuc   }
3403*0a6a1f1dSLionel Sambuc   S += "}\n";
3404*0a6a1f1dSLionel Sambuc   return S;
3405*0a6a1f1dSLionel Sambuc }
3406*0a6a1f1dSLionel Sambuc 
SynthesizeBlockImpl(BlockExpr * CE,std::string Tag,std::string Desc)3407*0a6a1f1dSLionel Sambuc std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3408*0a6a1f1dSLionel Sambuc                                              std::string Desc) {
3409*0a6a1f1dSLionel Sambuc   std::string S = "\nstruct " + Tag;
3410*0a6a1f1dSLionel Sambuc   std::string Constructor = "  " + Tag;
3411*0a6a1f1dSLionel Sambuc 
3412*0a6a1f1dSLionel Sambuc   S += " {\n  struct __block_impl impl;\n";
3413*0a6a1f1dSLionel Sambuc   S += "  struct " + Desc;
3414*0a6a1f1dSLionel Sambuc   S += "* Desc;\n";
3415*0a6a1f1dSLionel Sambuc 
3416*0a6a1f1dSLionel Sambuc   Constructor += "(void *fp, "; // Invoke function pointer.
3417*0a6a1f1dSLionel Sambuc   Constructor += "struct " + Desc; // Descriptor pointer.
3418*0a6a1f1dSLionel Sambuc   Constructor += " *desc";
3419*0a6a1f1dSLionel Sambuc 
3420*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
3421*0a6a1f1dSLionel Sambuc     // Output all "by copy" declarations.
3422*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3423*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
3424*0a6a1f1dSLionel Sambuc       S += "  ";
3425*0a6a1f1dSLionel Sambuc       std::string FieldName = (*I)->getNameAsString();
3426*0a6a1f1dSLionel Sambuc       std::string ArgName = "_" + FieldName;
3427*0a6a1f1dSLionel Sambuc       // Handle nested closure invocation. For example:
3428*0a6a1f1dSLionel Sambuc       //
3429*0a6a1f1dSLionel Sambuc       //   void (^myImportedBlock)(void);
3430*0a6a1f1dSLionel Sambuc       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3431*0a6a1f1dSLionel Sambuc       //
3432*0a6a1f1dSLionel Sambuc       //   void (^anotherBlock)(void);
3433*0a6a1f1dSLionel Sambuc       //   anotherBlock = ^(void) {
3434*0a6a1f1dSLionel Sambuc       //     myImportedBlock(); // import and invoke the closure
3435*0a6a1f1dSLionel Sambuc       //   };
3436*0a6a1f1dSLionel Sambuc       //
3437*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType((*I)->getType())) {
3438*0a6a1f1dSLionel Sambuc         S += "struct __block_impl *";
3439*0a6a1f1dSLionel Sambuc         Constructor += ", void *" + ArgName;
3440*0a6a1f1dSLionel Sambuc       } else {
3441*0a6a1f1dSLionel Sambuc         QualType QT = (*I)->getType();
3442*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I))
3443*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
3444*0a6a1f1dSLionel Sambuc         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3445*0a6a1f1dSLionel Sambuc         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3446*0a6a1f1dSLionel Sambuc         Constructor += ", " + ArgName;
3447*0a6a1f1dSLionel Sambuc       }
3448*0a6a1f1dSLionel Sambuc       S += FieldName + ";\n";
3449*0a6a1f1dSLionel Sambuc     }
3450*0a6a1f1dSLionel Sambuc     // Output all "by ref" declarations.
3451*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3452*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
3453*0a6a1f1dSLionel Sambuc       S += "  ";
3454*0a6a1f1dSLionel Sambuc       std::string FieldName = (*I)->getNameAsString();
3455*0a6a1f1dSLionel Sambuc       std::string ArgName = "_" + FieldName;
3456*0a6a1f1dSLionel Sambuc       {
3457*0a6a1f1dSLionel Sambuc         std::string TypeString;
3458*0a6a1f1dSLionel Sambuc         RewriteByRefString(TypeString, FieldName, (*I));
3459*0a6a1f1dSLionel Sambuc         TypeString += " *";
3460*0a6a1f1dSLionel Sambuc         FieldName = TypeString + FieldName;
3461*0a6a1f1dSLionel Sambuc         ArgName = TypeString + ArgName;
3462*0a6a1f1dSLionel Sambuc         Constructor += ", " + ArgName;
3463*0a6a1f1dSLionel Sambuc       }
3464*0a6a1f1dSLionel Sambuc       S += FieldName + "; // by ref\n";
3465*0a6a1f1dSLionel Sambuc     }
3466*0a6a1f1dSLionel Sambuc     // Finish writing the constructor.
3467*0a6a1f1dSLionel Sambuc     Constructor += ", int flags=0)";
3468*0a6a1f1dSLionel Sambuc     // Initialize all "by copy" arguments.
3469*0a6a1f1dSLionel Sambuc     bool firsTime = true;
3470*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3471*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
3472*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
3473*0a6a1f1dSLionel Sambuc         if (firsTime) {
3474*0a6a1f1dSLionel Sambuc           Constructor += " : ";
3475*0a6a1f1dSLionel Sambuc           firsTime = false;
3476*0a6a1f1dSLionel Sambuc         }
3477*0a6a1f1dSLionel Sambuc         else
3478*0a6a1f1dSLionel Sambuc           Constructor += ", ";
3479*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType((*I)->getType()))
3480*0a6a1f1dSLionel Sambuc           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3481*0a6a1f1dSLionel Sambuc         else
3482*0a6a1f1dSLionel Sambuc           Constructor += Name + "(_" + Name + ")";
3483*0a6a1f1dSLionel Sambuc     }
3484*0a6a1f1dSLionel Sambuc     // Initialize all "by ref" arguments.
3485*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3486*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
3487*0a6a1f1dSLionel Sambuc       std::string Name = (*I)->getNameAsString();
3488*0a6a1f1dSLionel Sambuc       if (firsTime) {
3489*0a6a1f1dSLionel Sambuc         Constructor += " : ";
3490*0a6a1f1dSLionel Sambuc         firsTime = false;
3491*0a6a1f1dSLionel Sambuc       }
3492*0a6a1f1dSLionel Sambuc       else
3493*0a6a1f1dSLionel Sambuc         Constructor += ", ";
3494*0a6a1f1dSLionel Sambuc       Constructor += Name + "(_" + Name + "->__forwarding)";
3495*0a6a1f1dSLionel Sambuc     }
3496*0a6a1f1dSLionel Sambuc 
3497*0a6a1f1dSLionel Sambuc     Constructor += " {\n";
3498*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl)
3499*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3500*0a6a1f1dSLionel Sambuc     else
3501*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3502*0a6a1f1dSLionel Sambuc     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3503*0a6a1f1dSLionel Sambuc 
3504*0a6a1f1dSLionel Sambuc     Constructor += "    Desc = desc;\n";
3505*0a6a1f1dSLionel Sambuc   } else {
3506*0a6a1f1dSLionel Sambuc     // Finish writing the constructor.
3507*0a6a1f1dSLionel Sambuc     Constructor += ", int flags=0) {\n";
3508*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl)
3509*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3510*0a6a1f1dSLionel Sambuc     else
3511*0a6a1f1dSLionel Sambuc       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3512*0a6a1f1dSLionel Sambuc     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3513*0a6a1f1dSLionel Sambuc     Constructor += "    Desc = desc;\n";
3514*0a6a1f1dSLionel Sambuc   }
3515*0a6a1f1dSLionel Sambuc   Constructor += "  ";
3516*0a6a1f1dSLionel Sambuc   Constructor += "}\n";
3517*0a6a1f1dSLionel Sambuc   S += Constructor;
3518*0a6a1f1dSLionel Sambuc   S += "};\n";
3519*0a6a1f1dSLionel Sambuc   return S;
3520*0a6a1f1dSLionel Sambuc }
3521*0a6a1f1dSLionel Sambuc 
SynthesizeBlockDescriptor(std::string DescTag,std::string ImplTag,int i,StringRef FunName,unsigned hasCopy)3522*0a6a1f1dSLionel Sambuc std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3523*0a6a1f1dSLionel Sambuc                                                    std::string ImplTag, int i,
3524*0a6a1f1dSLionel Sambuc                                                    StringRef FunName,
3525*0a6a1f1dSLionel Sambuc                                                    unsigned hasCopy) {
3526*0a6a1f1dSLionel Sambuc   std::string S = "\nstatic struct " + DescTag;
3527*0a6a1f1dSLionel Sambuc 
3528*0a6a1f1dSLionel Sambuc   S += " {\n  unsigned long reserved;\n";
3529*0a6a1f1dSLionel Sambuc   S += "  unsigned long Block_size;\n";
3530*0a6a1f1dSLionel Sambuc   if (hasCopy) {
3531*0a6a1f1dSLionel Sambuc     S += "  void (*copy)(struct ";
3532*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*, struct ";
3533*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*);\n";
3534*0a6a1f1dSLionel Sambuc 
3535*0a6a1f1dSLionel Sambuc     S += "  void (*dispose)(struct ";
3536*0a6a1f1dSLionel Sambuc     S += ImplTag; S += "*);\n";
3537*0a6a1f1dSLionel Sambuc   }
3538*0a6a1f1dSLionel Sambuc   S += "} ";
3539*0a6a1f1dSLionel Sambuc 
3540*0a6a1f1dSLionel Sambuc   S += DescTag + "_DATA = { 0, sizeof(struct ";
3541*0a6a1f1dSLionel Sambuc   S += ImplTag + ")";
3542*0a6a1f1dSLionel Sambuc   if (hasCopy) {
3543*0a6a1f1dSLionel Sambuc     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3544*0a6a1f1dSLionel Sambuc     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3545*0a6a1f1dSLionel Sambuc   }
3546*0a6a1f1dSLionel Sambuc   S += "};\n";
3547*0a6a1f1dSLionel Sambuc   return S;
3548*0a6a1f1dSLionel Sambuc }
3549*0a6a1f1dSLionel Sambuc 
SynthesizeBlockLiterals(SourceLocation FunLocStart,StringRef FunName)3550*0a6a1f1dSLionel Sambuc void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3551*0a6a1f1dSLionel Sambuc                                           StringRef FunName) {
3552*0a6a1f1dSLionel Sambuc   // Insert declaration for the function in which block literal is used.
3553*0a6a1f1dSLionel Sambuc   if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3554*0a6a1f1dSLionel Sambuc     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3555*0a6a1f1dSLionel Sambuc   bool RewriteSC = (GlobalVarDecl &&
3556*0a6a1f1dSLionel Sambuc                     !Blocks.empty() &&
3557*0a6a1f1dSLionel Sambuc                     GlobalVarDecl->getStorageClass() == SC_Static &&
3558*0a6a1f1dSLionel Sambuc                     GlobalVarDecl->getType().getCVRQualifiers());
3559*0a6a1f1dSLionel Sambuc   if (RewriteSC) {
3560*0a6a1f1dSLionel Sambuc     std::string SC(" void __");
3561*0a6a1f1dSLionel Sambuc     SC += GlobalVarDecl->getNameAsString();
3562*0a6a1f1dSLionel Sambuc     SC += "() {}";
3563*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, SC);
3564*0a6a1f1dSLionel Sambuc   }
3565*0a6a1f1dSLionel Sambuc 
3566*0a6a1f1dSLionel Sambuc   // Insert closures that were part of the function.
3567*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3568*0a6a1f1dSLionel Sambuc     CollectBlockDeclRefInfo(Blocks[i]);
3569*0a6a1f1dSLionel Sambuc     // Need to copy-in the inner copied-in variables not actually used in this
3570*0a6a1f1dSLionel Sambuc     // block.
3571*0a6a1f1dSLionel Sambuc     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3572*0a6a1f1dSLionel Sambuc       DeclRefExpr *Exp = InnerDeclRefs[count++];
3573*0a6a1f1dSLionel Sambuc       ValueDecl *VD = Exp->getDecl();
3574*0a6a1f1dSLionel Sambuc       BlockDeclRefs.push_back(Exp);
3575*0a6a1f1dSLionel Sambuc       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3576*0a6a1f1dSLionel Sambuc         BlockByCopyDeclsPtrSet.insert(VD);
3577*0a6a1f1dSLionel Sambuc         BlockByCopyDecls.push_back(VD);
3578*0a6a1f1dSLionel Sambuc       }
3579*0a6a1f1dSLionel Sambuc       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3580*0a6a1f1dSLionel Sambuc         BlockByRefDeclsPtrSet.insert(VD);
3581*0a6a1f1dSLionel Sambuc         BlockByRefDecls.push_back(VD);
3582*0a6a1f1dSLionel Sambuc       }
3583*0a6a1f1dSLionel Sambuc       // imported objects in the inner blocks not used in the outer
3584*0a6a1f1dSLionel Sambuc       // blocks must be copied/disposed in the outer block as well.
3585*0a6a1f1dSLionel Sambuc       if (VD->hasAttr<BlocksAttr>() ||
3586*0a6a1f1dSLionel Sambuc           VD->getType()->isObjCObjectPointerType() ||
3587*0a6a1f1dSLionel Sambuc           VD->getType()->isBlockPointerType())
3588*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(VD);
3589*0a6a1f1dSLionel Sambuc     }
3590*0a6a1f1dSLionel Sambuc 
3591*0a6a1f1dSLionel Sambuc     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3592*0a6a1f1dSLionel Sambuc     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3593*0a6a1f1dSLionel Sambuc 
3594*0a6a1f1dSLionel Sambuc     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3595*0a6a1f1dSLionel Sambuc 
3596*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, CI);
3597*0a6a1f1dSLionel Sambuc 
3598*0a6a1f1dSLionel Sambuc     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3599*0a6a1f1dSLionel Sambuc 
3600*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, CF);
3601*0a6a1f1dSLionel Sambuc 
3602*0a6a1f1dSLionel Sambuc     if (ImportedBlockDecls.size()) {
3603*0a6a1f1dSLionel Sambuc       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3604*0a6a1f1dSLionel Sambuc       InsertText(FunLocStart, HF);
3605*0a6a1f1dSLionel Sambuc     }
3606*0a6a1f1dSLionel Sambuc     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3607*0a6a1f1dSLionel Sambuc                                                ImportedBlockDecls.size() > 0);
3608*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, BD);
3609*0a6a1f1dSLionel Sambuc 
3610*0a6a1f1dSLionel Sambuc     BlockDeclRefs.clear();
3611*0a6a1f1dSLionel Sambuc     BlockByRefDecls.clear();
3612*0a6a1f1dSLionel Sambuc     BlockByRefDeclsPtrSet.clear();
3613*0a6a1f1dSLionel Sambuc     BlockByCopyDecls.clear();
3614*0a6a1f1dSLionel Sambuc     BlockByCopyDeclsPtrSet.clear();
3615*0a6a1f1dSLionel Sambuc     ImportedBlockDecls.clear();
3616*0a6a1f1dSLionel Sambuc   }
3617*0a6a1f1dSLionel Sambuc   if (RewriteSC) {
3618*0a6a1f1dSLionel Sambuc     // Must insert any 'const/volatile/static here. Since it has been
3619*0a6a1f1dSLionel Sambuc     // removed as result of rewriting of block literals.
3620*0a6a1f1dSLionel Sambuc     std::string SC;
3621*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getStorageClass() == SC_Static)
3622*0a6a1f1dSLionel Sambuc       SC = "static ";
3623*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isConstQualified())
3624*0a6a1f1dSLionel Sambuc       SC += "const ";
3625*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isVolatileQualified())
3626*0a6a1f1dSLionel Sambuc       SC += "volatile ";
3627*0a6a1f1dSLionel Sambuc     if (GlobalVarDecl->getType().isRestrictQualified())
3628*0a6a1f1dSLionel Sambuc       SC += "restrict ";
3629*0a6a1f1dSLionel Sambuc     InsertText(FunLocStart, SC);
3630*0a6a1f1dSLionel Sambuc   }
3631*0a6a1f1dSLionel Sambuc 
3632*0a6a1f1dSLionel Sambuc   Blocks.clear();
3633*0a6a1f1dSLionel Sambuc   InnerDeclRefsCount.clear();
3634*0a6a1f1dSLionel Sambuc   InnerDeclRefs.clear();
3635*0a6a1f1dSLionel Sambuc   RewrittenBlockExprs.clear();
3636*0a6a1f1dSLionel Sambuc }
3637*0a6a1f1dSLionel Sambuc 
InsertBlockLiteralsWithinFunction(FunctionDecl * FD)3638*0a6a1f1dSLionel Sambuc void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3639*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3640*0a6a1f1dSLionel Sambuc   StringRef FuncName = FD->getName();
3641*0a6a1f1dSLionel Sambuc 
3642*0a6a1f1dSLionel Sambuc   SynthesizeBlockLiterals(FunLocStart, FuncName);
3643*0a6a1f1dSLionel Sambuc }
3644*0a6a1f1dSLionel Sambuc 
BuildUniqueMethodName(std::string & Name,ObjCMethodDecl * MD)3645*0a6a1f1dSLionel Sambuc static void BuildUniqueMethodName(std::string &Name,
3646*0a6a1f1dSLionel Sambuc                                   ObjCMethodDecl *MD) {
3647*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *IFace = MD->getClassInterface();
3648*0a6a1f1dSLionel Sambuc   Name = IFace->getName();
3649*0a6a1f1dSLionel Sambuc   Name += "__" + MD->getSelector().getAsString();
3650*0a6a1f1dSLionel Sambuc   // Convert colons to underscores.
3651*0a6a1f1dSLionel Sambuc   std::string::size_type loc = 0;
3652*0a6a1f1dSLionel Sambuc   while ((loc = Name.find(":", loc)) != std::string::npos)
3653*0a6a1f1dSLionel Sambuc     Name.replace(loc, 1, "_");
3654*0a6a1f1dSLionel Sambuc }
3655*0a6a1f1dSLionel Sambuc 
InsertBlockLiteralsWithinMethod(ObjCMethodDecl * MD)3656*0a6a1f1dSLionel Sambuc void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3657*0a6a1f1dSLionel Sambuc   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3658*0a6a1f1dSLionel Sambuc   //SourceLocation FunLocStart = MD->getLocStart();
3659*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart = MD->getLocStart();
3660*0a6a1f1dSLionel Sambuc   std::string FuncName;
3661*0a6a1f1dSLionel Sambuc   BuildUniqueMethodName(FuncName, MD);
3662*0a6a1f1dSLionel Sambuc   SynthesizeBlockLiterals(FunLocStart, FuncName);
3663*0a6a1f1dSLionel Sambuc }
3664*0a6a1f1dSLionel Sambuc 
GetBlockDeclRefExprs(Stmt * S)3665*0a6a1f1dSLionel Sambuc void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3666*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
3667*0a6a1f1dSLionel Sambuc     if (*CI) {
3668*0a6a1f1dSLionel Sambuc       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3669*0a6a1f1dSLionel Sambuc         GetBlockDeclRefExprs(CBE->getBody());
3670*0a6a1f1dSLionel Sambuc       else
3671*0a6a1f1dSLionel Sambuc         GetBlockDeclRefExprs(*CI);
3672*0a6a1f1dSLionel Sambuc     }
3673*0a6a1f1dSLionel Sambuc   // Handle specific things.
3674*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3675*0a6a1f1dSLionel Sambuc     if (DRE->refersToEnclosingVariableOrCapture() ||
3676*0a6a1f1dSLionel Sambuc         HasLocalVariableExternalStorage(DRE->getDecl()))
3677*0a6a1f1dSLionel Sambuc       // FIXME: Handle enums.
3678*0a6a1f1dSLionel Sambuc       BlockDeclRefs.push_back(DRE);
3679*0a6a1f1dSLionel Sambuc 
3680*0a6a1f1dSLionel Sambuc   return;
3681*0a6a1f1dSLionel Sambuc }
3682*0a6a1f1dSLionel Sambuc 
GetInnerBlockDeclRefExprs(Stmt * S,SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs,llvm::SmallPtrSetImpl<const DeclContext * > & InnerContexts)3683*0a6a1f1dSLionel Sambuc void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3684*0a6a1f1dSLionel Sambuc                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3685*0a6a1f1dSLionel Sambuc                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3686*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
3687*0a6a1f1dSLionel Sambuc     if (*CI) {
3688*0a6a1f1dSLionel Sambuc       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3689*0a6a1f1dSLionel Sambuc         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3690*0a6a1f1dSLionel Sambuc         GetInnerBlockDeclRefExprs(CBE->getBody(),
3691*0a6a1f1dSLionel Sambuc                                   InnerBlockDeclRefs,
3692*0a6a1f1dSLionel Sambuc                                   InnerContexts);
3693*0a6a1f1dSLionel Sambuc       }
3694*0a6a1f1dSLionel Sambuc       else
3695*0a6a1f1dSLionel Sambuc         GetInnerBlockDeclRefExprs(*CI,
3696*0a6a1f1dSLionel Sambuc                                   InnerBlockDeclRefs,
3697*0a6a1f1dSLionel Sambuc                                   InnerContexts);
3698*0a6a1f1dSLionel Sambuc 
3699*0a6a1f1dSLionel Sambuc     }
3700*0a6a1f1dSLionel Sambuc   // Handle specific things.
3701*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3702*0a6a1f1dSLionel Sambuc     if (DRE->refersToEnclosingVariableOrCapture() ||
3703*0a6a1f1dSLionel Sambuc         HasLocalVariableExternalStorage(DRE->getDecl())) {
3704*0a6a1f1dSLionel Sambuc       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3705*0a6a1f1dSLionel Sambuc         InnerBlockDeclRefs.push_back(DRE);
3706*0a6a1f1dSLionel Sambuc       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3707*0a6a1f1dSLionel Sambuc         if (Var->isFunctionOrMethodVarDecl())
3708*0a6a1f1dSLionel Sambuc           ImportedLocalExternalDecls.insert(Var);
3709*0a6a1f1dSLionel Sambuc     }
3710*0a6a1f1dSLionel Sambuc   }
3711*0a6a1f1dSLionel Sambuc 
3712*0a6a1f1dSLionel Sambuc   return;
3713*0a6a1f1dSLionel Sambuc }
3714*0a6a1f1dSLionel Sambuc 
3715*0a6a1f1dSLionel Sambuc /// convertFunctionTypeOfBlocks - This routine converts a function type
3716*0a6a1f1dSLionel Sambuc /// whose result type may be a block pointer or whose argument type(s)
3717*0a6a1f1dSLionel Sambuc /// might be block pointers to an equivalent function type replacing
3718*0a6a1f1dSLionel Sambuc /// all block pointers to function pointers.
convertFunctionTypeOfBlocks(const FunctionType * FT)3719*0a6a1f1dSLionel Sambuc QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3720*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3721*0a6a1f1dSLionel Sambuc   // FTP will be null for closures that don't take arguments.
3722*0a6a1f1dSLionel Sambuc   // Generate a funky cast.
3723*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
3724*0a6a1f1dSLionel Sambuc   QualType Res = FT->getReturnType();
3725*0a6a1f1dSLionel Sambuc   bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3726*0a6a1f1dSLionel Sambuc 
3727*0a6a1f1dSLionel Sambuc   if (FTP) {
3728*0a6a1f1dSLionel Sambuc     for (auto &I : FTP->param_types()) {
3729*0a6a1f1dSLionel Sambuc       QualType t = I;
3730*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3731*0a6a1f1dSLionel Sambuc       if (convertBlockPointerToFunctionPointer(t))
3732*0a6a1f1dSLionel Sambuc         HasBlockType = true;
3733*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
3734*0a6a1f1dSLionel Sambuc     }
3735*0a6a1f1dSLionel Sambuc   }
3736*0a6a1f1dSLionel Sambuc   QualType FuncType;
3737*0a6a1f1dSLionel Sambuc   // FIXME. Does this work if block takes no argument but has a return type
3738*0a6a1f1dSLionel Sambuc   // which is of block type?
3739*0a6a1f1dSLionel Sambuc   if (HasBlockType)
3740*0a6a1f1dSLionel Sambuc     FuncType = getSimpleFunctionType(Res, ArgTypes);
3741*0a6a1f1dSLionel Sambuc   else FuncType = QualType(FT, 0);
3742*0a6a1f1dSLionel Sambuc   return FuncType;
3743*0a6a1f1dSLionel Sambuc }
3744*0a6a1f1dSLionel Sambuc 
SynthesizeBlockCall(CallExpr * Exp,const Expr * BlockExp)3745*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3746*0a6a1f1dSLionel Sambuc   // Navigate to relevant type information.
3747*0a6a1f1dSLionel Sambuc   const BlockPointerType *CPT = nullptr;
3748*0a6a1f1dSLionel Sambuc 
3749*0a6a1f1dSLionel Sambuc   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3750*0a6a1f1dSLionel Sambuc     CPT = DRE->getType()->getAs<BlockPointerType>();
3751*0a6a1f1dSLionel Sambuc   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3752*0a6a1f1dSLionel Sambuc     CPT = MExpr->getType()->getAs<BlockPointerType>();
3753*0a6a1f1dSLionel Sambuc   }
3754*0a6a1f1dSLionel Sambuc   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3755*0a6a1f1dSLionel Sambuc     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3756*0a6a1f1dSLionel Sambuc   }
3757*0a6a1f1dSLionel Sambuc   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3758*0a6a1f1dSLionel Sambuc     CPT = IEXPR->getType()->getAs<BlockPointerType>();
3759*0a6a1f1dSLionel Sambuc   else if (const ConditionalOperator *CEXPR =
3760*0a6a1f1dSLionel Sambuc             dyn_cast<ConditionalOperator>(BlockExp)) {
3761*0a6a1f1dSLionel Sambuc     Expr *LHSExp = CEXPR->getLHS();
3762*0a6a1f1dSLionel Sambuc     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3763*0a6a1f1dSLionel Sambuc     Expr *RHSExp = CEXPR->getRHS();
3764*0a6a1f1dSLionel Sambuc     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3765*0a6a1f1dSLionel Sambuc     Expr *CONDExp = CEXPR->getCond();
3766*0a6a1f1dSLionel Sambuc     ConditionalOperator *CondExpr =
3767*0a6a1f1dSLionel Sambuc       new (Context) ConditionalOperator(CONDExp,
3768*0a6a1f1dSLionel Sambuc                                       SourceLocation(), cast<Expr>(LHSStmt),
3769*0a6a1f1dSLionel Sambuc                                       SourceLocation(), cast<Expr>(RHSStmt),
3770*0a6a1f1dSLionel Sambuc                                       Exp->getType(), VK_RValue, OK_Ordinary);
3771*0a6a1f1dSLionel Sambuc     return CondExpr;
3772*0a6a1f1dSLionel Sambuc   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3773*0a6a1f1dSLionel Sambuc     CPT = IRE->getType()->getAs<BlockPointerType>();
3774*0a6a1f1dSLionel Sambuc   } else if (const PseudoObjectExpr *POE
3775*0a6a1f1dSLionel Sambuc                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3776*0a6a1f1dSLionel Sambuc     CPT = POE->getType()->castAs<BlockPointerType>();
3777*0a6a1f1dSLionel Sambuc   } else {
3778*0a6a1f1dSLionel Sambuc     assert(1 && "RewriteBlockClass: Bad type");
3779*0a6a1f1dSLionel Sambuc   }
3780*0a6a1f1dSLionel Sambuc   assert(CPT && "RewriteBlockClass: Bad type");
3781*0a6a1f1dSLionel Sambuc   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3782*0a6a1f1dSLionel Sambuc   assert(FT && "RewriteBlockClass: Bad type");
3783*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3784*0a6a1f1dSLionel Sambuc   // FTP will be null for closures that don't take arguments.
3785*0a6a1f1dSLionel Sambuc 
3786*0a6a1f1dSLionel Sambuc   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3787*0a6a1f1dSLionel Sambuc                                       SourceLocation(), SourceLocation(),
3788*0a6a1f1dSLionel Sambuc                                       &Context->Idents.get("__block_impl"));
3789*0a6a1f1dSLionel Sambuc   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3790*0a6a1f1dSLionel Sambuc 
3791*0a6a1f1dSLionel Sambuc   // Generate a funky cast.
3792*0a6a1f1dSLionel Sambuc   SmallVector<QualType, 8> ArgTypes;
3793*0a6a1f1dSLionel Sambuc 
3794*0a6a1f1dSLionel Sambuc   // Push the block argument type.
3795*0a6a1f1dSLionel Sambuc   ArgTypes.push_back(PtrBlock);
3796*0a6a1f1dSLionel Sambuc   if (FTP) {
3797*0a6a1f1dSLionel Sambuc     for (auto &I : FTP->param_types()) {
3798*0a6a1f1dSLionel Sambuc       QualType t = I;
3799*0a6a1f1dSLionel Sambuc       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3800*0a6a1f1dSLionel Sambuc       if (!convertBlockPointerToFunctionPointer(t))
3801*0a6a1f1dSLionel Sambuc         convertToUnqualifiedObjCType(t);
3802*0a6a1f1dSLionel Sambuc       ArgTypes.push_back(t);
3803*0a6a1f1dSLionel Sambuc     }
3804*0a6a1f1dSLionel Sambuc   }
3805*0a6a1f1dSLionel Sambuc   // Now do the pointer to function cast.
3806*0a6a1f1dSLionel Sambuc   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3807*0a6a1f1dSLionel Sambuc 
3808*0a6a1f1dSLionel Sambuc   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3809*0a6a1f1dSLionel Sambuc 
3810*0a6a1f1dSLionel Sambuc   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3811*0a6a1f1dSLionel Sambuc                                                CK_BitCast,
3812*0a6a1f1dSLionel Sambuc                                                const_cast<Expr*>(BlockExp));
3813*0a6a1f1dSLionel Sambuc   // Don't forget the parens to enforce the proper binding.
3814*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3815*0a6a1f1dSLionel Sambuc                                           BlkCast);
3816*0a6a1f1dSLionel Sambuc   //PE->dump();
3817*0a6a1f1dSLionel Sambuc 
3818*0a6a1f1dSLionel Sambuc   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3819*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
3820*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("FuncPtr"),
3821*0a6a1f1dSLionel Sambuc                                     Context->VoidPtrTy, nullptr,
3822*0a6a1f1dSLionel Sambuc                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3823*0a6a1f1dSLionel Sambuc                                     ICIS_NoInit);
3824*0a6a1f1dSLionel Sambuc   MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3825*0a6a1f1dSLionel Sambuc                                             FD->getType(), VK_LValue,
3826*0a6a1f1dSLionel Sambuc                                             OK_Ordinary);
3827*0a6a1f1dSLionel Sambuc 
3828*0a6a1f1dSLionel Sambuc 
3829*0a6a1f1dSLionel Sambuc   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3830*0a6a1f1dSLionel Sambuc                                                 CK_BitCast, ME);
3831*0a6a1f1dSLionel Sambuc   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3832*0a6a1f1dSLionel Sambuc 
3833*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 8> BlkExprs;
3834*0a6a1f1dSLionel Sambuc   // Add the implicit argument.
3835*0a6a1f1dSLionel Sambuc   BlkExprs.push_back(BlkCast);
3836*0a6a1f1dSLionel Sambuc   // Add the user arguments.
3837*0a6a1f1dSLionel Sambuc   for (CallExpr::arg_iterator I = Exp->arg_begin(),
3838*0a6a1f1dSLionel Sambuc        E = Exp->arg_end(); I != E; ++I) {
3839*0a6a1f1dSLionel Sambuc     BlkExprs.push_back(*I);
3840*0a6a1f1dSLionel Sambuc   }
3841*0a6a1f1dSLionel Sambuc   CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
3842*0a6a1f1dSLionel Sambuc                                         Exp->getType(), VK_RValue,
3843*0a6a1f1dSLionel Sambuc                                         SourceLocation());
3844*0a6a1f1dSLionel Sambuc   return CE;
3845*0a6a1f1dSLionel Sambuc }
3846*0a6a1f1dSLionel Sambuc 
3847*0a6a1f1dSLionel Sambuc // We need to return the rewritten expression to handle cases where the
3848*0a6a1f1dSLionel Sambuc // BlockDeclRefExpr is embedded in another expression being rewritten.
3849*0a6a1f1dSLionel Sambuc // For example:
3850*0a6a1f1dSLionel Sambuc //
3851*0a6a1f1dSLionel Sambuc // int main() {
3852*0a6a1f1dSLionel Sambuc //    __block Foo *f;
3853*0a6a1f1dSLionel Sambuc //    __block int i;
3854*0a6a1f1dSLionel Sambuc //
3855*0a6a1f1dSLionel Sambuc //    void (^myblock)() = ^() {
3856*0a6a1f1dSLionel Sambuc //        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3857*0a6a1f1dSLionel Sambuc //        i = 77;
3858*0a6a1f1dSLionel Sambuc //    };
3859*0a6a1f1dSLionel Sambuc //}
RewriteBlockDeclRefExpr(DeclRefExpr * DeclRefExp)3860*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3861*0a6a1f1dSLionel Sambuc   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3862*0a6a1f1dSLionel Sambuc   // for each DeclRefExp where BYREFVAR is name of the variable.
3863*0a6a1f1dSLionel Sambuc   ValueDecl *VD = DeclRefExp->getDecl();
3864*0a6a1f1dSLionel Sambuc   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3865*0a6a1f1dSLionel Sambuc                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3866*0a6a1f1dSLionel Sambuc 
3867*0a6a1f1dSLionel Sambuc   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3868*0a6a1f1dSLionel Sambuc                                     SourceLocation(),
3869*0a6a1f1dSLionel Sambuc                                     &Context->Idents.get("__forwarding"),
3870*0a6a1f1dSLionel Sambuc                                     Context->VoidPtrTy, nullptr,
3871*0a6a1f1dSLionel Sambuc                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3872*0a6a1f1dSLionel Sambuc                                     ICIS_NoInit);
3873*0a6a1f1dSLionel Sambuc   MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3874*0a6a1f1dSLionel Sambuc                                             FD, SourceLocation(),
3875*0a6a1f1dSLionel Sambuc                                             FD->getType(), VK_LValue,
3876*0a6a1f1dSLionel Sambuc                                             OK_Ordinary);
3877*0a6a1f1dSLionel Sambuc 
3878*0a6a1f1dSLionel Sambuc   StringRef Name = VD->getName();
3879*0a6a1f1dSLionel Sambuc   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3880*0a6a1f1dSLionel Sambuc                          &Context->Idents.get(Name),
3881*0a6a1f1dSLionel Sambuc                          Context->VoidPtrTy, nullptr,
3882*0a6a1f1dSLionel Sambuc                          /*BitWidth=*/nullptr, /*Mutable=*/true,
3883*0a6a1f1dSLionel Sambuc                          ICIS_NoInit);
3884*0a6a1f1dSLionel Sambuc   ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3885*0a6a1f1dSLionel Sambuc                                 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3886*0a6a1f1dSLionel Sambuc 
3887*0a6a1f1dSLionel Sambuc 
3888*0a6a1f1dSLionel Sambuc 
3889*0a6a1f1dSLionel Sambuc   // Need parens to enforce precedence.
3890*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3891*0a6a1f1dSLionel Sambuc                                           DeclRefExp->getExprLoc(),
3892*0a6a1f1dSLionel Sambuc                                           ME);
3893*0a6a1f1dSLionel Sambuc   ReplaceStmt(DeclRefExp, PE);
3894*0a6a1f1dSLionel Sambuc   return PE;
3895*0a6a1f1dSLionel Sambuc }
3896*0a6a1f1dSLionel Sambuc 
3897*0a6a1f1dSLionel Sambuc // Rewrites the imported local variable V with external storage
3898*0a6a1f1dSLionel Sambuc // (static, extern, etc.) as *V
3899*0a6a1f1dSLionel Sambuc //
RewriteLocalVariableExternalStorage(DeclRefExpr * DRE)3900*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3901*0a6a1f1dSLionel Sambuc   ValueDecl *VD = DRE->getDecl();
3902*0a6a1f1dSLionel Sambuc   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3903*0a6a1f1dSLionel Sambuc     if (!ImportedLocalExternalDecls.count(Var))
3904*0a6a1f1dSLionel Sambuc       return DRE;
3905*0a6a1f1dSLionel Sambuc   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3906*0a6a1f1dSLionel Sambuc                                           VK_LValue, OK_Ordinary,
3907*0a6a1f1dSLionel Sambuc                                           DRE->getLocation());
3908*0a6a1f1dSLionel Sambuc   // Need parens to enforce precedence.
3909*0a6a1f1dSLionel Sambuc   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3910*0a6a1f1dSLionel Sambuc                                           Exp);
3911*0a6a1f1dSLionel Sambuc   ReplaceStmt(DRE, PE);
3912*0a6a1f1dSLionel Sambuc   return PE;
3913*0a6a1f1dSLionel Sambuc }
3914*0a6a1f1dSLionel Sambuc 
RewriteCastExpr(CStyleCastExpr * CE)3915*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3916*0a6a1f1dSLionel Sambuc   SourceLocation LocStart = CE->getLParenLoc();
3917*0a6a1f1dSLionel Sambuc   SourceLocation LocEnd = CE->getRParenLoc();
3918*0a6a1f1dSLionel Sambuc 
3919*0a6a1f1dSLionel Sambuc   // Need to avoid trying to rewrite synthesized casts.
3920*0a6a1f1dSLionel Sambuc   if (LocStart.isInvalid())
3921*0a6a1f1dSLionel Sambuc     return;
3922*0a6a1f1dSLionel Sambuc   // Need to avoid trying to rewrite casts contained in macros.
3923*0a6a1f1dSLionel Sambuc   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3924*0a6a1f1dSLionel Sambuc     return;
3925*0a6a1f1dSLionel Sambuc 
3926*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(LocStart);
3927*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(LocEnd);
3928*0a6a1f1dSLionel Sambuc   QualType QT = CE->getType();
3929*0a6a1f1dSLionel Sambuc   const Type* TypePtr = QT->getAs<Type>();
3930*0a6a1f1dSLionel Sambuc   if (isa<TypeOfExprType>(TypePtr)) {
3931*0a6a1f1dSLionel Sambuc     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3932*0a6a1f1dSLionel Sambuc     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3933*0a6a1f1dSLionel Sambuc     std::string TypeAsString = "(";
3934*0a6a1f1dSLionel Sambuc     RewriteBlockPointerType(TypeAsString, QT);
3935*0a6a1f1dSLionel Sambuc     TypeAsString += ")";
3936*0a6a1f1dSLionel Sambuc     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3937*0a6a1f1dSLionel Sambuc     return;
3938*0a6a1f1dSLionel Sambuc   }
3939*0a6a1f1dSLionel Sambuc   // advance the location to startArgList.
3940*0a6a1f1dSLionel Sambuc   const char *argPtr = startBuf;
3941*0a6a1f1dSLionel Sambuc 
3942*0a6a1f1dSLionel Sambuc   while (*argPtr++ && (argPtr < endBuf)) {
3943*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
3944*0a6a1f1dSLionel Sambuc     case '^':
3945*0a6a1f1dSLionel Sambuc       // Replace the '^' with '*'.
3946*0a6a1f1dSLionel Sambuc       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3947*0a6a1f1dSLionel Sambuc       ReplaceText(LocStart, 1, "*");
3948*0a6a1f1dSLionel Sambuc       break;
3949*0a6a1f1dSLionel Sambuc     }
3950*0a6a1f1dSLionel Sambuc   }
3951*0a6a1f1dSLionel Sambuc   return;
3952*0a6a1f1dSLionel Sambuc }
3953*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerFunctionArgs(FunctionDecl * FD)3954*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3955*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = FD->getLocation();
3956*0a6a1f1dSLionel Sambuc   unsigned parenCount = 0;
3957*0a6a1f1dSLionel Sambuc 
3958*0a6a1f1dSLionel Sambuc   // We have 1 or more arguments that have closure pointers.
3959*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
3960*0a6a1f1dSLionel Sambuc   const char *startArgList = strchr(startBuf, '(');
3961*0a6a1f1dSLionel Sambuc 
3962*0a6a1f1dSLionel Sambuc   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3963*0a6a1f1dSLionel Sambuc 
3964*0a6a1f1dSLionel Sambuc   parenCount++;
3965*0a6a1f1dSLionel Sambuc   // advance the location to startArgList.
3966*0a6a1f1dSLionel Sambuc   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3967*0a6a1f1dSLionel Sambuc   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3968*0a6a1f1dSLionel Sambuc 
3969*0a6a1f1dSLionel Sambuc   const char *argPtr = startArgList;
3970*0a6a1f1dSLionel Sambuc 
3971*0a6a1f1dSLionel Sambuc   while (*argPtr++ && parenCount) {
3972*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
3973*0a6a1f1dSLionel Sambuc     case '^':
3974*0a6a1f1dSLionel Sambuc       // Replace the '^' with '*'.
3975*0a6a1f1dSLionel Sambuc       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3976*0a6a1f1dSLionel Sambuc       ReplaceText(DeclLoc, 1, "*");
3977*0a6a1f1dSLionel Sambuc       break;
3978*0a6a1f1dSLionel Sambuc     case '(':
3979*0a6a1f1dSLionel Sambuc       parenCount++;
3980*0a6a1f1dSLionel Sambuc       break;
3981*0a6a1f1dSLionel Sambuc     case ')':
3982*0a6a1f1dSLionel Sambuc       parenCount--;
3983*0a6a1f1dSLionel Sambuc       break;
3984*0a6a1f1dSLionel Sambuc     }
3985*0a6a1f1dSLionel Sambuc   }
3986*0a6a1f1dSLionel Sambuc   return;
3987*0a6a1f1dSLionel Sambuc }
3988*0a6a1f1dSLionel Sambuc 
PointerTypeTakesAnyBlockArguments(QualType QT)3989*0a6a1f1dSLionel Sambuc bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3990*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP;
3991*0a6a1f1dSLionel Sambuc   const PointerType *PT = QT->getAs<PointerType>();
3992*0a6a1f1dSLionel Sambuc   if (PT) {
3993*0a6a1f1dSLionel Sambuc     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3994*0a6a1f1dSLionel Sambuc   } else {
3995*0a6a1f1dSLionel Sambuc     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3996*0a6a1f1dSLionel Sambuc     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3997*0a6a1f1dSLionel Sambuc     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3998*0a6a1f1dSLionel Sambuc   }
3999*0a6a1f1dSLionel Sambuc   if (FTP) {
4000*0a6a1f1dSLionel Sambuc     for (const auto &I : FTP->param_types())
4001*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(I))
4002*0a6a1f1dSLionel Sambuc         return true;
4003*0a6a1f1dSLionel Sambuc   }
4004*0a6a1f1dSLionel Sambuc   return false;
4005*0a6a1f1dSLionel Sambuc }
4006*0a6a1f1dSLionel Sambuc 
PointerTypeTakesAnyObjCQualifiedType(QualType QT)4007*0a6a1f1dSLionel Sambuc bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4008*0a6a1f1dSLionel Sambuc   const FunctionProtoType *FTP;
4009*0a6a1f1dSLionel Sambuc   const PointerType *PT = QT->getAs<PointerType>();
4010*0a6a1f1dSLionel Sambuc   if (PT) {
4011*0a6a1f1dSLionel Sambuc     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4012*0a6a1f1dSLionel Sambuc   } else {
4013*0a6a1f1dSLionel Sambuc     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4014*0a6a1f1dSLionel Sambuc     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4015*0a6a1f1dSLionel Sambuc     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4016*0a6a1f1dSLionel Sambuc   }
4017*0a6a1f1dSLionel Sambuc   if (FTP) {
4018*0a6a1f1dSLionel Sambuc     for (const auto &I : FTP->param_types()) {
4019*0a6a1f1dSLionel Sambuc       if (I->isObjCQualifiedIdType())
4020*0a6a1f1dSLionel Sambuc         return true;
4021*0a6a1f1dSLionel Sambuc       if (I->isObjCObjectPointerType() &&
4022*0a6a1f1dSLionel Sambuc           I->getPointeeType()->isObjCQualifiedInterfaceType())
4023*0a6a1f1dSLionel Sambuc         return true;
4024*0a6a1f1dSLionel Sambuc     }
4025*0a6a1f1dSLionel Sambuc 
4026*0a6a1f1dSLionel Sambuc   }
4027*0a6a1f1dSLionel Sambuc   return false;
4028*0a6a1f1dSLionel Sambuc }
4029*0a6a1f1dSLionel Sambuc 
GetExtentOfArgList(const char * Name,const char * & LParen,const char * & RParen)4030*0a6a1f1dSLionel Sambuc void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4031*0a6a1f1dSLionel Sambuc                                      const char *&RParen) {
4032*0a6a1f1dSLionel Sambuc   const char *argPtr = strchr(Name, '(');
4033*0a6a1f1dSLionel Sambuc   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4034*0a6a1f1dSLionel Sambuc 
4035*0a6a1f1dSLionel Sambuc   LParen = argPtr; // output the start.
4036*0a6a1f1dSLionel Sambuc   argPtr++; // skip past the left paren.
4037*0a6a1f1dSLionel Sambuc   unsigned parenCount = 1;
4038*0a6a1f1dSLionel Sambuc 
4039*0a6a1f1dSLionel Sambuc   while (*argPtr && parenCount) {
4040*0a6a1f1dSLionel Sambuc     switch (*argPtr) {
4041*0a6a1f1dSLionel Sambuc     case '(': parenCount++; break;
4042*0a6a1f1dSLionel Sambuc     case ')': parenCount--; break;
4043*0a6a1f1dSLionel Sambuc     default: break;
4044*0a6a1f1dSLionel Sambuc     }
4045*0a6a1f1dSLionel Sambuc     if (parenCount) argPtr++;
4046*0a6a1f1dSLionel Sambuc   }
4047*0a6a1f1dSLionel Sambuc   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4048*0a6a1f1dSLionel Sambuc   RParen = argPtr; // output the end
4049*0a6a1f1dSLionel Sambuc }
4050*0a6a1f1dSLionel Sambuc 
RewriteBlockPointerDecl(NamedDecl * ND)4051*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4052*0a6a1f1dSLionel Sambuc   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4053*0a6a1f1dSLionel Sambuc     RewriteBlockPointerFunctionArgs(FD);
4054*0a6a1f1dSLionel Sambuc     return;
4055*0a6a1f1dSLionel Sambuc   }
4056*0a6a1f1dSLionel Sambuc   // Handle Variables and Typedefs.
4057*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getLocation();
4058*0a6a1f1dSLionel Sambuc   QualType DeclT;
4059*0a6a1f1dSLionel Sambuc   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4060*0a6a1f1dSLionel Sambuc     DeclT = VD->getType();
4061*0a6a1f1dSLionel Sambuc   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4062*0a6a1f1dSLionel Sambuc     DeclT = TDD->getUnderlyingType();
4063*0a6a1f1dSLionel Sambuc   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4064*0a6a1f1dSLionel Sambuc     DeclT = FD->getType();
4065*0a6a1f1dSLionel Sambuc   else
4066*0a6a1f1dSLionel Sambuc     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4067*0a6a1f1dSLionel Sambuc 
4068*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
4069*0a6a1f1dSLionel Sambuc   const char *endBuf = startBuf;
4070*0a6a1f1dSLionel Sambuc   // scan backward (from the decl location) for the end of the previous decl.
4071*0a6a1f1dSLionel Sambuc   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4072*0a6a1f1dSLionel Sambuc     startBuf--;
4073*0a6a1f1dSLionel Sambuc   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4074*0a6a1f1dSLionel Sambuc   std::string buf;
4075*0a6a1f1dSLionel Sambuc   unsigned OrigLength=0;
4076*0a6a1f1dSLionel Sambuc   // *startBuf != '^' if we are dealing with a pointer to function that
4077*0a6a1f1dSLionel Sambuc   // may take block argument types (which will be handled below).
4078*0a6a1f1dSLionel Sambuc   if (*startBuf == '^') {
4079*0a6a1f1dSLionel Sambuc     // Replace the '^' with '*', computing a negative offset.
4080*0a6a1f1dSLionel Sambuc     buf = '*';
4081*0a6a1f1dSLionel Sambuc     startBuf++;
4082*0a6a1f1dSLionel Sambuc     OrigLength++;
4083*0a6a1f1dSLionel Sambuc   }
4084*0a6a1f1dSLionel Sambuc   while (*startBuf != ')') {
4085*0a6a1f1dSLionel Sambuc     buf += *startBuf;
4086*0a6a1f1dSLionel Sambuc     startBuf++;
4087*0a6a1f1dSLionel Sambuc     OrigLength++;
4088*0a6a1f1dSLionel Sambuc   }
4089*0a6a1f1dSLionel Sambuc   buf += ')';
4090*0a6a1f1dSLionel Sambuc   OrigLength++;
4091*0a6a1f1dSLionel Sambuc 
4092*0a6a1f1dSLionel Sambuc   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4093*0a6a1f1dSLionel Sambuc       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4094*0a6a1f1dSLionel Sambuc     // Replace the '^' with '*' for arguments.
4095*0a6a1f1dSLionel Sambuc     // Replace id<P> with id/*<>*/
4096*0a6a1f1dSLionel Sambuc     DeclLoc = ND->getLocation();
4097*0a6a1f1dSLionel Sambuc     startBuf = SM->getCharacterData(DeclLoc);
4098*0a6a1f1dSLionel Sambuc     const char *argListBegin, *argListEnd;
4099*0a6a1f1dSLionel Sambuc     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4100*0a6a1f1dSLionel Sambuc     while (argListBegin < argListEnd) {
4101*0a6a1f1dSLionel Sambuc       if (*argListBegin == '^')
4102*0a6a1f1dSLionel Sambuc         buf += '*';
4103*0a6a1f1dSLionel Sambuc       else if (*argListBegin ==  '<') {
4104*0a6a1f1dSLionel Sambuc         buf += "/*";
4105*0a6a1f1dSLionel Sambuc         buf += *argListBegin++;
4106*0a6a1f1dSLionel Sambuc         OrigLength++;
4107*0a6a1f1dSLionel Sambuc         while (*argListBegin != '>') {
4108*0a6a1f1dSLionel Sambuc           buf += *argListBegin++;
4109*0a6a1f1dSLionel Sambuc           OrigLength++;
4110*0a6a1f1dSLionel Sambuc         }
4111*0a6a1f1dSLionel Sambuc         buf += *argListBegin;
4112*0a6a1f1dSLionel Sambuc         buf += "*/";
4113*0a6a1f1dSLionel Sambuc       }
4114*0a6a1f1dSLionel Sambuc       else
4115*0a6a1f1dSLionel Sambuc         buf += *argListBegin;
4116*0a6a1f1dSLionel Sambuc       argListBegin++;
4117*0a6a1f1dSLionel Sambuc       OrigLength++;
4118*0a6a1f1dSLionel Sambuc     }
4119*0a6a1f1dSLionel Sambuc     buf += ')';
4120*0a6a1f1dSLionel Sambuc     OrigLength++;
4121*0a6a1f1dSLionel Sambuc   }
4122*0a6a1f1dSLionel Sambuc   ReplaceText(Start, OrigLength, buf);
4123*0a6a1f1dSLionel Sambuc 
4124*0a6a1f1dSLionel Sambuc   return;
4125*0a6a1f1dSLionel Sambuc }
4126*0a6a1f1dSLionel Sambuc 
4127*0a6a1f1dSLionel Sambuc 
4128*0a6a1f1dSLionel Sambuc /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4129*0a6a1f1dSLionel Sambuc /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4130*0a6a1f1dSLionel Sambuc ///                    struct Block_byref_id_object *src) {
4131*0a6a1f1dSLionel Sambuc ///  _Block_object_assign (&_dest->object, _src->object,
4132*0a6a1f1dSLionel Sambuc ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4133*0a6a1f1dSLionel Sambuc ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4134*0a6a1f1dSLionel Sambuc ///  _Block_object_assign(&_dest->object, _src->object,
4135*0a6a1f1dSLionel Sambuc ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4136*0a6a1f1dSLionel Sambuc ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4137*0a6a1f1dSLionel Sambuc /// }
4138*0a6a1f1dSLionel Sambuc /// And:
4139*0a6a1f1dSLionel Sambuc /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4140*0a6a1f1dSLionel Sambuc ///  _Block_object_dispose(_src->object,
4141*0a6a1f1dSLionel Sambuc ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4142*0a6a1f1dSLionel Sambuc ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4143*0a6a1f1dSLionel Sambuc ///  _Block_object_dispose(_src->object,
4144*0a6a1f1dSLionel Sambuc ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4145*0a6a1f1dSLionel Sambuc ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4146*0a6a1f1dSLionel Sambuc /// }
4147*0a6a1f1dSLionel Sambuc 
SynthesizeByrefCopyDestroyHelper(VarDecl * VD,int flag)4148*0a6a1f1dSLionel Sambuc std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4149*0a6a1f1dSLionel Sambuc                                                           int flag) {
4150*0a6a1f1dSLionel Sambuc   std::string S;
4151*0a6a1f1dSLionel Sambuc   if (CopyDestroyCache.count(flag))
4152*0a6a1f1dSLionel Sambuc     return S;
4153*0a6a1f1dSLionel Sambuc   CopyDestroyCache.insert(flag);
4154*0a6a1f1dSLionel Sambuc   S = "static void __Block_byref_id_object_copy_";
4155*0a6a1f1dSLionel Sambuc   S += utostr(flag);
4156*0a6a1f1dSLionel Sambuc   S += "(void *dst, void *src) {\n";
4157*0a6a1f1dSLionel Sambuc 
4158*0a6a1f1dSLionel Sambuc   // offset into the object pointer is computed as:
4159*0a6a1f1dSLionel Sambuc   // void * + void* + int + int + void* + void *
4160*0a6a1f1dSLionel Sambuc   unsigned IntSize =
4161*0a6a1f1dSLionel Sambuc   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4162*0a6a1f1dSLionel Sambuc   unsigned VoidPtrSize =
4163*0a6a1f1dSLionel Sambuc   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4164*0a6a1f1dSLionel Sambuc 
4165*0a6a1f1dSLionel Sambuc   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4166*0a6a1f1dSLionel Sambuc   S += " _Block_object_assign((char*)dst + ";
4167*0a6a1f1dSLionel Sambuc   S += utostr(offset);
4168*0a6a1f1dSLionel Sambuc   S += ", *(void * *) ((char*)src + ";
4169*0a6a1f1dSLionel Sambuc   S += utostr(offset);
4170*0a6a1f1dSLionel Sambuc   S += "), ";
4171*0a6a1f1dSLionel Sambuc   S += utostr(flag);
4172*0a6a1f1dSLionel Sambuc   S += ");\n}\n";
4173*0a6a1f1dSLionel Sambuc 
4174*0a6a1f1dSLionel Sambuc   S += "static void __Block_byref_id_object_dispose_";
4175*0a6a1f1dSLionel Sambuc   S += utostr(flag);
4176*0a6a1f1dSLionel Sambuc   S += "(void *src) {\n";
4177*0a6a1f1dSLionel Sambuc   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4178*0a6a1f1dSLionel Sambuc   S += utostr(offset);
4179*0a6a1f1dSLionel Sambuc   S += "), ";
4180*0a6a1f1dSLionel Sambuc   S += utostr(flag);
4181*0a6a1f1dSLionel Sambuc   S += ");\n}\n";
4182*0a6a1f1dSLionel Sambuc   return S;
4183*0a6a1f1dSLionel Sambuc }
4184*0a6a1f1dSLionel Sambuc 
4185*0a6a1f1dSLionel Sambuc /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4186*0a6a1f1dSLionel Sambuc /// the declaration into:
4187*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND {
4188*0a6a1f1dSLionel Sambuc /// void *__isa;                  // NULL for everything except __weak pointers
4189*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND *__forwarding;
4190*0a6a1f1dSLionel Sambuc /// int32_t __flags;
4191*0a6a1f1dSLionel Sambuc /// int32_t __size;
4192*0a6a1f1dSLionel Sambuc /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4193*0a6a1f1dSLionel Sambuc /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4194*0a6a1f1dSLionel Sambuc /// typex ND;
4195*0a6a1f1dSLionel Sambuc /// };
4196*0a6a1f1dSLionel Sambuc ///
4197*0a6a1f1dSLionel Sambuc /// It then replaces declaration of ND variable with:
4198*0a6a1f1dSLionel Sambuc /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4199*0a6a1f1dSLionel Sambuc ///                               __size=sizeof(struct __Block_byref_ND),
4200*0a6a1f1dSLionel Sambuc ///                               ND=initializer-if-any};
4201*0a6a1f1dSLionel Sambuc ///
4202*0a6a1f1dSLionel Sambuc ///
RewriteByRefVar(VarDecl * ND)4203*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4204*0a6a1f1dSLionel Sambuc   // Insert declaration for the function in which block literal is
4205*0a6a1f1dSLionel Sambuc   // used.
4206*0a6a1f1dSLionel Sambuc   if (CurFunctionDeclToDeclareForBlock)
4207*0a6a1f1dSLionel Sambuc     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4208*0a6a1f1dSLionel Sambuc   int flag = 0;
4209*0a6a1f1dSLionel Sambuc   int isa = 0;
4210*0a6a1f1dSLionel Sambuc   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4211*0a6a1f1dSLionel Sambuc   if (DeclLoc.isInvalid())
4212*0a6a1f1dSLionel Sambuc     // If type location is missing, it is because of missing type (a warning).
4213*0a6a1f1dSLionel Sambuc     // Use variable's location which is good for this case.
4214*0a6a1f1dSLionel Sambuc     DeclLoc = ND->getLocation();
4215*0a6a1f1dSLionel Sambuc   const char *startBuf = SM->getCharacterData(DeclLoc);
4216*0a6a1f1dSLionel Sambuc   SourceLocation X = ND->getLocEnd();
4217*0a6a1f1dSLionel Sambuc   X = SM->getExpansionLoc(X);
4218*0a6a1f1dSLionel Sambuc   const char *endBuf = SM->getCharacterData(X);
4219*0a6a1f1dSLionel Sambuc   std::string Name(ND->getNameAsString());
4220*0a6a1f1dSLionel Sambuc   std::string ByrefType;
4221*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND, true);
4222*0a6a1f1dSLionel Sambuc   ByrefType += " {\n";
4223*0a6a1f1dSLionel Sambuc   ByrefType += "  void *__isa;\n";
4224*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND);
4225*0a6a1f1dSLionel Sambuc   ByrefType += " *__forwarding;\n";
4226*0a6a1f1dSLionel Sambuc   ByrefType += " int __flags;\n";
4227*0a6a1f1dSLionel Sambuc   ByrefType += " int __size;\n";
4228*0a6a1f1dSLionel Sambuc   // Add void *__Block_byref_id_object_copy;
4229*0a6a1f1dSLionel Sambuc   // void *__Block_byref_id_object_dispose; if needed.
4230*0a6a1f1dSLionel Sambuc   QualType Ty = ND->getType();
4231*0a6a1f1dSLionel Sambuc   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4232*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose) {
4233*0a6a1f1dSLionel Sambuc     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4234*0a6a1f1dSLionel Sambuc     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4235*0a6a1f1dSLionel Sambuc   }
4236*0a6a1f1dSLionel Sambuc 
4237*0a6a1f1dSLionel Sambuc   QualType T = Ty;
4238*0a6a1f1dSLionel Sambuc   (void)convertBlockPointerToFunctionPointer(T);
4239*0a6a1f1dSLionel Sambuc   T.getAsStringInternal(Name, Context->getPrintingPolicy());
4240*0a6a1f1dSLionel Sambuc 
4241*0a6a1f1dSLionel Sambuc   ByrefType += " " + Name + ";\n";
4242*0a6a1f1dSLionel Sambuc   ByrefType += "};\n";
4243*0a6a1f1dSLionel Sambuc   // Insert this type in global scope. It is needed by helper function.
4244*0a6a1f1dSLionel Sambuc   SourceLocation FunLocStart;
4245*0a6a1f1dSLionel Sambuc   if (CurFunctionDef)
4246*0a6a1f1dSLionel Sambuc      FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4247*0a6a1f1dSLionel Sambuc   else {
4248*0a6a1f1dSLionel Sambuc     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4249*0a6a1f1dSLionel Sambuc     FunLocStart = CurMethodDef->getLocStart();
4250*0a6a1f1dSLionel Sambuc   }
4251*0a6a1f1dSLionel Sambuc   InsertText(FunLocStart, ByrefType);
4252*0a6a1f1dSLionel Sambuc   if (Ty.isObjCGCWeak()) {
4253*0a6a1f1dSLionel Sambuc     flag |= BLOCK_FIELD_IS_WEAK;
4254*0a6a1f1dSLionel Sambuc     isa = 1;
4255*0a6a1f1dSLionel Sambuc   }
4256*0a6a1f1dSLionel Sambuc 
4257*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose) {
4258*0a6a1f1dSLionel Sambuc     flag = BLOCK_BYREF_CALLER;
4259*0a6a1f1dSLionel Sambuc     QualType Ty = ND->getType();
4260*0a6a1f1dSLionel Sambuc     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4261*0a6a1f1dSLionel Sambuc     if (Ty->isBlockPointerType())
4262*0a6a1f1dSLionel Sambuc       flag |= BLOCK_FIELD_IS_BLOCK;
4263*0a6a1f1dSLionel Sambuc     else
4264*0a6a1f1dSLionel Sambuc       flag |= BLOCK_FIELD_IS_OBJECT;
4265*0a6a1f1dSLionel Sambuc     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4266*0a6a1f1dSLionel Sambuc     if (!HF.empty())
4267*0a6a1f1dSLionel Sambuc       InsertText(FunLocStart, HF);
4268*0a6a1f1dSLionel Sambuc   }
4269*0a6a1f1dSLionel Sambuc 
4270*0a6a1f1dSLionel Sambuc   // struct __Block_byref_ND ND =
4271*0a6a1f1dSLionel Sambuc   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4272*0a6a1f1dSLionel Sambuc   //  initializer-if-any};
4273*0a6a1f1dSLionel Sambuc   bool hasInit = (ND->getInit() != nullptr);
4274*0a6a1f1dSLionel Sambuc   unsigned flags = 0;
4275*0a6a1f1dSLionel Sambuc   if (HasCopyAndDispose)
4276*0a6a1f1dSLionel Sambuc     flags |= BLOCK_HAS_COPY_DISPOSE;
4277*0a6a1f1dSLionel Sambuc   Name = ND->getNameAsString();
4278*0a6a1f1dSLionel Sambuc   ByrefType.clear();
4279*0a6a1f1dSLionel Sambuc   RewriteByRefString(ByrefType, Name, ND);
4280*0a6a1f1dSLionel Sambuc   std::string ForwardingCastType("(");
4281*0a6a1f1dSLionel Sambuc   ForwardingCastType += ByrefType + " *)";
4282*0a6a1f1dSLionel Sambuc   if (!hasInit) {
4283*0a6a1f1dSLionel Sambuc     ByrefType += " " + Name + " = {(void*)";
4284*0a6a1f1dSLionel Sambuc     ByrefType += utostr(isa);
4285*0a6a1f1dSLionel Sambuc     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4286*0a6a1f1dSLionel Sambuc     ByrefType += utostr(flags);
4287*0a6a1f1dSLionel Sambuc     ByrefType += ", ";
4288*0a6a1f1dSLionel Sambuc     ByrefType += "sizeof(";
4289*0a6a1f1dSLionel Sambuc     RewriteByRefString(ByrefType, Name, ND);
4290*0a6a1f1dSLionel Sambuc     ByrefType += ")";
4291*0a6a1f1dSLionel Sambuc     if (HasCopyAndDispose) {
4292*0a6a1f1dSLionel Sambuc       ByrefType += ", __Block_byref_id_object_copy_";
4293*0a6a1f1dSLionel Sambuc       ByrefType += utostr(flag);
4294*0a6a1f1dSLionel Sambuc       ByrefType += ", __Block_byref_id_object_dispose_";
4295*0a6a1f1dSLionel Sambuc       ByrefType += utostr(flag);
4296*0a6a1f1dSLionel Sambuc     }
4297*0a6a1f1dSLionel Sambuc     ByrefType += "};\n";
4298*0a6a1f1dSLionel Sambuc     unsigned nameSize = Name.size();
4299*0a6a1f1dSLionel Sambuc     // for block or function pointer declaration. Name is aleady
4300*0a6a1f1dSLionel Sambuc     // part of the declaration.
4301*0a6a1f1dSLionel Sambuc     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4302*0a6a1f1dSLionel Sambuc       nameSize = 1;
4303*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4304*0a6a1f1dSLionel Sambuc   }
4305*0a6a1f1dSLionel Sambuc   else {
4306*0a6a1f1dSLionel Sambuc     SourceLocation startLoc;
4307*0a6a1f1dSLionel Sambuc     Expr *E = ND->getInit();
4308*0a6a1f1dSLionel Sambuc     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4309*0a6a1f1dSLionel Sambuc       startLoc = ECE->getLParenLoc();
4310*0a6a1f1dSLionel Sambuc     else
4311*0a6a1f1dSLionel Sambuc       startLoc = E->getLocStart();
4312*0a6a1f1dSLionel Sambuc     startLoc = SM->getExpansionLoc(startLoc);
4313*0a6a1f1dSLionel Sambuc     endBuf = SM->getCharacterData(startLoc);
4314*0a6a1f1dSLionel Sambuc     ByrefType += " " + Name;
4315*0a6a1f1dSLionel Sambuc     ByrefType += " = {(void*)";
4316*0a6a1f1dSLionel Sambuc     ByrefType += utostr(isa);
4317*0a6a1f1dSLionel Sambuc     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4318*0a6a1f1dSLionel Sambuc     ByrefType += utostr(flags);
4319*0a6a1f1dSLionel Sambuc     ByrefType += ", ";
4320*0a6a1f1dSLionel Sambuc     ByrefType += "sizeof(";
4321*0a6a1f1dSLionel Sambuc     RewriteByRefString(ByrefType, Name, ND);
4322*0a6a1f1dSLionel Sambuc     ByrefType += "), ";
4323*0a6a1f1dSLionel Sambuc     if (HasCopyAndDispose) {
4324*0a6a1f1dSLionel Sambuc       ByrefType += "__Block_byref_id_object_copy_";
4325*0a6a1f1dSLionel Sambuc       ByrefType += utostr(flag);
4326*0a6a1f1dSLionel Sambuc       ByrefType += ", __Block_byref_id_object_dispose_";
4327*0a6a1f1dSLionel Sambuc       ByrefType += utostr(flag);
4328*0a6a1f1dSLionel Sambuc       ByrefType += ", ";
4329*0a6a1f1dSLionel Sambuc     }
4330*0a6a1f1dSLionel Sambuc     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4331*0a6a1f1dSLionel Sambuc 
4332*0a6a1f1dSLionel Sambuc     // Complete the newly synthesized compound expression by inserting a right
4333*0a6a1f1dSLionel Sambuc     // curly brace before the end of the declaration.
4334*0a6a1f1dSLionel Sambuc     // FIXME: This approach avoids rewriting the initializer expression. It
4335*0a6a1f1dSLionel Sambuc     // also assumes there is only one declarator. For example, the following
4336*0a6a1f1dSLionel Sambuc     // isn't currently supported by this routine (in general):
4337*0a6a1f1dSLionel Sambuc     //
4338*0a6a1f1dSLionel Sambuc     // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4339*0a6a1f1dSLionel Sambuc     //
4340*0a6a1f1dSLionel Sambuc     const char *startInitializerBuf = SM->getCharacterData(startLoc);
4341*0a6a1f1dSLionel Sambuc     const char *semiBuf = strchr(startInitializerBuf, ';');
4342*0a6a1f1dSLionel Sambuc     assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4343*0a6a1f1dSLionel Sambuc     SourceLocation semiLoc =
4344*0a6a1f1dSLionel Sambuc       startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4345*0a6a1f1dSLionel Sambuc 
4346*0a6a1f1dSLionel Sambuc     InsertText(semiLoc, "}");
4347*0a6a1f1dSLionel Sambuc   }
4348*0a6a1f1dSLionel Sambuc   return;
4349*0a6a1f1dSLionel Sambuc }
4350*0a6a1f1dSLionel Sambuc 
CollectBlockDeclRefInfo(BlockExpr * Exp)4351*0a6a1f1dSLionel Sambuc void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4352*0a6a1f1dSLionel Sambuc   // Add initializers for any closure decl refs.
4353*0a6a1f1dSLionel Sambuc   GetBlockDeclRefExprs(Exp->getBody());
4354*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
4355*0a6a1f1dSLionel Sambuc     // Unique all "by copy" declarations.
4356*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4357*0a6a1f1dSLionel Sambuc       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4358*0a6a1f1dSLionel Sambuc         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4359*0a6a1f1dSLionel Sambuc           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4360*0a6a1f1dSLionel Sambuc           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4361*0a6a1f1dSLionel Sambuc         }
4362*0a6a1f1dSLionel Sambuc       }
4363*0a6a1f1dSLionel Sambuc     // Unique all "by ref" declarations.
4364*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4365*0a6a1f1dSLionel Sambuc       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4366*0a6a1f1dSLionel Sambuc         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4367*0a6a1f1dSLionel Sambuc           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4368*0a6a1f1dSLionel Sambuc           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4369*0a6a1f1dSLionel Sambuc         }
4370*0a6a1f1dSLionel Sambuc       }
4371*0a6a1f1dSLionel Sambuc     // Find any imported blocks...they will need special attention.
4372*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4373*0a6a1f1dSLionel Sambuc       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4374*0a6a1f1dSLionel Sambuc           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4375*0a6a1f1dSLionel Sambuc           BlockDeclRefs[i]->getType()->isBlockPointerType())
4376*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4377*0a6a1f1dSLionel Sambuc   }
4378*0a6a1f1dSLionel Sambuc }
4379*0a6a1f1dSLionel Sambuc 
SynthBlockInitFunctionDecl(StringRef name)4380*0a6a1f1dSLionel Sambuc FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4381*0a6a1f1dSLionel Sambuc   IdentifierInfo *ID = &Context->Idents.get(name);
4382*0a6a1f1dSLionel Sambuc   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4383*0a6a1f1dSLionel Sambuc   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4384*0a6a1f1dSLionel Sambuc                               SourceLocation(), ID, FType, nullptr, SC_Extern,
4385*0a6a1f1dSLionel Sambuc                               false, false);
4386*0a6a1f1dSLionel Sambuc }
4387*0a6a1f1dSLionel Sambuc 
SynthBlockInitExpr(BlockExpr * Exp,const SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs)4388*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4389*0a6a1f1dSLionel Sambuc                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4390*0a6a1f1dSLionel Sambuc   const BlockDecl *block = Exp->getBlockDecl();
4391*0a6a1f1dSLionel Sambuc   Blocks.push_back(Exp);
4392*0a6a1f1dSLionel Sambuc 
4393*0a6a1f1dSLionel Sambuc   CollectBlockDeclRefInfo(Exp);
4394*0a6a1f1dSLionel Sambuc 
4395*0a6a1f1dSLionel Sambuc   // Add inner imported variables now used in current block.
4396*0a6a1f1dSLionel Sambuc  int countOfInnerDecls = 0;
4397*0a6a1f1dSLionel Sambuc   if (!InnerBlockDeclRefs.empty()) {
4398*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4399*0a6a1f1dSLionel Sambuc       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4400*0a6a1f1dSLionel Sambuc       ValueDecl *VD = Exp->getDecl();
4401*0a6a1f1dSLionel Sambuc       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4402*0a6a1f1dSLionel Sambuc       // We need to save the copied-in variables in nested
4403*0a6a1f1dSLionel Sambuc       // blocks because it is needed at the end for some of the API generations.
4404*0a6a1f1dSLionel Sambuc       // See SynthesizeBlockLiterals routine.
4405*0a6a1f1dSLionel Sambuc         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4406*0a6a1f1dSLionel Sambuc         BlockDeclRefs.push_back(Exp);
4407*0a6a1f1dSLionel Sambuc         BlockByCopyDeclsPtrSet.insert(VD);
4408*0a6a1f1dSLionel Sambuc         BlockByCopyDecls.push_back(VD);
4409*0a6a1f1dSLionel Sambuc       }
4410*0a6a1f1dSLionel Sambuc       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4411*0a6a1f1dSLionel Sambuc         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4412*0a6a1f1dSLionel Sambuc         BlockDeclRefs.push_back(Exp);
4413*0a6a1f1dSLionel Sambuc         BlockByRefDeclsPtrSet.insert(VD);
4414*0a6a1f1dSLionel Sambuc         BlockByRefDecls.push_back(VD);
4415*0a6a1f1dSLionel Sambuc       }
4416*0a6a1f1dSLionel Sambuc     }
4417*0a6a1f1dSLionel Sambuc     // Find any imported blocks...they will need special attention.
4418*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4419*0a6a1f1dSLionel Sambuc       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4420*0a6a1f1dSLionel Sambuc           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4421*0a6a1f1dSLionel Sambuc           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4422*0a6a1f1dSLionel Sambuc         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4423*0a6a1f1dSLionel Sambuc   }
4424*0a6a1f1dSLionel Sambuc   InnerDeclRefsCount.push_back(countOfInnerDecls);
4425*0a6a1f1dSLionel Sambuc 
4426*0a6a1f1dSLionel Sambuc   std::string FuncName;
4427*0a6a1f1dSLionel Sambuc 
4428*0a6a1f1dSLionel Sambuc   if (CurFunctionDef)
4429*0a6a1f1dSLionel Sambuc     FuncName = CurFunctionDef->getNameAsString();
4430*0a6a1f1dSLionel Sambuc   else if (CurMethodDef)
4431*0a6a1f1dSLionel Sambuc     BuildUniqueMethodName(FuncName, CurMethodDef);
4432*0a6a1f1dSLionel Sambuc   else if (GlobalVarDecl)
4433*0a6a1f1dSLionel Sambuc     FuncName = std::string(GlobalVarDecl->getNameAsString());
4434*0a6a1f1dSLionel Sambuc 
4435*0a6a1f1dSLionel Sambuc   std::string BlockNumber = utostr(Blocks.size()-1);
4436*0a6a1f1dSLionel Sambuc 
4437*0a6a1f1dSLionel Sambuc   std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4438*0a6a1f1dSLionel Sambuc   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4439*0a6a1f1dSLionel Sambuc 
4440*0a6a1f1dSLionel Sambuc   // Get a pointer to the function type so we can cast appropriately.
4441*0a6a1f1dSLionel Sambuc   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4442*0a6a1f1dSLionel Sambuc   QualType FType = Context->getPointerType(BFT);
4443*0a6a1f1dSLionel Sambuc 
4444*0a6a1f1dSLionel Sambuc   FunctionDecl *FD;
4445*0a6a1f1dSLionel Sambuc   Expr *NewRep;
4446*0a6a1f1dSLionel Sambuc 
4447*0a6a1f1dSLionel Sambuc   // Simulate a constructor call...
4448*0a6a1f1dSLionel Sambuc   FD = SynthBlockInitFunctionDecl(Tag);
4449*0a6a1f1dSLionel Sambuc   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
4450*0a6a1f1dSLionel Sambuc                                                SourceLocation());
4451*0a6a1f1dSLionel Sambuc 
4452*0a6a1f1dSLionel Sambuc   SmallVector<Expr*, 4> InitExprs;
4453*0a6a1f1dSLionel Sambuc 
4454*0a6a1f1dSLionel Sambuc   // Initialize the block function.
4455*0a6a1f1dSLionel Sambuc   FD = SynthBlockInitFunctionDecl(Func);
4456*0a6a1f1dSLionel Sambuc   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4457*0a6a1f1dSLionel Sambuc                                                VK_LValue, SourceLocation());
4458*0a6a1f1dSLionel Sambuc   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4459*0a6a1f1dSLionel Sambuc                                                 CK_BitCast, Arg);
4460*0a6a1f1dSLionel Sambuc   InitExprs.push_back(castExpr);
4461*0a6a1f1dSLionel Sambuc 
4462*0a6a1f1dSLionel Sambuc   // Initialize the block descriptor.
4463*0a6a1f1dSLionel Sambuc   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4464*0a6a1f1dSLionel Sambuc 
4465*0a6a1f1dSLionel Sambuc   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4466*0a6a1f1dSLionel Sambuc                                    SourceLocation(), SourceLocation(),
4467*0a6a1f1dSLionel Sambuc                                    &Context->Idents.get(DescData.c_str()),
4468*0a6a1f1dSLionel Sambuc                                    Context->VoidPtrTy, nullptr,
4469*0a6a1f1dSLionel Sambuc                                    SC_Static);
4470*0a6a1f1dSLionel Sambuc   UnaryOperator *DescRefExpr =
4471*0a6a1f1dSLionel Sambuc     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
4472*0a6a1f1dSLionel Sambuc                                                           Context->VoidPtrTy,
4473*0a6a1f1dSLionel Sambuc                                                           VK_LValue,
4474*0a6a1f1dSLionel Sambuc                                                           SourceLocation()),
4475*0a6a1f1dSLionel Sambuc                                 UO_AddrOf,
4476*0a6a1f1dSLionel Sambuc                                 Context->getPointerType(Context->VoidPtrTy),
4477*0a6a1f1dSLionel Sambuc                                 VK_RValue, OK_Ordinary,
4478*0a6a1f1dSLionel Sambuc                                 SourceLocation());
4479*0a6a1f1dSLionel Sambuc   InitExprs.push_back(DescRefExpr);
4480*0a6a1f1dSLionel Sambuc 
4481*0a6a1f1dSLionel Sambuc   // Add initializers for any closure decl refs.
4482*0a6a1f1dSLionel Sambuc   if (BlockDeclRefs.size()) {
4483*0a6a1f1dSLionel Sambuc     Expr *Exp;
4484*0a6a1f1dSLionel Sambuc     // Output all "by copy" declarations.
4485*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4486*0a6a1f1dSLionel Sambuc          E = BlockByCopyDecls.end(); I != E; ++I) {
4487*0a6a1f1dSLionel Sambuc       if (isObjCType((*I)->getType())) {
4488*0a6a1f1dSLionel Sambuc         // FIXME: Conform to ABI ([[obj retain] autorelease]).
4489*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
4490*0a6a1f1dSLionel Sambuc         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4491*0a6a1f1dSLionel Sambuc                                         SourceLocation());
4492*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I)) {
4493*0a6a1f1dSLionel Sambuc           QualType QT = (*I)->getType();
4494*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
4495*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4496*0a6a1f1dSLionel Sambuc                                             OK_Ordinary, SourceLocation());
4497*0a6a1f1dSLionel Sambuc         }
4498*0a6a1f1dSLionel Sambuc       } else if (isTopLevelBlockPointerType((*I)->getType())) {
4499*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
4500*0a6a1f1dSLionel Sambuc         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4501*0a6a1f1dSLionel Sambuc                                         SourceLocation());
4502*0a6a1f1dSLionel Sambuc         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4503*0a6a1f1dSLionel Sambuc                                        CK_BitCast, Arg);
4504*0a6a1f1dSLionel Sambuc       } else {
4505*0a6a1f1dSLionel Sambuc         FD = SynthBlockInitFunctionDecl((*I)->getName());
4506*0a6a1f1dSLionel Sambuc         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4507*0a6a1f1dSLionel Sambuc                                         SourceLocation());
4508*0a6a1f1dSLionel Sambuc         if (HasLocalVariableExternalStorage(*I)) {
4509*0a6a1f1dSLionel Sambuc           QualType QT = (*I)->getType();
4510*0a6a1f1dSLionel Sambuc           QT = Context->getPointerType(QT);
4511*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4512*0a6a1f1dSLionel Sambuc                                             OK_Ordinary, SourceLocation());
4513*0a6a1f1dSLionel Sambuc         }
4514*0a6a1f1dSLionel Sambuc 
4515*0a6a1f1dSLionel Sambuc       }
4516*0a6a1f1dSLionel Sambuc       InitExprs.push_back(Exp);
4517*0a6a1f1dSLionel Sambuc     }
4518*0a6a1f1dSLionel Sambuc     // Output all "by ref" declarations.
4519*0a6a1f1dSLionel Sambuc     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4520*0a6a1f1dSLionel Sambuc          E = BlockByRefDecls.end(); I != E; ++I) {
4521*0a6a1f1dSLionel Sambuc       ValueDecl *ND = (*I);
4522*0a6a1f1dSLionel Sambuc       std::string Name(ND->getNameAsString());
4523*0a6a1f1dSLionel Sambuc       std::string RecName;
4524*0a6a1f1dSLionel Sambuc       RewriteByRefString(RecName, Name, ND, true);
4525*0a6a1f1dSLionel Sambuc       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4526*0a6a1f1dSLionel Sambuc                                                 + sizeof("struct"));
4527*0a6a1f1dSLionel Sambuc       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4528*0a6a1f1dSLionel Sambuc                                           SourceLocation(), SourceLocation(),
4529*0a6a1f1dSLionel Sambuc                                           II);
4530*0a6a1f1dSLionel Sambuc       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4531*0a6a1f1dSLionel Sambuc       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4532*0a6a1f1dSLionel Sambuc 
4533*0a6a1f1dSLionel Sambuc       FD = SynthBlockInitFunctionDecl((*I)->getName());
4534*0a6a1f1dSLionel Sambuc       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4535*0a6a1f1dSLionel Sambuc                                       SourceLocation());
4536*0a6a1f1dSLionel Sambuc       bool isNestedCapturedVar = false;
4537*0a6a1f1dSLionel Sambuc       if (block)
4538*0a6a1f1dSLionel Sambuc         for (const auto &CI : block->captures()) {
4539*0a6a1f1dSLionel Sambuc           const VarDecl *variable = CI.getVariable();
4540*0a6a1f1dSLionel Sambuc           if (variable == ND && CI.isNested()) {
4541*0a6a1f1dSLionel Sambuc             assert (CI.isByRef() &&
4542*0a6a1f1dSLionel Sambuc                     "SynthBlockInitExpr - captured block variable is not byref");
4543*0a6a1f1dSLionel Sambuc             isNestedCapturedVar = true;
4544*0a6a1f1dSLionel Sambuc             break;
4545*0a6a1f1dSLionel Sambuc           }
4546*0a6a1f1dSLionel Sambuc         }
4547*0a6a1f1dSLionel Sambuc       // captured nested byref variable has its address passed. Do not take
4548*0a6a1f1dSLionel Sambuc       // its address again.
4549*0a6a1f1dSLionel Sambuc       if (!isNestedCapturedVar)
4550*0a6a1f1dSLionel Sambuc           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4551*0a6a1f1dSLionel Sambuc                                      Context->getPointerType(Exp->getType()),
4552*0a6a1f1dSLionel Sambuc                                      VK_RValue, OK_Ordinary, SourceLocation());
4553*0a6a1f1dSLionel Sambuc       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4554*0a6a1f1dSLionel Sambuc       InitExprs.push_back(Exp);
4555*0a6a1f1dSLionel Sambuc     }
4556*0a6a1f1dSLionel Sambuc   }
4557*0a6a1f1dSLionel Sambuc   if (ImportedBlockDecls.size()) {
4558*0a6a1f1dSLionel Sambuc     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4559*0a6a1f1dSLionel Sambuc     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4560*0a6a1f1dSLionel Sambuc     unsigned IntSize =
4561*0a6a1f1dSLionel Sambuc       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4562*0a6a1f1dSLionel Sambuc     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4563*0a6a1f1dSLionel Sambuc                                            Context->IntTy, SourceLocation());
4564*0a6a1f1dSLionel Sambuc     InitExprs.push_back(FlagExp);
4565*0a6a1f1dSLionel Sambuc   }
4566*0a6a1f1dSLionel Sambuc   NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
4567*0a6a1f1dSLionel Sambuc                                   FType, VK_LValue, SourceLocation());
4568*0a6a1f1dSLionel Sambuc   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4569*0a6a1f1dSLionel Sambuc                              Context->getPointerType(NewRep->getType()),
4570*0a6a1f1dSLionel Sambuc                              VK_RValue, OK_Ordinary, SourceLocation());
4571*0a6a1f1dSLionel Sambuc   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4572*0a6a1f1dSLionel Sambuc                                     NewRep);
4573*0a6a1f1dSLionel Sambuc   BlockDeclRefs.clear();
4574*0a6a1f1dSLionel Sambuc   BlockByRefDecls.clear();
4575*0a6a1f1dSLionel Sambuc   BlockByRefDeclsPtrSet.clear();
4576*0a6a1f1dSLionel Sambuc   BlockByCopyDecls.clear();
4577*0a6a1f1dSLionel Sambuc   BlockByCopyDeclsPtrSet.clear();
4578*0a6a1f1dSLionel Sambuc   ImportedBlockDecls.clear();
4579*0a6a1f1dSLionel Sambuc   return NewRep;
4580*0a6a1f1dSLionel Sambuc }
4581*0a6a1f1dSLionel Sambuc 
IsDeclStmtInForeachHeader(DeclStmt * DS)4582*0a6a1f1dSLionel Sambuc bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4583*0a6a1f1dSLionel Sambuc   if (const ObjCForCollectionStmt * CS =
4584*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4585*0a6a1f1dSLionel Sambuc         return CS->getElement() == DS;
4586*0a6a1f1dSLionel Sambuc   return false;
4587*0a6a1f1dSLionel Sambuc }
4588*0a6a1f1dSLionel Sambuc 
4589*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
4590*0a6a1f1dSLionel Sambuc // Function Body / Expression rewriting
4591*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
4592*0a6a1f1dSLionel Sambuc 
RewriteFunctionBodyOrGlobalInitializer(Stmt * S)4593*0a6a1f1dSLionel Sambuc Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4594*0a6a1f1dSLionel Sambuc   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4595*0a6a1f1dSLionel Sambuc       isa<DoStmt>(S) || isa<ForStmt>(S))
4596*0a6a1f1dSLionel Sambuc     Stmts.push_back(S);
4597*0a6a1f1dSLionel Sambuc   else if (isa<ObjCForCollectionStmt>(S)) {
4598*0a6a1f1dSLionel Sambuc     Stmts.push_back(S);
4599*0a6a1f1dSLionel Sambuc     ObjCBcLabelNo.push_back(++BcLabelCount);
4600*0a6a1f1dSLionel Sambuc   }
4601*0a6a1f1dSLionel Sambuc 
4602*0a6a1f1dSLionel Sambuc   // Pseudo-object operations and ivar references need special
4603*0a6a1f1dSLionel Sambuc   // treatment because we're going to recursively rewrite them.
4604*0a6a1f1dSLionel Sambuc   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4605*0a6a1f1dSLionel Sambuc     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4606*0a6a1f1dSLionel Sambuc       return RewritePropertyOrImplicitSetter(PseudoOp);
4607*0a6a1f1dSLionel Sambuc     } else {
4608*0a6a1f1dSLionel Sambuc       return RewritePropertyOrImplicitGetter(PseudoOp);
4609*0a6a1f1dSLionel Sambuc     }
4610*0a6a1f1dSLionel Sambuc   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4611*0a6a1f1dSLionel Sambuc     return RewriteObjCIvarRefExpr(IvarRefExpr);
4612*0a6a1f1dSLionel Sambuc   }
4613*0a6a1f1dSLionel Sambuc 
4614*0a6a1f1dSLionel Sambuc   SourceRange OrigStmtRange = S->getSourceRange();
4615*0a6a1f1dSLionel Sambuc 
4616*0a6a1f1dSLionel Sambuc   // Perform a bottom up rewrite of all children.
4617*0a6a1f1dSLionel Sambuc   for (Stmt::child_range CI = S->children(); CI; ++CI)
4618*0a6a1f1dSLionel Sambuc     if (*CI) {
4619*0a6a1f1dSLionel Sambuc       Stmt *childStmt = (*CI);
4620*0a6a1f1dSLionel Sambuc       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4621*0a6a1f1dSLionel Sambuc       if (newStmt) {
4622*0a6a1f1dSLionel Sambuc         *CI = newStmt;
4623*0a6a1f1dSLionel Sambuc       }
4624*0a6a1f1dSLionel Sambuc     }
4625*0a6a1f1dSLionel Sambuc 
4626*0a6a1f1dSLionel Sambuc   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4627*0a6a1f1dSLionel Sambuc     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4628*0a6a1f1dSLionel Sambuc     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4629*0a6a1f1dSLionel Sambuc     InnerContexts.insert(BE->getBlockDecl());
4630*0a6a1f1dSLionel Sambuc     ImportedLocalExternalDecls.clear();
4631*0a6a1f1dSLionel Sambuc     GetInnerBlockDeclRefExprs(BE->getBody(),
4632*0a6a1f1dSLionel Sambuc                               InnerBlockDeclRefs, InnerContexts);
4633*0a6a1f1dSLionel Sambuc     // Rewrite the block body in place.
4634*0a6a1f1dSLionel Sambuc     Stmt *SaveCurrentBody = CurrentBody;
4635*0a6a1f1dSLionel Sambuc     CurrentBody = BE->getBody();
4636*0a6a1f1dSLionel Sambuc     PropParentMap = nullptr;
4637*0a6a1f1dSLionel Sambuc     // block literal on rhs of a property-dot-sytax assignment
4638*0a6a1f1dSLionel Sambuc     // must be replaced by its synthesize ast so getRewrittenText
4639*0a6a1f1dSLionel Sambuc     // works as expected. In this case, what actually ends up on RHS
4640*0a6a1f1dSLionel Sambuc     // is the blockTranscribed which is the helper function for the
4641*0a6a1f1dSLionel Sambuc     // block literal; as in: self.c = ^() {[ace ARR];};
4642*0a6a1f1dSLionel Sambuc     bool saveDisableReplaceStmt = DisableReplaceStmt;
4643*0a6a1f1dSLionel Sambuc     DisableReplaceStmt = false;
4644*0a6a1f1dSLionel Sambuc     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4645*0a6a1f1dSLionel Sambuc     DisableReplaceStmt = saveDisableReplaceStmt;
4646*0a6a1f1dSLionel Sambuc     CurrentBody = SaveCurrentBody;
4647*0a6a1f1dSLionel Sambuc     PropParentMap = nullptr;
4648*0a6a1f1dSLionel Sambuc     ImportedLocalExternalDecls.clear();
4649*0a6a1f1dSLionel Sambuc     // Now we snarf the rewritten text and stash it away for later use.
4650*0a6a1f1dSLionel Sambuc     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4651*0a6a1f1dSLionel Sambuc     RewrittenBlockExprs[BE] = Str;
4652*0a6a1f1dSLionel Sambuc 
4653*0a6a1f1dSLionel Sambuc     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4654*0a6a1f1dSLionel Sambuc 
4655*0a6a1f1dSLionel Sambuc     //blockTranscribed->dump();
4656*0a6a1f1dSLionel Sambuc     ReplaceStmt(S, blockTranscribed);
4657*0a6a1f1dSLionel Sambuc     return blockTranscribed;
4658*0a6a1f1dSLionel Sambuc   }
4659*0a6a1f1dSLionel Sambuc   // Handle specific things.
4660*0a6a1f1dSLionel Sambuc   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4661*0a6a1f1dSLionel Sambuc     return RewriteAtEncode(AtEncode);
4662*0a6a1f1dSLionel Sambuc 
4663*0a6a1f1dSLionel Sambuc   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4664*0a6a1f1dSLionel Sambuc     return RewriteAtSelector(AtSelector);
4665*0a6a1f1dSLionel Sambuc 
4666*0a6a1f1dSLionel Sambuc   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4667*0a6a1f1dSLionel Sambuc     return RewriteObjCStringLiteral(AtString);
4668*0a6a1f1dSLionel Sambuc 
4669*0a6a1f1dSLionel Sambuc   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4670*0a6a1f1dSLionel Sambuc #if 0
4671*0a6a1f1dSLionel Sambuc     // Before we rewrite it, put the original message expression in a comment.
4672*0a6a1f1dSLionel Sambuc     SourceLocation startLoc = MessExpr->getLocStart();
4673*0a6a1f1dSLionel Sambuc     SourceLocation endLoc = MessExpr->getLocEnd();
4674*0a6a1f1dSLionel Sambuc 
4675*0a6a1f1dSLionel Sambuc     const char *startBuf = SM->getCharacterData(startLoc);
4676*0a6a1f1dSLionel Sambuc     const char *endBuf = SM->getCharacterData(endLoc);
4677*0a6a1f1dSLionel Sambuc 
4678*0a6a1f1dSLionel Sambuc     std::string messString;
4679*0a6a1f1dSLionel Sambuc     messString += "// ";
4680*0a6a1f1dSLionel Sambuc     messString.append(startBuf, endBuf-startBuf+1);
4681*0a6a1f1dSLionel Sambuc     messString += "\n";
4682*0a6a1f1dSLionel Sambuc 
4683*0a6a1f1dSLionel Sambuc     // FIXME: Missing definition of
4684*0a6a1f1dSLionel Sambuc     // InsertText(clang::SourceLocation, char const*, unsigned int).
4685*0a6a1f1dSLionel Sambuc     // InsertText(startLoc, messString.c_str(), messString.size());
4686*0a6a1f1dSLionel Sambuc     // Tried this, but it didn't work either...
4687*0a6a1f1dSLionel Sambuc     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4688*0a6a1f1dSLionel Sambuc #endif
4689*0a6a1f1dSLionel Sambuc     return RewriteMessageExpr(MessExpr);
4690*0a6a1f1dSLionel Sambuc   }
4691*0a6a1f1dSLionel Sambuc 
4692*0a6a1f1dSLionel Sambuc   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4693*0a6a1f1dSLionel Sambuc     return RewriteObjCTryStmt(StmtTry);
4694*0a6a1f1dSLionel Sambuc 
4695*0a6a1f1dSLionel Sambuc   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4696*0a6a1f1dSLionel Sambuc     return RewriteObjCSynchronizedStmt(StmtTry);
4697*0a6a1f1dSLionel Sambuc 
4698*0a6a1f1dSLionel Sambuc   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4699*0a6a1f1dSLionel Sambuc     return RewriteObjCThrowStmt(StmtThrow);
4700*0a6a1f1dSLionel Sambuc 
4701*0a6a1f1dSLionel Sambuc   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4702*0a6a1f1dSLionel Sambuc     return RewriteObjCProtocolExpr(ProtocolExp);
4703*0a6a1f1dSLionel Sambuc 
4704*0a6a1f1dSLionel Sambuc   if (ObjCForCollectionStmt *StmtForCollection =
4705*0a6a1f1dSLionel Sambuc         dyn_cast<ObjCForCollectionStmt>(S))
4706*0a6a1f1dSLionel Sambuc     return RewriteObjCForCollectionStmt(StmtForCollection,
4707*0a6a1f1dSLionel Sambuc                                         OrigStmtRange.getEnd());
4708*0a6a1f1dSLionel Sambuc   if (BreakStmt *StmtBreakStmt =
4709*0a6a1f1dSLionel Sambuc       dyn_cast<BreakStmt>(S))
4710*0a6a1f1dSLionel Sambuc     return RewriteBreakStmt(StmtBreakStmt);
4711*0a6a1f1dSLionel Sambuc   if (ContinueStmt *StmtContinueStmt =
4712*0a6a1f1dSLionel Sambuc       dyn_cast<ContinueStmt>(S))
4713*0a6a1f1dSLionel Sambuc     return RewriteContinueStmt(StmtContinueStmt);
4714*0a6a1f1dSLionel Sambuc 
4715*0a6a1f1dSLionel Sambuc   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4716*0a6a1f1dSLionel Sambuc   // and cast exprs.
4717*0a6a1f1dSLionel Sambuc   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4718*0a6a1f1dSLionel Sambuc     // FIXME: What we're doing here is modifying the type-specifier that
4719*0a6a1f1dSLionel Sambuc     // precedes the first Decl.  In the future the DeclGroup should have
4720*0a6a1f1dSLionel Sambuc     // a separate type-specifier that we can rewrite.
4721*0a6a1f1dSLionel Sambuc     // NOTE: We need to avoid rewriting the DeclStmt if it is within
4722*0a6a1f1dSLionel Sambuc     // the context of an ObjCForCollectionStmt. For example:
4723*0a6a1f1dSLionel Sambuc     //   NSArray *someArray;
4724*0a6a1f1dSLionel Sambuc     //   for (id <FooProtocol> index in someArray) ;
4725*0a6a1f1dSLionel Sambuc     // This is because RewriteObjCForCollectionStmt() does textual rewriting
4726*0a6a1f1dSLionel Sambuc     // and it depends on the original text locations/positions.
4727*0a6a1f1dSLionel Sambuc     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4728*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4729*0a6a1f1dSLionel Sambuc 
4730*0a6a1f1dSLionel Sambuc     // Blocks rewrite rules.
4731*0a6a1f1dSLionel Sambuc     for (auto *SD : DS->decls()) {
4732*0a6a1f1dSLionel Sambuc       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4733*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(ND->getType()))
4734*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(ND);
4735*0a6a1f1dSLionel Sambuc         else if (ND->getType()->isFunctionPointerType())
4736*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(ND->getType(), ND);
4737*0a6a1f1dSLionel Sambuc         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4738*0a6a1f1dSLionel Sambuc           if (VD->hasAttr<BlocksAttr>()) {
4739*0a6a1f1dSLionel Sambuc             static unsigned uniqueByrefDeclCount = 0;
4740*0a6a1f1dSLionel Sambuc             assert(!BlockByRefDeclNo.count(ND) &&
4741*0a6a1f1dSLionel Sambuc               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4742*0a6a1f1dSLionel Sambuc             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4743*0a6a1f1dSLionel Sambuc             RewriteByRefVar(VD);
4744*0a6a1f1dSLionel Sambuc           }
4745*0a6a1f1dSLionel Sambuc           else
4746*0a6a1f1dSLionel Sambuc             RewriteTypeOfDecl(VD);
4747*0a6a1f1dSLionel Sambuc         }
4748*0a6a1f1dSLionel Sambuc       }
4749*0a6a1f1dSLionel Sambuc       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4750*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4751*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(TD);
4752*0a6a1f1dSLionel Sambuc         else if (TD->getUnderlyingType()->isFunctionPointerType())
4753*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4754*0a6a1f1dSLionel Sambuc       }
4755*0a6a1f1dSLionel Sambuc     }
4756*0a6a1f1dSLionel Sambuc   }
4757*0a6a1f1dSLionel Sambuc 
4758*0a6a1f1dSLionel Sambuc   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4759*0a6a1f1dSLionel Sambuc     RewriteObjCQualifiedInterfaceTypes(CE);
4760*0a6a1f1dSLionel Sambuc 
4761*0a6a1f1dSLionel Sambuc   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4762*0a6a1f1dSLionel Sambuc       isa<DoStmt>(S) || isa<ForStmt>(S)) {
4763*0a6a1f1dSLionel Sambuc     assert(!Stmts.empty() && "Statement stack is empty");
4764*0a6a1f1dSLionel Sambuc     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4765*0a6a1f1dSLionel Sambuc              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4766*0a6a1f1dSLionel Sambuc             && "Statement stack mismatch");
4767*0a6a1f1dSLionel Sambuc     Stmts.pop_back();
4768*0a6a1f1dSLionel Sambuc   }
4769*0a6a1f1dSLionel Sambuc   // Handle blocks rewriting.
4770*0a6a1f1dSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4771*0a6a1f1dSLionel Sambuc     ValueDecl *VD = DRE->getDecl();
4772*0a6a1f1dSLionel Sambuc     if (VD->hasAttr<BlocksAttr>())
4773*0a6a1f1dSLionel Sambuc       return RewriteBlockDeclRefExpr(DRE);
4774*0a6a1f1dSLionel Sambuc     if (HasLocalVariableExternalStorage(VD))
4775*0a6a1f1dSLionel Sambuc       return RewriteLocalVariableExternalStorage(DRE);
4776*0a6a1f1dSLionel Sambuc   }
4777*0a6a1f1dSLionel Sambuc 
4778*0a6a1f1dSLionel Sambuc   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4779*0a6a1f1dSLionel Sambuc     if (CE->getCallee()->getType()->isBlockPointerType()) {
4780*0a6a1f1dSLionel Sambuc       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4781*0a6a1f1dSLionel Sambuc       ReplaceStmt(S, BlockCall);
4782*0a6a1f1dSLionel Sambuc       return BlockCall;
4783*0a6a1f1dSLionel Sambuc     }
4784*0a6a1f1dSLionel Sambuc   }
4785*0a6a1f1dSLionel Sambuc   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4786*0a6a1f1dSLionel Sambuc     RewriteCastExpr(CE);
4787*0a6a1f1dSLionel Sambuc   }
4788*0a6a1f1dSLionel Sambuc #if 0
4789*0a6a1f1dSLionel Sambuc   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4790*0a6a1f1dSLionel Sambuc     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4791*0a6a1f1dSLionel Sambuc                                                    ICE->getSubExpr(),
4792*0a6a1f1dSLionel Sambuc                                                    SourceLocation());
4793*0a6a1f1dSLionel Sambuc     // Get the new text.
4794*0a6a1f1dSLionel Sambuc     std::string SStr;
4795*0a6a1f1dSLionel Sambuc     llvm::raw_string_ostream Buf(SStr);
4796*0a6a1f1dSLionel Sambuc     Replacement->printPretty(Buf);
4797*0a6a1f1dSLionel Sambuc     const std::string &Str = Buf.str();
4798*0a6a1f1dSLionel Sambuc 
4799*0a6a1f1dSLionel Sambuc     printf("CAST = %s\n", &Str[0]);
4800*0a6a1f1dSLionel Sambuc     InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4801*0a6a1f1dSLionel Sambuc     delete S;
4802*0a6a1f1dSLionel Sambuc     return Replacement;
4803*0a6a1f1dSLionel Sambuc   }
4804*0a6a1f1dSLionel Sambuc #endif
4805*0a6a1f1dSLionel Sambuc   // Return this stmt unmodified.
4806*0a6a1f1dSLionel Sambuc   return S;
4807*0a6a1f1dSLionel Sambuc }
4808*0a6a1f1dSLionel Sambuc 
RewriteRecordBody(RecordDecl * RD)4809*0a6a1f1dSLionel Sambuc void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4810*0a6a1f1dSLionel Sambuc   for (auto *FD : RD->fields()) {
4811*0a6a1f1dSLionel Sambuc     if (isTopLevelBlockPointerType(FD->getType()))
4812*0a6a1f1dSLionel Sambuc       RewriteBlockPointerDecl(FD);
4813*0a6a1f1dSLionel Sambuc     if (FD->getType()->isObjCQualifiedIdType() ||
4814*0a6a1f1dSLionel Sambuc         FD->getType()->isObjCQualifiedInterfaceType())
4815*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(FD);
4816*0a6a1f1dSLionel Sambuc   }
4817*0a6a1f1dSLionel Sambuc }
4818*0a6a1f1dSLionel Sambuc 
4819*0a6a1f1dSLionel Sambuc /// HandleDeclInMainFile - This is called for each top-level decl defined in the
4820*0a6a1f1dSLionel Sambuc /// main file of the input.
HandleDeclInMainFile(Decl * D)4821*0a6a1f1dSLionel Sambuc void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4822*0a6a1f1dSLionel Sambuc   switch (D->getKind()) {
4823*0a6a1f1dSLionel Sambuc     case Decl::Function: {
4824*0a6a1f1dSLionel Sambuc       FunctionDecl *FD = cast<FunctionDecl>(D);
4825*0a6a1f1dSLionel Sambuc       if (FD->isOverloadedOperator())
4826*0a6a1f1dSLionel Sambuc         return;
4827*0a6a1f1dSLionel Sambuc 
4828*0a6a1f1dSLionel Sambuc       // Since function prototypes don't have ParmDecl's, we check the function
4829*0a6a1f1dSLionel Sambuc       // prototype. This enables us to rewrite function declarations and
4830*0a6a1f1dSLionel Sambuc       // definitions using the same code.
4831*0a6a1f1dSLionel Sambuc       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4832*0a6a1f1dSLionel Sambuc 
4833*0a6a1f1dSLionel Sambuc       if (!FD->isThisDeclarationADefinition())
4834*0a6a1f1dSLionel Sambuc         break;
4835*0a6a1f1dSLionel Sambuc 
4836*0a6a1f1dSLionel Sambuc       // FIXME: If this should support Obj-C++, support CXXTryStmt
4837*0a6a1f1dSLionel Sambuc       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4838*0a6a1f1dSLionel Sambuc         CurFunctionDef = FD;
4839*0a6a1f1dSLionel Sambuc         CurFunctionDeclToDeclareForBlock = FD;
4840*0a6a1f1dSLionel Sambuc         CurrentBody = Body;
4841*0a6a1f1dSLionel Sambuc         Body =
4842*0a6a1f1dSLionel Sambuc         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4843*0a6a1f1dSLionel Sambuc         FD->setBody(Body);
4844*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
4845*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
4846*0a6a1f1dSLionel Sambuc           delete PropParentMap;
4847*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
4848*0a6a1f1dSLionel Sambuc         }
4849*0a6a1f1dSLionel Sambuc         // This synthesizes and inserts the block "impl" struct, invoke function,
4850*0a6a1f1dSLionel Sambuc         // and any copy/dispose helper functions.
4851*0a6a1f1dSLionel Sambuc         InsertBlockLiteralsWithinFunction(FD);
4852*0a6a1f1dSLionel Sambuc         CurFunctionDef = nullptr;
4853*0a6a1f1dSLionel Sambuc         CurFunctionDeclToDeclareForBlock = nullptr;
4854*0a6a1f1dSLionel Sambuc       }
4855*0a6a1f1dSLionel Sambuc       break;
4856*0a6a1f1dSLionel Sambuc     }
4857*0a6a1f1dSLionel Sambuc     case Decl::ObjCMethod: {
4858*0a6a1f1dSLionel Sambuc       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4859*0a6a1f1dSLionel Sambuc       if (CompoundStmt *Body = MD->getCompoundBody()) {
4860*0a6a1f1dSLionel Sambuc         CurMethodDef = MD;
4861*0a6a1f1dSLionel Sambuc         CurrentBody = Body;
4862*0a6a1f1dSLionel Sambuc         Body =
4863*0a6a1f1dSLionel Sambuc           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4864*0a6a1f1dSLionel Sambuc         MD->setBody(Body);
4865*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
4866*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
4867*0a6a1f1dSLionel Sambuc           delete PropParentMap;
4868*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
4869*0a6a1f1dSLionel Sambuc         }
4870*0a6a1f1dSLionel Sambuc         InsertBlockLiteralsWithinMethod(MD);
4871*0a6a1f1dSLionel Sambuc         CurMethodDef = nullptr;
4872*0a6a1f1dSLionel Sambuc       }
4873*0a6a1f1dSLionel Sambuc       break;
4874*0a6a1f1dSLionel Sambuc     }
4875*0a6a1f1dSLionel Sambuc     case Decl::ObjCImplementation: {
4876*0a6a1f1dSLionel Sambuc       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4877*0a6a1f1dSLionel Sambuc       ClassImplementation.push_back(CI);
4878*0a6a1f1dSLionel Sambuc       break;
4879*0a6a1f1dSLionel Sambuc     }
4880*0a6a1f1dSLionel Sambuc     case Decl::ObjCCategoryImpl: {
4881*0a6a1f1dSLionel Sambuc       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4882*0a6a1f1dSLionel Sambuc       CategoryImplementation.push_back(CI);
4883*0a6a1f1dSLionel Sambuc       break;
4884*0a6a1f1dSLionel Sambuc     }
4885*0a6a1f1dSLionel Sambuc     case Decl::Var: {
4886*0a6a1f1dSLionel Sambuc       VarDecl *VD = cast<VarDecl>(D);
4887*0a6a1f1dSLionel Sambuc       RewriteObjCQualifiedInterfaceTypes(VD);
4888*0a6a1f1dSLionel Sambuc       if (isTopLevelBlockPointerType(VD->getType()))
4889*0a6a1f1dSLionel Sambuc         RewriteBlockPointerDecl(VD);
4890*0a6a1f1dSLionel Sambuc       else if (VD->getType()->isFunctionPointerType()) {
4891*0a6a1f1dSLionel Sambuc         CheckFunctionPointerDecl(VD->getType(), VD);
4892*0a6a1f1dSLionel Sambuc         if (VD->getInit()) {
4893*0a6a1f1dSLionel Sambuc           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4894*0a6a1f1dSLionel Sambuc             RewriteCastExpr(CE);
4895*0a6a1f1dSLionel Sambuc           }
4896*0a6a1f1dSLionel Sambuc         }
4897*0a6a1f1dSLionel Sambuc       } else if (VD->getType()->isRecordType()) {
4898*0a6a1f1dSLionel Sambuc         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4899*0a6a1f1dSLionel Sambuc         if (RD->isCompleteDefinition())
4900*0a6a1f1dSLionel Sambuc           RewriteRecordBody(RD);
4901*0a6a1f1dSLionel Sambuc       }
4902*0a6a1f1dSLionel Sambuc       if (VD->getInit()) {
4903*0a6a1f1dSLionel Sambuc         GlobalVarDecl = VD;
4904*0a6a1f1dSLionel Sambuc         CurrentBody = VD->getInit();
4905*0a6a1f1dSLionel Sambuc         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4906*0a6a1f1dSLionel Sambuc         CurrentBody = nullptr;
4907*0a6a1f1dSLionel Sambuc         if (PropParentMap) {
4908*0a6a1f1dSLionel Sambuc           delete PropParentMap;
4909*0a6a1f1dSLionel Sambuc           PropParentMap = nullptr;
4910*0a6a1f1dSLionel Sambuc         }
4911*0a6a1f1dSLionel Sambuc         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4912*0a6a1f1dSLionel Sambuc         GlobalVarDecl = nullptr;
4913*0a6a1f1dSLionel Sambuc 
4914*0a6a1f1dSLionel Sambuc         // This is needed for blocks.
4915*0a6a1f1dSLionel Sambuc         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4916*0a6a1f1dSLionel Sambuc             RewriteCastExpr(CE);
4917*0a6a1f1dSLionel Sambuc         }
4918*0a6a1f1dSLionel Sambuc       }
4919*0a6a1f1dSLionel Sambuc       break;
4920*0a6a1f1dSLionel Sambuc     }
4921*0a6a1f1dSLionel Sambuc     case Decl::TypeAlias:
4922*0a6a1f1dSLionel Sambuc     case Decl::Typedef: {
4923*0a6a1f1dSLionel Sambuc       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4924*0a6a1f1dSLionel Sambuc         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4925*0a6a1f1dSLionel Sambuc           RewriteBlockPointerDecl(TD);
4926*0a6a1f1dSLionel Sambuc         else if (TD->getUnderlyingType()->isFunctionPointerType())
4927*0a6a1f1dSLionel Sambuc           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4928*0a6a1f1dSLionel Sambuc       }
4929*0a6a1f1dSLionel Sambuc       break;
4930*0a6a1f1dSLionel Sambuc     }
4931*0a6a1f1dSLionel Sambuc     case Decl::CXXRecord:
4932*0a6a1f1dSLionel Sambuc     case Decl::Record: {
4933*0a6a1f1dSLionel Sambuc       RecordDecl *RD = cast<RecordDecl>(D);
4934*0a6a1f1dSLionel Sambuc       if (RD->isCompleteDefinition())
4935*0a6a1f1dSLionel Sambuc         RewriteRecordBody(RD);
4936*0a6a1f1dSLionel Sambuc       break;
4937*0a6a1f1dSLionel Sambuc     }
4938*0a6a1f1dSLionel Sambuc     default:
4939*0a6a1f1dSLionel Sambuc       break;
4940*0a6a1f1dSLionel Sambuc   }
4941*0a6a1f1dSLionel Sambuc   // Nothing yet.
4942*0a6a1f1dSLionel Sambuc }
4943*0a6a1f1dSLionel Sambuc 
HandleTranslationUnit(ASTContext & C)4944*0a6a1f1dSLionel Sambuc void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4945*0a6a1f1dSLionel Sambuc   if (Diags.hasErrorOccurred())
4946*0a6a1f1dSLionel Sambuc     return;
4947*0a6a1f1dSLionel Sambuc 
4948*0a6a1f1dSLionel Sambuc   RewriteInclude();
4949*0a6a1f1dSLionel Sambuc 
4950*0a6a1f1dSLionel Sambuc   // Here's a great place to add any extra declarations that may be needed.
4951*0a6a1f1dSLionel Sambuc   // Write out meta data for each @protocol(<expr>).
4952*0a6a1f1dSLionel Sambuc   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4953*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4954*0a6a1f1dSLionel Sambuc 
4955*0a6a1f1dSLionel Sambuc   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4956*0a6a1f1dSLionel Sambuc   if (ClassImplementation.size() || CategoryImplementation.size())
4957*0a6a1f1dSLionel Sambuc     RewriteImplementations();
4958*0a6a1f1dSLionel Sambuc 
4959*0a6a1f1dSLionel Sambuc   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4960*0a6a1f1dSLionel Sambuc   // we are done.
4961*0a6a1f1dSLionel Sambuc   if (const RewriteBuffer *RewriteBuf =
4962*0a6a1f1dSLionel Sambuc       Rewrite.getRewriteBufferFor(MainFileID)) {
4963*0a6a1f1dSLionel Sambuc     //printf("Changed:\n");
4964*0a6a1f1dSLionel Sambuc     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4965*0a6a1f1dSLionel Sambuc   } else {
4966*0a6a1f1dSLionel Sambuc     llvm::errs() << "No changes\n";
4967*0a6a1f1dSLionel Sambuc   }
4968*0a6a1f1dSLionel Sambuc 
4969*0a6a1f1dSLionel Sambuc   if (ClassImplementation.size() || CategoryImplementation.size() ||
4970*0a6a1f1dSLionel Sambuc       ProtocolExprDecls.size()) {
4971*0a6a1f1dSLionel Sambuc     // Rewrite Objective-c meta data*
4972*0a6a1f1dSLionel Sambuc     std::string ResultStr;
4973*0a6a1f1dSLionel Sambuc     RewriteMetaDataIntoBuffer(ResultStr);
4974*0a6a1f1dSLionel Sambuc     // Emit metadata.
4975*0a6a1f1dSLionel Sambuc     *OutFile << ResultStr;
4976*0a6a1f1dSLionel Sambuc   }
4977*0a6a1f1dSLionel Sambuc   OutFile->flush();
4978*0a6a1f1dSLionel Sambuc }
4979*0a6a1f1dSLionel Sambuc 
Initialize(ASTContext & context)4980*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4981*0a6a1f1dSLionel Sambuc   InitializeCommon(context);
4982*0a6a1f1dSLionel Sambuc 
4983*0a6a1f1dSLionel Sambuc   // declaring objc_selector outside the parameter list removes a silly
4984*0a6a1f1dSLionel Sambuc   // scope related warning...
4985*0a6a1f1dSLionel Sambuc   if (IsHeader)
4986*0a6a1f1dSLionel Sambuc     Preamble = "#pragma once\n";
4987*0a6a1f1dSLionel Sambuc   Preamble += "struct objc_selector; struct objc_class;\n";
4988*0a6a1f1dSLionel Sambuc   Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4989*0a6a1f1dSLionel Sambuc   Preamble += "struct objc_object *superClass; ";
4990*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
4991*0a6a1f1dSLionel Sambuc     // Add a constructor for creating temporary objects.
4992*0a6a1f1dSLionel Sambuc     Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4993*0a6a1f1dSLionel Sambuc     ": ";
4994*0a6a1f1dSLionel Sambuc     Preamble += "object(o), superClass(s) {} ";
4995*0a6a1f1dSLionel Sambuc   }
4996*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
4997*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4998*0a6a1f1dSLionel Sambuc   Preamble += "typedef struct objc_object Protocol;\n";
4999*0a6a1f1dSLionel Sambuc   Preamble += "#define _REWRITER_typedef_Protocol\n";
5000*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5001*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
5002*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5003*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5004*0a6a1f1dSLionel Sambuc   } else
5005*0a6a1f1dSLionel Sambuc     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5006*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5007*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5008*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5009*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5010*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5011*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5012*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5013*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5014*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5015*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5016*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5017*0a6a1f1dSLionel Sambuc   Preamble += "(const char *);\n";
5018*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5019*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_class *);\n";
5020*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5021*0a6a1f1dSLionel Sambuc   Preamble += "(const char *);\n";
5022*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5023*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5024*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5025*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5026*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5027*0a6a1f1dSLionel Sambuc   Preamble += "(struct objc_class *, struct objc_object *);\n";
5028*0a6a1f1dSLionel Sambuc   // @synchronized hooks.
5029*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5030*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
5031*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5032*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5033*0a6a1f1dSLionel Sambuc   Preamble += "struct __objcFastEnumerationState {\n\t";
5034*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long state;\n\t";
5035*0a6a1f1dSLionel Sambuc   Preamble += "void **itemsPtr;\n\t";
5036*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long *mutationsPtr;\n\t";
5037*0a6a1f1dSLionel Sambuc   Preamble += "unsigned long extra[5];\n};\n";
5038*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5039*0a6a1f1dSLionel Sambuc   Preamble += "#define __FASTENUMERATIONSTATE\n";
5040*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5041*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5042*0a6a1f1dSLionel Sambuc   Preamble += "struct __NSConstantStringImpl {\n";
5043*0a6a1f1dSLionel Sambuc   Preamble += "  int *isa;\n";
5044*0a6a1f1dSLionel Sambuc   Preamble += "  int flags;\n";
5045*0a6a1f1dSLionel Sambuc   Preamble += "  char *str;\n";
5046*0a6a1f1dSLionel Sambuc   Preamble += "  long length;\n";
5047*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
5048*0a6a1f1dSLionel Sambuc   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5049*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5050*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
5051*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5052*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5053*0a6a1f1dSLionel Sambuc   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5054*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5055*0a6a1f1dSLionel Sambuc   // Blocks preamble.
5056*0a6a1f1dSLionel Sambuc   Preamble += "#ifndef BLOCK_IMPL\n";
5057*0a6a1f1dSLionel Sambuc   Preamble += "#define BLOCK_IMPL\n";
5058*0a6a1f1dSLionel Sambuc   Preamble += "struct __block_impl {\n";
5059*0a6a1f1dSLionel Sambuc   Preamble += "  void *isa;\n";
5060*0a6a1f1dSLionel Sambuc   Preamble += "  int Flags;\n";
5061*0a6a1f1dSLionel Sambuc   Preamble += "  int Reserved;\n";
5062*0a6a1f1dSLionel Sambuc   Preamble += "  void *FuncPtr;\n";
5063*0a6a1f1dSLionel Sambuc   Preamble += "};\n";
5064*0a6a1f1dSLionel Sambuc   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5065*0a6a1f1dSLionel Sambuc   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5066*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) "
5067*0a6a1f1dSLionel Sambuc   "void _Block_object_assign(void *, const void *, const int);\n";
5068*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5069*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5070*0a6a1f1dSLionel Sambuc   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5071*0a6a1f1dSLionel Sambuc   Preamble += "#else\n";
5072*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5073*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5074*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5075*0a6a1f1dSLionel Sambuc   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5076*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5077*0a6a1f1dSLionel Sambuc   Preamble += "#endif\n";
5078*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
5079*0a6a1f1dSLionel Sambuc     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5080*0a6a1f1dSLionel Sambuc     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5081*0a6a1f1dSLionel Sambuc     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5082*0a6a1f1dSLionel Sambuc     Preamble += "#define __attribute__(X)\n";
5083*0a6a1f1dSLionel Sambuc     Preamble += "#endif\n";
5084*0a6a1f1dSLionel Sambuc     Preamble += "#define __weak\n";
5085*0a6a1f1dSLionel Sambuc   }
5086*0a6a1f1dSLionel Sambuc   else {
5087*0a6a1f1dSLionel Sambuc     Preamble += "#define __block\n";
5088*0a6a1f1dSLionel Sambuc     Preamble += "#define __weak\n";
5089*0a6a1f1dSLionel Sambuc   }
5090*0a6a1f1dSLionel Sambuc   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5091*0a6a1f1dSLionel Sambuc   // as this avoids warning in any 64bit/32bit compilation model.
5092*0a6a1f1dSLionel Sambuc   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5093*0a6a1f1dSLionel Sambuc }
5094*0a6a1f1dSLionel Sambuc 
5095*0a6a1f1dSLionel Sambuc /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5096*0a6a1f1dSLionel Sambuc /// ivar offset.
RewriteIvarOffsetComputation(ObjCIvarDecl * ivar,std::string & Result)5097*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5098*0a6a1f1dSLionel Sambuc                                                          std::string &Result) {
5099*0a6a1f1dSLionel Sambuc   if (ivar->isBitField()) {
5100*0a6a1f1dSLionel Sambuc     // FIXME: The hack below doesn't work for bitfields. For now, we simply
5101*0a6a1f1dSLionel Sambuc     // place all bitfields at offset 0.
5102*0a6a1f1dSLionel Sambuc     Result += "0";
5103*0a6a1f1dSLionel Sambuc   } else {
5104*0a6a1f1dSLionel Sambuc     Result += "__OFFSETOFIVAR__(struct ";
5105*0a6a1f1dSLionel Sambuc     Result += ivar->getContainingInterface()->getNameAsString();
5106*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
5107*0a6a1f1dSLionel Sambuc       Result += "_IMPL";
5108*0a6a1f1dSLionel Sambuc     Result += ", ";
5109*0a6a1f1dSLionel Sambuc     Result += ivar->getNameAsString();
5110*0a6a1f1dSLionel Sambuc     Result += ")";
5111*0a6a1f1dSLionel Sambuc   }
5112*0a6a1f1dSLionel Sambuc }
5113*0a6a1f1dSLionel Sambuc 
5114*0a6a1f1dSLionel Sambuc /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
RewriteObjCProtocolMetaData(ObjCProtocolDecl * PDecl,StringRef prefix,StringRef ClassName,std::string & Result)5115*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5116*0a6a1f1dSLionel Sambuc                             ObjCProtocolDecl *PDecl, StringRef prefix,
5117*0a6a1f1dSLionel Sambuc                             StringRef ClassName, std::string &Result) {
5118*0a6a1f1dSLionel Sambuc   static bool objc_protocol_methods = false;
5119*0a6a1f1dSLionel Sambuc 
5120*0a6a1f1dSLionel Sambuc   // Output struct protocol_methods holder of method selector and type.
5121*0a6a1f1dSLionel Sambuc   if (!objc_protocol_methods && PDecl->hasDefinition()) {
5122*0a6a1f1dSLionel Sambuc     /* struct protocol_methods {
5123*0a6a1f1dSLionel Sambuc      SEL _cmd;
5124*0a6a1f1dSLionel Sambuc      char *method_types;
5125*0a6a1f1dSLionel Sambuc      }
5126*0a6a1f1dSLionel Sambuc      */
5127*0a6a1f1dSLionel Sambuc     Result += "\nstruct _protocol_methods {\n";
5128*0a6a1f1dSLionel Sambuc     Result += "\tstruct objc_selector *_cmd;\n";
5129*0a6a1f1dSLionel Sambuc     Result += "\tchar *method_types;\n";
5130*0a6a1f1dSLionel Sambuc     Result += "};\n";
5131*0a6a1f1dSLionel Sambuc 
5132*0a6a1f1dSLionel Sambuc     objc_protocol_methods = true;
5133*0a6a1f1dSLionel Sambuc   }
5134*0a6a1f1dSLionel Sambuc   // Do not synthesize the protocol more than once.
5135*0a6a1f1dSLionel Sambuc   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5136*0a6a1f1dSLionel Sambuc     return;
5137*0a6a1f1dSLionel Sambuc 
5138*0a6a1f1dSLionel Sambuc   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5139*0a6a1f1dSLionel Sambuc     PDecl = Def;
5140*0a6a1f1dSLionel Sambuc 
5141*0a6a1f1dSLionel Sambuc   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5142*0a6a1f1dSLionel Sambuc     unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5143*0a6a1f1dSLionel Sambuc                                         PDecl->instmeth_end());
5144*0a6a1f1dSLionel Sambuc     /* struct _objc_protocol_method_list {
5145*0a6a1f1dSLionel Sambuc      int protocol_method_count;
5146*0a6a1f1dSLionel Sambuc      struct protocol_methods protocols[];
5147*0a6a1f1dSLionel Sambuc      }
5148*0a6a1f1dSLionel Sambuc      */
5149*0a6a1f1dSLionel Sambuc     Result += "\nstatic struct {\n";
5150*0a6a1f1dSLionel Sambuc     Result += "\tint protocol_method_count;\n";
5151*0a6a1f1dSLionel Sambuc     Result += "\tstruct _protocol_methods protocol_methods[";
5152*0a6a1f1dSLionel Sambuc     Result += utostr(NumMethods);
5153*0a6a1f1dSLionel Sambuc     Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5154*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString();
5155*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5156*0a6a1f1dSLionel Sambuc     "{\n\t" + utostr(NumMethods) + "\n";
5157*0a6a1f1dSLionel Sambuc 
5158*0a6a1f1dSLionel Sambuc     // Output instance methods declared in this protocol.
5159*0a6a1f1dSLionel Sambuc     for (ObjCProtocolDecl::instmeth_iterator
5160*0a6a1f1dSLionel Sambuc          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5161*0a6a1f1dSLionel Sambuc          I != E; ++I) {
5162*0a6a1f1dSLionel Sambuc       if (I == PDecl->instmeth_begin())
5163*0a6a1f1dSLionel Sambuc         Result += "\t  ,{{(struct objc_selector *)\"";
5164*0a6a1f1dSLionel Sambuc       else
5165*0a6a1f1dSLionel Sambuc         Result += "\t  ,{(struct objc_selector *)\"";
5166*0a6a1f1dSLionel Sambuc       Result += (*I)->getSelector().getAsString();
5167*0a6a1f1dSLionel Sambuc       std::string MethodTypeString;
5168*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5169*0a6a1f1dSLionel Sambuc       Result += "\", \"";
5170*0a6a1f1dSLionel Sambuc       Result += MethodTypeString;
5171*0a6a1f1dSLionel Sambuc       Result += "\"}\n";
5172*0a6a1f1dSLionel Sambuc     }
5173*0a6a1f1dSLionel Sambuc     Result += "\t }\n};\n";
5174*0a6a1f1dSLionel Sambuc   }
5175*0a6a1f1dSLionel Sambuc 
5176*0a6a1f1dSLionel Sambuc   // Output class methods declared in this protocol.
5177*0a6a1f1dSLionel Sambuc   unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5178*0a6a1f1dSLionel Sambuc                                       PDecl->classmeth_end());
5179*0a6a1f1dSLionel Sambuc   if (NumMethods > 0) {
5180*0a6a1f1dSLionel Sambuc     /* struct _objc_protocol_method_list {
5181*0a6a1f1dSLionel Sambuc      int protocol_method_count;
5182*0a6a1f1dSLionel Sambuc      struct protocol_methods protocols[];
5183*0a6a1f1dSLionel Sambuc      }
5184*0a6a1f1dSLionel Sambuc      */
5185*0a6a1f1dSLionel Sambuc     Result += "\nstatic struct {\n";
5186*0a6a1f1dSLionel Sambuc     Result += "\tint protocol_method_count;\n";
5187*0a6a1f1dSLionel Sambuc     Result += "\tstruct _protocol_methods protocol_methods[";
5188*0a6a1f1dSLionel Sambuc     Result += utostr(NumMethods);
5189*0a6a1f1dSLionel Sambuc     Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5190*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString();
5191*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5192*0a6a1f1dSLionel Sambuc     "{\n\t";
5193*0a6a1f1dSLionel Sambuc     Result += utostr(NumMethods);
5194*0a6a1f1dSLionel Sambuc     Result += "\n";
5195*0a6a1f1dSLionel Sambuc 
5196*0a6a1f1dSLionel Sambuc     // Output instance methods declared in this protocol.
5197*0a6a1f1dSLionel Sambuc     for (ObjCProtocolDecl::classmeth_iterator
5198*0a6a1f1dSLionel Sambuc          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5199*0a6a1f1dSLionel Sambuc          I != E; ++I) {
5200*0a6a1f1dSLionel Sambuc       if (I == PDecl->classmeth_begin())
5201*0a6a1f1dSLionel Sambuc         Result += "\t  ,{{(struct objc_selector *)\"";
5202*0a6a1f1dSLionel Sambuc       else
5203*0a6a1f1dSLionel Sambuc         Result += "\t  ,{(struct objc_selector *)\"";
5204*0a6a1f1dSLionel Sambuc       Result += (*I)->getSelector().getAsString();
5205*0a6a1f1dSLionel Sambuc       std::string MethodTypeString;
5206*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5207*0a6a1f1dSLionel Sambuc       Result += "\", \"";
5208*0a6a1f1dSLionel Sambuc       Result += MethodTypeString;
5209*0a6a1f1dSLionel Sambuc       Result += "\"}\n";
5210*0a6a1f1dSLionel Sambuc     }
5211*0a6a1f1dSLionel Sambuc     Result += "\t }\n};\n";
5212*0a6a1f1dSLionel Sambuc   }
5213*0a6a1f1dSLionel Sambuc 
5214*0a6a1f1dSLionel Sambuc   // Output:
5215*0a6a1f1dSLionel Sambuc   /* struct _objc_protocol {
5216*0a6a1f1dSLionel Sambuc    // Objective-C 1.0 extensions
5217*0a6a1f1dSLionel Sambuc    struct _objc_protocol_extension *isa;
5218*0a6a1f1dSLionel Sambuc    char *protocol_name;
5219*0a6a1f1dSLionel Sambuc    struct _objc_protocol **protocol_list;
5220*0a6a1f1dSLionel Sambuc    struct _objc_protocol_method_list *instance_methods;
5221*0a6a1f1dSLionel Sambuc    struct _objc_protocol_method_list *class_methods;
5222*0a6a1f1dSLionel Sambuc    };
5223*0a6a1f1dSLionel Sambuc    */
5224*0a6a1f1dSLionel Sambuc   static bool objc_protocol = false;
5225*0a6a1f1dSLionel Sambuc   if (!objc_protocol) {
5226*0a6a1f1dSLionel Sambuc     Result += "\nstruct _objc_protocol {\n";
5227*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol_extension *isa;\n";
5228*0a6a1f1dSLionel Sambuc     Result += "\tchar *protocol_name;\n";
5229*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol **protocol_list;\n";
5230*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5231*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5232*0a6a1f1dSLionel Sambuc     Result += "};\n";
5233*0a6a1f1dSLionel Sambuc 
5234*0a6a1f1dSLionel Sambuc     objc_protocol = true;
5235*0a6a1f1dSLionel Sambuc   }
5236*0a6a1f1dSLionel Sambuc 
5237*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5238*0a6a1f1dSLionel Sambuc   Result += PDecl->getNameAsString();
5239*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5240*0a6a1f1dSLionel Sambuc   "{\n\t0, \"";
5241*0a6a1f1dSLionel Sambuc   Result += PDecl->getNameAsString();
5242*0a6a1f1dSLionel Sambuc   Result += "\", 0, ";
5243*0a6a1f1dSLionel Sambuc   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5244*0a6a1f1dSLionel Sambuc     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5245*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString();
5246*0a6a1f1dSLionel Sambuc     Result += ", ";
5247*0a6a1f1dSLionel Sambuc   }
5248*0a6a1f1dSLionel Sambuc   else
5249*0a6a1f1dSLionel Sambuc     Result += "0, ";
5250*0a6a1f1dSLionel Sambuc   if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5251*0a6a1f1dSLionel Sambuc     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5252*0a6a1f1dSLionel Sambuc     Result += PDecl->getNameAsString();
5253*0a6a1f1dSLionel Sambuc     Result += "\n";
5254*0a6a1f1dSLionel Sambuc   }
5255*0a6a1f1dSLionel Sambuc   else
5256*0a6a1f1dSLionel Sambuc     Result += "0\n";
5257*0a6a1f1dSLionel Sambuc   Result += "};\n";
5258*0a6a1f1dSLionel Sambuc 
5259*0a6a1f1dSLionel Sambuc   // Mark this protocol as having been generated.
5260*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5261*0a6a1f1dSLionel Sambuc     llvm_unreachable("protocol already synthesized");
5262*0a6a1f1dSLionel Sambuc 
5263*0a6a1f1dSLionel Sambuc }
5264*0a6a1f1dSLionel Sambuc 
RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> & Protocols,StringRef prefix,StringRef ClassName,std::string & Result)5265*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5266*0a6a1f1dSLionel Sambuc                                 const ObjCList<ObjCProtocolDecl> &Protocols,
5267*0a6a1f1dSLionel Sambuc                                 StringRef prefix, StringRef ClassName,
5268*0a6a1f1dSLionel Sambuc                                 std::string &Result) {
5269*0a6a1f1dSLionel Sambuc   if (Protocols.empty()) return;
5270*0a6a1f1dSLionel Sambuc 
5271*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; i != Protocols.size(); i++)
5272*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5273*0a6a1f1dSLionel Sambuc 
5274*0a6a1f1dSLionel Sambuc   // Output the top lovel protocol meta-data for the class.
5275*0a6a1f1dSLionel Sambuc   /* struct _objc_protocol_list {
5276*0a6a1f1dSLionel Sambuc    struct _objc_protocol_list *next;
5277*0a6a1f1dSLionel Sambuc    int    protocol_count;
5278*0a6a1f1dSLionel Sambuc    struct _objc_protocol *class_protocols[];
5279*0a6a1f1dSLionel Sambuc    }
5280*0a6a1f1dSLionel Sambuc    */
5281*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct {\n";
5282*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_protocol_list *next;\n";
5283*0a6a1f1dSLionel Sambuc   Result += "\tint    protocol_count;\n";
5284*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_protocol *class_protocols[";
5285*0a6a1f1dSLionel Sambuc   Result += utostr(Protocols.size());
5286*0a6a1f1dSLionel Sambuc   Result += "];\n} _OBJC_";
5287*0a6a1f1dSLionel Sambuc   Result += prefix;
5288*0a6a1f1dSLionel Sambuc   Result += "_PROTOCOLS_";
5289*0a6a1f1dSLionel Sambuc   Result += ClassName;
5290*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5291*0a6a1f1dSLionel Sambuc   "{\n\t0, ";
5292*0a6a1f1dSLionel Sambuc   Result += utostr(Protocols.size());
5293*0a6a1f1dSLionel Sambuc   Result += "\n";
5294*0a6a1f1dSLionel Sambuc 
5295*0a6a1f1dSLionel Sambuc   Result += "\t,{&_OBJC_PROTOCOL_";
5296*0a6a1f1dSLionel Sambuc   Result += Protocols[0]->getNameAsString();
5297*0a6a1f1dSLionel Sambuc   Result += " \n";
5298*0a6a1f1dSLionel Sambuc 
5299*0a6a1f1dSLionel Sambuc   for (unsigned i = 1; i != Protocols.size(); i++) {
5300*0a6a1f1dSLionel Sambuc     Result += "\t ,&_OBJC_PROTOCOL_";
5301*0a6a1f1dSLionel Sambuc     Result += Protocols[i]->getNameAsString();
5302*0a6a1f1dSLionel Sambuc     Result += "\n";
5303*0a6a1f1dSLionel Sambuc   }
5304*0a6a1f1dSLionel Sambuc   Result += "\t }\n};\n";
5305*0a6a1f1dSLionel Sambuc }
5306*0a6a1f1dSLionel Sambuc 
RewriteObjCClassMetaData(ObjCImplementationDecl * IDecl,std::string & Result)5307*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5308*0a6a1f1dSLionel Sambuc                                            std::string &Result) {
5309*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5310*0a6a1f1dSLionel Sambuc 
5311*0a6a1f1dSLionel Sambuc   // Explicitly declared @interface's are already synthesized.
5312*0a6a1f1dSLionel Sambuc   if (CDecl->isImplicitInterfaceDecl()) {
5313*0a6a1f1dSLionel Sambuc     // FIXME: Implementation of a class with no @interface (legacy) does not
5314*0a6a1f1dSLionel Sambuc     // produce correct synthesis as yet.
5315*0a6a1f1dSLionel Sambuc     RewriteObjCInternalStruct(CDecl, Result);
5316*0a6a1f1dSLionel Sambuc   }
5317*0a6a1f1dSLionel Sambuc 
5318*0a6a1f1dSLionel Sambuc   // Build _objc_ivar_list metadata for classes ivars if needed
5319*0a6a1f1dSLionel Sambuc   unsigned NumIvars = !IDecl->ivar_empty()
5320*0a6a1f1dSLionel Sambuc   ? IDecl->ivar_size()
5321*0a6a1f1dSLionel Sambuc   : (CDecl ? CDecl->ivar_size() : 0);
5322*0a6a1f1dSLionel Sambuc   if (NumIvars > 0) {
5323*0a6a1f1dSLionel Sambuc     static bool objc_ivar = false;
5324*0a6a1f1dSLionel Sambuc     if (!objc_ivar) {
5325*0a6a1f1dSLionel Sambuc       /* struct _objc_ivar {
5326*0a6a1f1dSLionel Sambuc        char *ivar_name;
5327*0a6a1f1dSLionel Sambuc        char *ivar_type;
5328*0a6a1f1dSLionel Sambuc        int ivar_offset;
5329*0a6a1f1dSLionel Sambuc        };
5330*0a6a1f1dSLionel Sambuc        */
5331*0a6a1f1dSLionel Sambuc       Result += "\nstruct _objc_ivar {\n";
5332*0a6a1f1dSLionel Sambuc       Result += "\tchar *ivar_name;\n";
5333*0a6a1f1dSLionel Sambuc       Result += "\tchar *ivar_type;\n";
5334*0a6a1f1dSLionel Sambuc       Result += "\tint ivar_offset;\n";
5335*0a6a1f1dSLionel Sambuc       Result += "};\n";
5336*0a6a1f1dSLionel Sambuc 
5337*0a6a1f1dSLionel Sambuc       objc_ivar = true;
5338*0a6a1f1dSLionel Sambuc     }
5339*0a6a1f1dSLionel Sambuc 
5340*0a6a1f1dSLionel Sambuc     /* struct {
5341*0a6a1f1dSLionel Sambuc      int ivar_count;
5342*0a6a1f1dSLionel Sambuc      struct _objc_ivar ivar_list[nIvars];
5343*0a6a1f1dSLionel Sambuc      };
5344*0a6a1f1dSLionel Sambuc      */
5345*0a6a1f1dSLionel Sambuc     Result += "\nstatic struct {\n";
5346*0a6a1f1dSLionel Sambuc     Result += "\tint ivar_count;\n";
5347*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_ivar ivar_list[";
5348*0a6a1f1dSLionel Sambuc     Result += utostr(NumIvars);
5349*0a6a1f1dSLionel Sambuc     Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5350*0a6a1f1dSLionel Sambuc     Result += IDecl->getNameAsString();
5351*0a6a1f1dSLionel Sambuc     Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5352*0a6a1f1dSLionel Sambuc     "{\n\t";
5353*0a6a1f1dSLionel Sambuc     Result += utostr(NumIvars);
5354*0a6a1f1dSLionel Sambuc     Result += "\n";
5355*0a6a1f1dSLionel Sambuc 
5356*0a6a1f1dSLionel Sambuc     ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5357*0a6a1f1dSLionel Sambuc     SmallVector<ObjCIvarDecl *, 8> IVars;
5358*0a6a1f1dSLionel Sambuc     if (!IDecl->ivar_empty()) {
5359*0a6a1f1dSLionel Sambuc       for (auto *IV : IDecl->ivars())
5360*0a6a1f1dSLionel Sambuc         IVars.push_back(IV);
5361*0a6a1f1dSLionel Sambuc       IVI = IDecl->ivar_begin();
5362*0a6a1f1dSLionel Sambuc       IVE = IDecl->ivar_end();
5363*0a6a1f1dSLionel Sambuc     } else {
5364*0a6a1f1dSLionel Sambuc       IVI = CDecl->ivar_begin();
5365*0a6a1f1dSLionel Sambuc       IVE = CDecl->ivar_end();
5366*0a6a1f1dSLionel Sambuc     }
5367*0a6a1f1dSLionel Sambuc     Result += "\t,{{\"";
5368*0a6a1f1dSLionel Sambuc     Result += IVI->getNameAsString();
5369*0a6a1f1dSLionel Sambuc     Result += "\", \"";
5370*0a6a1f1dSLionel Sambuc     std::string TmpString, StrEncoding;
5371*0a6a1f1dSLionel Sambuc     Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5372*0a6a1f1dSLionel Sambuc     QuoteDoublequotes(TmpString, StrEncoding);
5373*0a6a1f1dSLionel Sambuc     Result += StrEncoding;
5374*0a6a1f1dSLionel Sambuc     Result += "\", ";
5375*0a6a1f1dSLionel Sambuc     RewriteIvarOffsetComputation(*IVI, Result);
5376*0a6a1f1dSLionel Sambuc     Result += "}\n";
5377*0a6a1f1dSLionel Sambuc     for (++IVI; IVI != IVE; ++IVI) {
5378*0a6a1f1dSLionel Sambuc       Result += "\t  ,{\"";
5379*0a6a1f1dSLionel Sambuc       Result += IVI->getNameAsString();
5380*0a6a1f1dSLionel Sambuc       Result += "\", \"";
5381*0a6a1f1dSLionel Sambuc       std::string TmpString, StrEncoding;
5382*0a6a1f1dSLionel Sambuc       Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5383*0a6a1f1dSLionel Sambuc       QuoteDoublequotes(TmpString, StrEncoding);
5384*0a6a1f1dSLionel Sambuc       Result += StrEncoding;
5385*0a6a1f1dSLionel Sambuc       Result += "\", ";
5386*0a6a1f1dSLionel Sambuc       RewriteIvarOffsetComputation(*IVI, Result);
5387*0a6a1f1dSLionel Sambuc       Result += "}\n";
5388*0a6a1f1dSLionel Sambuc     }
5389*0a6a1f1dSLionel Sambuc 
5390*0a6a1f1dSLionel Sambuc     Result += "\t }\n};\n";
5391*0a6a1f1dSLionel Sambuc   }
5392*0a6a1f1dSLionel Sambuc 
5393*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's instance methods if needed
5394*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5395*0a6a1f1dSLionel Sambuc 
5396*0a6a1f1dSLionel Sambuc   // If any of our property implementations have associated getters or
5397*0a6a1f1dSLionel Sambuc   // setters, produce metadata for them as well.
5398*0a6a1f1dSLionel Sambuc   for (const auto *Prop : IDecl->property_impls()) {
5399*0a6a1f1dSLionel Sambuc     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5400*0a6a1f1dSLionel Sambuc       continue;
5401*0a6a1f1dSLionel Sambuc     if (!Prop->getPropertyIvarDecl())
5402*0a6a1f1dSLionel Sambuc       continue;
5403*0a6a1f1dSLionel Sambuc     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5404*0a6a1f1dSLionel Sambuc     if (!PD)
5405*0a6a1f1dSLionel Sambuc       continue;
5406*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5407*0a6a1f1dSLionel Sambuc       if (!Getter->isDefined())
5408*0a6a1f1dSLionel Sambuc         InstanceMethods.push_back(Getter);
5409*0a6a1f1dSLionel Sambuc     if (PD->isReadOnly())
5410*0a6a1f1dSLionel Sambuc       continue;
5411*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5412*0a6a1f1dSLionel Sambuc       if (!Setter->isDefined())
5413*0a6a1f1dSLionel Sambuc         InstanceMethods.push_back(Setter);
5414*0a6a1f1dSLionel Sambuc   }
5415*0a6a1f1dSLionel Sambuc   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5416*0a6a1f1dSLionel Sambuc                              true, "", IDecl->getName(), Result);
5417*0a6a1f1dSLionel Sambuc 
5418*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's class methods if needed
5419*0a6a1f1dSLionel Sambuc   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5420*0a6a1f1dSLionel Sambuc                              false, "", IDecl->getName(), Result);
5421*0a6a1f1dSLionel Sambuc 
5422*0a6a1f1dSLionel Sambuc   // Protocols referenced in class declaration?
5423*0a6a1f1dSLionel Sambuc   RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5424*0a6a1f1dSLionel Sambuc                                   "CLASS", CDecl->getName(), Result);
5425*0a6a1f1dSLionel Sambuc 
5426*0a6a1f1dSLionel Sambuc   // Declaration of class/meta-class metadata
5427*0a6a1f1dSLionel Sambuc   /* struct _objc_class {
5428*0a6a1f1dSLionel Sambuc    struct _objc_class *isa; // or const char *root_class_name when metadata
5429*0a6a1f1dSLionel Sambuc    const char *super_class_name;
5430*0a6a1f1dSLionel Sambuc    char *name;
5431*0a6a1f1dSLionel Sambuc    long version;
5432*0a6a1f1dSLionel Sambuc    long info;
5433*0a6a1f1dSLionel Sambuc    long instance_size;
5434*0a6a1f1dSLionel Sambuc    struct _objc_ivar_list *ivars;
5435*0a6a1f1dSLionel Sambuc    struct _objc_method_list *methods;
5436*0a6a1f1dSLionel Sambuc    struct objc_cache *cache;
5437*0a6a1f1dSLionel Sambuc    struct objc_protocol_list *protocols;
5438*0a6a1f1dSLionel Sambuc    const char *ivar_layout;
5439*0a6a1f1dSLionel Sambuc    struct _objc_class_ext  *ext;
5440*0a6a1f1dSLionel Sambuc    };
5441*0a6a1f1dSLionel Sambuc    */
5442*0a6a1f1dSLionel Sambuc   static bool objc_class = false;
5443*0a6a1f1dSLionel Sambuc   if (!objc_class) {
5444*0a6a1f1dSLionel Sambuc     Result += "\nstruct _objc_class {\n";
5445*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_class *isa;\n";
5446*0a6a1f1dSLionel Sambuc     Result += "\tconst char *super_class_name;\n";
5447*0a6a1f1dSLionel Sambuc     Result += "\tchar *name;\n";
5448*0a6a1f1dSLionel Sambuc     Result += "\tlong version;\n";
5449*0a6a1f1dSLionel Sambuc     Result += "\tlong info;\n";
5450*0a6a1f1dSLionel Sambuc     Result += "\tlong instance_size;\n";
5451*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_ivar_list *ivars;\n";
5452*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_method_list *methods;\n";
5453*0a6a1f1dSLionel Sambuc     Result += "\tstruct objc_cache *cache;\n";
5454*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol_list *protocols;\n";
5455*0a6a1f1dSLionel Sambuc     Result += "\tconst char *ivar_layout;\n";
5456*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_class_ext  *ext;\n";
5457*0a6a1f1dSLionel Sambuc     Result += "};\n";
5458*0a6a1f1dSLionel Sambuc     objc_class = true;
5459*0a6a1f1dSLionel Sambuc   }
5460*0a6a1f1dSLionel Sambuc 
5461*0a6a1f1dSLionel Sambuc   // Meta-class metadata generation.
5462*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *RootClass = nullptr;
5463*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5464*0a6a1f1dSLionel Sambuc   while (SuperClass) {
5465*0a6a1f1dSLionel Sambuc     RootClass = SuperClass;
5466*0a6a1f1dSLionel Sambuc     SuperClass = SuperClass->getSuperClass();
5467*0a6a1f1dSLionel Sambuc   }
5468*0a6a1f1dSLionel Sambuc   SuperClass = CDecl->getSuperClass();
5469*0a6a1f1dSLionel Sambuc 
5470*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5471*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
5472*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5473*0a6a1f1dSLionel Sambuc   "{\n\t(struct _objc_class *)\"";
5474*0a6a1f1dSLionel Sambuc   Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5475*0a6a1f1dSLionel Sambuc   Result += "\"";
5476*0a6a1f1dSLionel Sambuc 
5477*0a6a1f1dSLionel Sambuc   if (SuperClass) {
5478*0a6a1f1dSLionel Sambuc     Result += ", \"";
5479*0a6a1f1dSLionel Sambuc     Result += SuperClass->getNameAsString();
5480*0a6a1f1dSLionel Sambuc     Result += "\", \"";
5481*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5482*0a6a1f1dSLionel Sambuc     Result += "\"";
5483*0a6a1f1dSLionel Sambuc   }
5484*0a6a1f1dSLionel Sambuc   else {
5485*0a6a1f1dSLionel Sambuc     Result += ", 0, \"";
5486*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5487*0a6a1f1dSLionel Sambuc     Result += "\"";
5488*0a6a1f1dSLionel Sambuc   }
5489*0a6a1f1dSLionel Sambuc   // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5490*0a6a1f1dSLionel Sambuc   // 'info' field is initialized to CLS_META(2) for metaclass
5491*0a6a1f1dSLionel Sambuc   Result += ", 0,2, sizeof(struct _objc_class), 0";
5492*0a6a1f1dSLionel Sambuc   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5493*0a6a1f1dSLionel Sambuc     Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5494*0a6a1f1dSLionel Sambuc     Result += IDecl->getNameAsString();
5495*0a6a1f1dSLionel Sambuc     Result += "\n";
5496*0a6a1f1dSLionel Sambuc   }
5497*0a6a1f1dSLionel Sambuc   else
5498*0a6a1f1dSLionel Sambuc     Result += ", 0\n";
5499*0a6a1f1dSLionel Sambuc   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5500*0a6a1f1dSLionel Sambuc     Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5501*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5502*0a6a1f1dSLionel Sambuc     Result += ",0,0\n";
5503*0a6a1f1dSLionel Sambuc   }
5504*0a6a1f1dSLionel Sambuc   else
5505*0a6a1f1dSLionel Sambuc     Result += "\t,0,0,0,0\n";
5506*0a6a1f1dSLionel Sambuc   Result += "};\n";
5507*0a6a1f1dSLionel Sambuc 
5508*0a6a1f1dSLionel Sambuc   // class metadata generation.
5509*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5510*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
5511*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5512*0a6a1f1dSLionel Sambuc   "{\n\t&_OBJC_METACLASS_";
5513*0a6a1f1dSLionel Sambuc   Result += CDecl->getNameAsString();
5514*0a6a1f1dSLionel Sambuc   if (SuperClass) {
5515*0a6a1f1dSLionel Sambuc     Result += ", \"";
5516*0a6a1f1dSLionel Sambuc     Result += SuperClass->getNameAsString();
5517*0a6a1f1dSLionel Sambuc     Result += "\", \"";
5518*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5519*0a6a1f1dSLionel Sambuc     Result += "\"";
5520*0a6a1f1dSLionel Sambuc   }
5521*0a6a1f1dSLionel Sambuc   else {
5522*0a6a1f1dSLionel Sambuc     Result += ", 0, \"";
5523*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5524*0a6a1f1dSLionel Sambuc     Result += "\"";
5525*0a6a1f1dSLionel Sambuc   }
5526*0a6a1f1dSLionel Sambuc   // 'info' field is initialized to CLS_CLASS(1) for class
5527*0a6a1f1dSLionel Sambuc   Result += ", 0,1";
5528*0a6a1f1dSLionel Sambuc   if (!ObjCSynthesizedStructs.count(CDecl))
5529*0a6a1f1dSLionel Sambuc     Result += ",0";
5530*0a6a1f1dSLionel Sambuc   else {
5531*0a6a1f1dSLionel Sambuc     // class has size. Must synthesize its size.
5532*0a6a1f1dSLionel Sambuc     Result += ",sizeof(struct ";
5533*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5534*0a6a1f1dSLionel Sambuc     if (LangOpts.MicrosoftExt)
5535*0a6a1f1dSLionel Sambuc       Result += "_IMPL";
5536*0a6a1f1dSLionel Sambuc     Result += ")";
5537*0a6a1f1dSLionel Sambuc   }
5538*0a6a1f1dSLionel Sambuc   if (NumIvars > 0) {
5539*0a6a1f1dSLionel Sambuc     Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5540*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5541*0a6a1f1dSLionel Sambuc     Result += "\n\t";
5542*0a6a1f1dSLionel Sambuc   }
5543*0a6a1f1dSLionel Sambuc   else
5544*0a6a1f1dSLionel Sambuc     Result += ",0";
5545*0a6a1f1dSLionel Sambuc   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5546*0a6a1f1dSLionel Sambuc     Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5547*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5548*0a6a1f1dSLionel Sambuc     Result += ", 0\n\t";
5549*0a6a1f1dSLionel Sambuc   }
5550*0a6a1f1dSLionel Sambuc   else
5551*0a6a1f1dSLionel Sambuc     Result += ",0,0";
5552*0a6a1f1dSLionel Sambuc   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5553*0a6a1f1dSLionel Sambuc     Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5554*0a6a1f1dSLionel Sambuc     Result += CDecl->getNameAsString();
5555*0a6a1f1dSLionel Sambuc     Result += ", 0,0\n";
5556*0a6a1f1dSLionel Sambuc   }
5557*0a6a1f1dSLionel Sambuc   else
5558*0a6a1f1dSLionel Sambuc     Result += ",0,0,0\n";
5559*0a6a1f1dSLionel Sambuc   Result += "};\n";
5560*0a6a1f1dSLionel Sambuc }
5561*0a6a1f1dSLionel Sambuc 
RewriteMetaDataIntoBuffer(std::string & Result)5562*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5563*0a6a1f1dSLionel Sambuc   int ClsDefCount = ClassImplementation.size();
5564*0a6a1f1dSLionel Sambuc   int CatDefCount = CategoryImplementation.size();
5565*0a6a1f1dSLionel Sambuc 
5566*0a6a1f1dSLionel Sambuc   // For each implemented class, write out all its meta data.
5567*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++)
5568*0a6a1f1dSLionel Sambuc     RewriteObjCClassMetaData(ClassImplementation[i], Result);
5569*0a6a1f1dSLionel Sambuc 
5570*0a6a1f1dSLionel Sambuc   // For each implemented category, write out all its meta data.
5571*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++)
5572*0a6a1f1dSLionel Sambuc     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5573*0a6a1f1dSLionel Sambuc 
5574*0a6a1f1dSLionel Sambuc   // Write objc_symtab metadata
5575*0a6a1f1dSLionel Sambuc   /*
5576*0a6a1f1dSLionel Sambuc    struct _objc_symtab
5577*0a6a1f1dSLionel Sambuc    {
5578*0a6a1f1dSLionel Sambuc    long sel_ref_cnt;
5579*0a6a1f1dSLionel Sambuc    SEL *refs;
5580*0a6a1f1dSLionel Sambuc    short cls_def_cnt;
5581*0a6a1f1dSLionel Sambuc    short cat_def_cnt;
5582*0a6a1f1dSLionel Sambuc    void *defs[cls_def_cnt + cat_def_cnt];
5583*0a6a1f1dSLionel Sambuc    };
5584*0a6a1f1dSLionel Sambuc    */
5585*0a6a1f1dSLionel Sambuc 
5586*0a6a1f1dSLionel Sambuc   Result += "\nstruct _objc_symtab {\n";
5587*0a6a1f1dSLionel Sambuc   Result += "\tlong sel_ref_cnt;\n";
5588*0a6a1f1dSLionel Sambuc   Result += "\tSEL *refs;\n";
5589*0a6a1f1dSLionel Sambuc   Result += "\tshort cls_def_cnt;\n";
5590*0a6a1f1dSLionel Sambuc   Result += "\tshort cat_def_cnt;\n";
5591*0a6a1f1dSLionel Sambuc   Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5592*0a6a1f1dSLionel Sambuc   Result += "};\n\n";
5593*0a6a1f1dSLionel Sambuc 
5594*0a6a1f1dSLionel Sambuc   Result += "static struct _objc_symtab "
5595*0a6a1f1dSLionel Sambuc   "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5596*0a6a1f1dSLionel Sambuc   Result += "\t0, 0, " + utostr(ClsDefCount)
5597*0a6a1f1dSLionel Sambuc   + ", " + utostr(CatDefCount) + "\n";
5598*0a6a1f1dSLionel Sambuc   for (int i = 0; i < ClsDefCount; i++) {
5599*0a6a1f1dSLionel Sambuc     Result += "\t,&_OBJC_CLASS_";
5600*0a6a1f1dSLionel Sambuc     Result += ClassImplementation[i]->getNameAsString();
5601*0a6a1f1dSLionel Sambuc     Result += "\n";
5602*0a6a1f1dSLionel Sambuc   }
5603*0a6a1f1dSLionel Sambuc 
5604*0a6a1f1dSLionel Sambuc   for (int i = 0; i < CatDefCount; i++) {
5605*0a6a1f1dSLionel Sambuc     Result += "\t,&_OBJC_CATEGORY_";
5606*0a6a1f1dSLionel Sambuc     Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5607*0a6a1f1dSLionel Sambuc     Result += "_";
5608*0a6a1f1dSLionel Sambuc     Result += CategoryImplementation[i]->getNameAsString();
5609*0a6a1f1dSLionel Sambuc     Result += "\n";
5610*0a6a1f1dSLionel Sambuc   }
5611*0a6a1f1dSLionel Sambuc 
5612*0a6a1f1dSLionel Sambuc   Result += "};\n\n";
5613*0a6a1f1dSLionel Sambuc 
5614*0a6a1f1dSLionel Sambuc   // Write objc_module metadata
5615*0a6a1f1dSLionel Sambuc 
5616*0a6a1f1dSLionel Sambuc   /*
5617*0a6a1f1dSLionel Sambuc    struct _objc_module {
5618*0a6a1f1dSLionel Sambuc    long version;
5619*0a6a1f1dSLionel Sambuc    long size;
5620*0a6a1f1dSLionel Sambuc    const char *name;
5621*0a6a1f1dSLionel Sambuc    struct _objc_symtab *symtab;
5622*0a6a1f1dSLionel Sambuc    }
5623*0a6a1f1dSLionel Sambuc    */
5624*0a6a1f1dSLionel Sambuc 
5625*0a6a1f1dSLionel Sambuc   Result += "\nstruct _objc_module {\n";
5626*0a6a1f1dSLionel Sambuc   Result += "\tlong version;\n";
5627*0a6a1f1dSLionel Sambuc   Result += "\tlong size;\n";
5628*0a6a1f1dSLionel Sambuc   Result += "\tconst char *name;\n";
5629*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_symtab *symtab;\n";
5630*0a6a1f1dSLionel Sambuc   Result += "};\n\n";
5631*0a6a1f1dSLionel Sambuc   Result += "static struct _objc_module "
5632*0a6a1f1dSLionel Sambuc   "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5633*0a6a1f1dSLionel Sambuc   Result += "\t" + utostr(OBJC_ABI_VERSION) +
5634*0a6a1f1dSLionel Sambuc   ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5635*0a6a1f1dSLionel Sambuc   Result += "};\n\n";
5636*0a6a1f1dSLionel Sambuc 
5637*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
5638*0a6a1f1dSLionel Sambuc     if (ProtocolExprDecls.size()) {
5639*0a6a1f1dSLionel Sambuc       Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5640*0a6a1f1dSLionel Sambuc       Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5641*0a6a1f1dSLionel Sambuc       for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5642*0a6a1f1dSLionel Sambuc         Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5643*0a6a1f1dSLionel Sambuc         Result += ProtDecl->getNameAsString();
5644*0a6a1f1dSLionel Sambuc         Result += " = &_OBJC_PROTOCOL_";
5645*0a6a1f1dSLionel Sambuc         Result += ProtDecl->getNameAsString();
5646*0a6a1f1dSLionel Sambuc         Result += ";\n";
5647*0a6a1f1dSLionel Sambuc       }
5648*0a6a1f1dSLionel Sambuc       Result += "#pragma data_seg(pop)\n\n";
5649*0a6a1f1dSLionel Sambuc     }
5650*0a6a1f1dSLionel Sambuc     Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5651*0a6a1f1dSLionel Sambuc     Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5652*0a6a1f1dSLionel Sambuc     Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5653*0a6a1f1dSLionel Sambuc     Result += "&_OBJC_MODULES;\n";
5654*0a6a1f1dSLionel Sambuc     Result += "#pragma data_seg(pop)\n\n";
5655*0a6a1f1dSLionel Sambuc   }
5656*0a6a1f1dSLionel Sambuc }
5657*0a6a1f1dSLionel Sambuc 
5658*0a6a1f1dSLionel Sambuc /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5659*0a6a1f1dSLionel Sambuc /// implementation.
RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl * IDecl,std::string & Result)5660*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5661*0a6a1f1dSLionel Sambuc                                               std::string &Result) {
5662*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5663*0a6a1f1dSLionel Sambuc   // Find category declaration for this implementation.
5664*0a6a1f1dSLionel Sambuc   ObjCCategoryDecl *CDecl
5665*0a6a1f1dSLionel Sambuc     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5666*0a6a1f1dSLionel Sambuc 
5667*0a6a1f1dSLionel Sambuc   std::string FullCategoryName = ClassDecl->getNameAsString();
5668*0a6a1f1dSLionel Sambuc   FullCategoryName += '_';
5669*0a6a1f1dSLionel Sambuc   FullCategoryName += IDecl->getNameAsString();
5670*0a6a1f1dSLionel Sambuc 
5671*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's instance methods if needed
5672*0a6a1f1dSLionel Sambuc   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5673*0a6a1f1dSLionel Sambuc 
5674*0a6a1f1dSLionel Sambuc   // If any of our property implementations have associated getters or
5675*0a6a1f1dSLionel Sambuc   // setters, produce metadata for them as well.
5676*0a6a1f1dSLionel Sambuc   for (const auto *Prop : IDecl->property_impls()) {
5677*0a6a1f1dSLionel Sambuc     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5678*0a6a1f1dSLionel Sambuc       continue;
5679*0a6a1f1dSLionel Sambuc     if (!Prop->getPropertyIvarDecl())
5680*0a6a1f1dSLionel Sambuc       continue;
5681*0a6a1f1dSLionel Sambuc     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5682*0a6a1f1dSLionel Sambuc     if (!PD)
5683*0a6a1f1dSLionel Sambuc       continue;
5684*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5685*0a6a1f1dSLionel Sambuc       InstanceMethods.push_back(Getter);
5686*0a6a1f1dSLionel Sambuc     if (PD->isReadOnly())
5687*0a6a1f1dSLionel Sambuc       continue;
5688*0a6a1f1dSLionel Sambuc     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5689*0a6a1f1dSLionel Sambuc       InstanceMethods.push_back(Setter);
5690*0a6a1f1dSLionel Sambuc   }
5691*0a6a1f1dSLionel Sambuc   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5692*0a6a1f1dSLionel Sambuc                              true, "CATEGORY_", FullCategoryName.c_str(),
5693*0a6a1f1dSLionel Sambuc                              Result);
5694*0a6a1f1dSLionel Sambuc 
5695*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's class methods if needed
5696*0a6a1f1dSLionel Sambuc   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5697*0a6a1f1dSLionel Sambuc                              false, "CATEGORY_", FullCategoryName.c_str(),
5698*0a6a1f1dSLionel Sambuc                              Result);
5699*0a6a1f1dSLionel Sambuc 
5700*0a6a1f1dSLionel Sambuc   // Protocols referenced in class declaration?
5701*0a6a1f1dSLionel Sambuc   // Null CDecl is case of a category implementation with no category interface
5702*0a6a1f1dSLionel Sambuc   if (CDecl)
5703*0a6a1f1dSLionel Sambuc     RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5704*0a6a1f1dSLionel Sambuc                                     FullCategoryName, Result);
5705*0a6a1f1dSLionel Sambuc   /* struct _objc_category {
5706*0a6a1f1dSLionel Sambuc    char *category_name;
5707*0a6a1f1dSLionel Sambuc    char *class_name;
5708*0a6a1f1dSLionel Sambuc    struct _objc_method_list *instance_methods;
5709*0a6a1f1dSLionel Sambuc    struct _objc_method_list *class_methods;
5710*0a6a1f1dSLionel Sambuc    struct _objc_protocol_list *protocols;
5711*0a6a1f1dSLionel Sambuc    // Objective-C 1.0 extensions
5712*0a6a1f1dSLionel Sambuc    uint32_t size;     // sizeof (struct _objc_category)
5713*0a6a1f1dSLionel Sambuc    struct _objc_property_list *instance_properties;  // category's own
5714*0a6a1f1dSLionel Sambuc    // @property decl.
5715*0a6a1f1dSLionel Sambuc    };
5716*0a6a1f1dSLionel Sambuc    */
5717*0a6a1f1dSLionel Sambuc 
5718*0a6a1f1dSLionel Sambuc   static bool objc_category = false;
5719*0a6a1f1dSLionel Sambuc   if (!objc_category) {
5720*0a6a1f1dSLionel Sambuc     Result += "\nstruct _objc_category {\n";
5721*0a6a1f1dSLionel Sambuc     Result += "\tchar *category_name;\n";
5722*0a6a1f1dSLionel Sambuc     Result += "\tchar *class_name;\n";
5723*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_method_list *instance_methods;\n";
5724*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_method_list *class_methods;\n";
5725*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_protocol_list *protocols;\n";
5726*0a6a1f1dSLionel Sambuc     Result += "\tunsigned int size;\n";
5727*0a6a1f1dSLionel Sambuc     Result += "\tstruct _objc_property_list *instance_properties;\n";
5728*0a6a1f1dSLionel Sambuc     Result += "};\n";
5729*0a6a1f1dSLionel Sambuc     objc_category = true;
5730*0a6a1f1dSLionel Sambuc   }
5731*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5732*0a6a1f1dSLionel Sambuc   Result += FullCategoryName;
5733*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5734*0a6a1f1dSLionel Sambuc   Result += IDecl->getNameAsString();
5735*0a6a1f1dSLionel Sambuc   Result += "\"\n\t, \"";
5736*0a6a1f1dSLionel Sambuc   Result += ClassDecl->getNameAsString();
5737*0a6a1f1dSLionel Sambuc   Result += "\"\n";
5738*0a6a1f1dSLionel Sambuc 
5739*0a6a1f1dSLionel Sambuc   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5740*0a6a1f1dSLionel Sambuc     Result += "\t, (struct _objc_method_list *)"
5741*0a6a1f1dSLionel Sambuc     "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5742*0a6a1f1dSLionel Sambuc     Result += FullCategoryName;
5743*0a6a1f1dSLionel Sambuc     Result += "\n";
5744*0a6a1f1dSLionel Sambuc   }
5745*0a6a1f1dSLionel Sambuc   else
5746*0a6a1f1dSLionel Sambuc     Result += "\t, 0\n";
5747*0a6a1f1dSLionel Sambuc   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5748*0a6a1f1dSLionel Sambuc     Result += "\t, (struct _objc_method_list *)"
5749*0a6a1f1dSLionel Sambuc     "&_OBJC_CATEGORY_CLASS_METHODS_";
5750*0a6a1f1dSLionel Sambuc     Result += FullCategoryName;
5751*0a6a1f1dSLionel Sambuc     Result += "\n";
5752*0a6a1f1dSLionel Sambuc   }
5753*0a6a1f1dSLionel Sambuc   else
5754*0a6a1f1dSLionel Sambuc     Result += "\t, 0\n";
5755*0a6a1f1dSLionel Sambuc 
5756*0a6a1f1dSLionel Sambuc   if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5757*0a6a1f1dSLionel Sambuc     Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5758*0a6a1f1dSLionel Sambuc     Result += FullCategoryName;
5759*0a6a1f1dSLionel Sambuc     Result += "\n";
5760*0a6a1f1dSLionel Sambuc   }
5761*0a6a1f1dSLionel Sambuc   else
5762*0a6a1f1dSLionel Sambuc     Result += "\t, 0\n";
5763*0a6a1f1dSLionel Sambuc   Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5764*0a6a1f1dSLionel Sambuc }
5765*0a6a1f1dSLionel Sambuc 
5766*0a6a1f1dSLionel Sambuc // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5767*0a6a1f1dSLionel Sambuc /// class methods.
5768*0a6a1f1dSLionel Sambuc template<typename MethodIterator>
RewriteObjCMethodsMetaData(MethodIterator MethodBegin,MethodIterator MethodEnd,bool IsInstanceMethod,StringRef prefix,StringRef ClassName,std::string & Result)5769*0a6a1f1dSLionel Sambuc void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5770*0a6a1f1dSLionel Sambuc                                              MethodIterator MethodEnd,
5771*0a6a1f1dSLionel Sambuc                                              bool IsInstanceMethod,
5772*0a6a1f1dSLionel Sambuc                                              StringRef prefix,
5773*0a6a1f1dSLionel Sambuc                                              StringRef ClassName,
5774*0a6a1f1dSLionel Sambuc                                              std::string &Result) {
5775*0a6a1f1dSLionel Sambuc   if (MethodBegin == MethodEnd) return;
5776*0a6a1f1dSLionel Sambuc 
5777*0a6a1f1dSLionel Sambuc   if (!objc_impl_method) {
5778*0a6a1f1dSLionel Sambuc     /* struct _objc_method {
5779*0a6a1f1dSLionel Sambuc      SEL _cmd;
5780*0a6a1f1dSLionel Sambuc      char *method_types;
5781*0a6a1f1dSLionel Sambuc      void *_imp;
5782*0a6a1f1dSLionel Sambuc      }
5783*0a6a1f1dSLionel Sambuc      */
5784*0a6a1f1dSLionel Sambuc     Result += "\nstruct _objc_method {\n";
5785*0a6a1f1dSLionel Sambuc     Result += "\tSEL _cmd;\n";
5786*0a6a1f1dSLionel Sambuc     Result += "\tchar *method_types;\n";
5787*0a6a1f1dSLionel Sambuc     Result += "\tvoid *_imp;\n";
5788*0a6a1f1dSLionel Sambuc     Result += "};\n";
5789*0a6a1f1dSLionel Sambuc 
5790*0a6a1f1dSLionel Sambuc     objc_impl_method = true;
5791*0a6a1f1dSLionel Sambuc   }
5792*0a6a1f1dSLionel Sambuc 
5793*0a6a1f1dSLionel Sambuc   // Build _objc_method_list for class's methods if needed
5794*0a6a1f1dSLionel Sambuc 
5795*0a6a1f1dSLionel Sambuc   /* struct  {
5796*0a6a1f1dSLionel Sambuc    struct _objc_method_list *next_method;
5797*0a6a1f1dSLionel Sambuc    int method_count;
5798*0a6a1f1dSLionel Sambuc    struct _objc_method method_list[];
5799*0a6a1f1dSLionel Sambuc    }
5800*0a6a1f1dSLionel Sambuc    */
5801*0a6a1f1dSLionel Sambuc   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5802*0a6a1f1dSLionel Sambuc   Result += "\nstatic struct {\n";
5803*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_method_list *next_method;\n";
5804*0a6a1f1dSLionel Sambuc   Result += "\tint method_count;\n";
5805*0a6a1f1dSLionel Sambuc   Result += "\tstruct _objc_method method_list[";
5806*0a6a1f1dSLionel Sambuc   Result += utostr(NumMethods);
5807*0a6a1f1dSLionel Sambuc   Result += "];\n} _OBJC_";
5808*0a6a1f1dSLionel Sambuc   Result += prefix;
5809*0a6a1f1dSLionel Sambuc   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5810*0a6a1f1dSLionel Sambuc   Result += "_METHODS_";
5811*0a6a1f1dSLionel Sambuc   Result += ClassName;
5812*0a6a1f1dSLionel Sambuc   Result += " __attribute__ ((used, section (\"__OBJC, __";
5813*0a6a1f1dSLionel Sambuc   Result += IsInstanceMethod ? "inst" : "cls";
5814*0a6a1f1dSLionel Sambuc   Result += "_meth\")))= ";
5815*0a6a1f1dSLionel Sambuc   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5816*0a6a1f1dSLionel Sambuc 
5817*0a6a1f1dSLionel Sambuc   Result += "\t,{{(SEL)\"";
5818*0a6a1f1dSLionel Sambuc   Result += (*MethodBegin)->getSelector().getAsString().c_str();
5819*0a6a1f1dSLionel Sambuc   std::string MethodTypeString;
5820*0a6a1f1dSLionel Sambuc   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5821*0a6a1f1dSLionel Sambuc   Result += "\", \"";
5822*0a6a1f1dSLionel Sambuc   Result += MethodTypeString;
5823*0a6a1f1dSLionel Sambuc   Result += "\", (void *)";
5824*0a6a1f1dSLionel Sambuc   Result += MethodInternalNames[*MethodBegin];
5825*0a6a1f1dSLionel Sambuc   Result += "}\n";
5826*0a6a1f1dSLionel Sambuc   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5827*0a6a1f1dSLionel Sambuc     Result += "\t  ,{(SEL)\"";
5828*0a6a1f1dSLionel Sambuc     Result += (*MethodBegin)->getSelector().getAsString().c_str();
5829*0a6a1f1dSLionel Sambuc     std::string MethodTypeString;
5830*0a6a1f1dSLionel Sambuc     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5831*0a6a1f1dSLionel Sambuc     Result += "\", \"";
5832*0a6a1f1dSLionel Sambuc     Result += MethodTypeString;
5833*0a6a1f1dSLionel Sambuc     Result += "\", (void *)";
5834*0a6a1f1dSLionel Sambuc     Result += MethodInternalNames[*MethodBegin];
5835*0a6a1f1dSLionel Sambuc     Result += "}\n";
5836*0a6a1f1dSLionel Sambuc   }
5837*0a6a1f1dSLionel Sambuc   Result += "\t }\n};\n";
5838*0a6a1f1dSLionel Sambuc }
5839*0a6a1f1dSLionel Sambuc 
RewriteObjCIvarRefExpr(ObjCIvarRefExpr * IV)5840*0a6a1f1dSLionel Sambuc Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5841*0a6a1f1dSLionel Sambuc   SourceRange OldRange = IV->getSourceRange();
5842*0a6a1f1dSLionel Sambuc   Expr *BaseExpr = IV->getBase();
5843*0a6a1f1dSLionel Sambuc 
5844*0a6a1f1dSLionel Sambuc   // Rewrite the base, but without actually doing replaces.
5845*0a6a1f1dSLionel Sambuc   {
5846*0a6a1f1dSLionel Sambuc     DisableReplaceStmtScope S(*this);
5847*0a6a1f1dSLionel Sambuc     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5848*0a6a1f1dSLionel Sambuc     IV->setBase(BaseExpr);
5849*0a6a1f1dSLionel Sambuc   }
5850*0a6a1f1dSLionel Sambuc 
5851*0a6a1f1dSLionel Sambuc   ObjCIvarDecl *D = IV->getDecl();
5852*0a6a1f1dSLionel Sambuc 
5853*0a6a1f1dSLionel Sambuc   Expr *Replacement = IV;
5854*0a6a1f1dSLionel Sambuc   if (CurMethodDef) {
5855*0a6a1f1dSLionel Sambuc     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5856*0a6a1f1dSLionel Sambuc       const ObjCInterfaceType *iFaceDecl =
5857*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5858*0a6a1f1dSLionel Sambuc       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5859*0a6a1f1dSLionel Sambuc       // lookup which class implements the instance variable.
5860*0a6a1f1dSLionel Sambuc       ObjCInterfaceDecl *clsDeclared = nullptr;
5861*0a6a1f1dSLionel Sambuc       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5862*0a6a1f1dSLionel Sambuc                                                    clsDeclared);
5863*0a6a1f1dSLionel Sambuc       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5864*0a6a1f1dSLionel Sambuc 
5865*0a6a1f1dSLionel Sambuc       // Synthesize an explicit cast to gain access to the ivar.
5866*0a6a1f1dSLionel Sambuc       std::string RecName = clsDeclared->getIdentifier()->getName();
5867*0a6a1f1dSLionel Sambuc       RecName += "_IMPL";
5868*0a6a1f1dSLionel Sambuc       IdentifierInfo *II = &Context->Idents.get(RecName);
5869*0a6a1f1dSLionel Sambuc       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5870*0a6a1f1dSLionel Sambuc                                           SourceLocation(), SourceLocation(),
5871*0a6a1f1dSLionel Sambuc                                           II);
5872*0a6a1f1dSLionel Sambuc       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5873*0a6a1f1dSLionel Sambuc       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5874*0a6a1f1dSLionel Sambuc       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5875*0a6a1f1dSLionel Sambuc                                                     CK_BitCast,
5876*0a6a1f1dSLionel Sambuc                                                     IV->getBase());
5877*0a6a1f1dSLionel Sambuc       // Don't forget the parens to enforce the proper binding.
5878*0a6a1f1dSLionel Sambuc       ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5879*0a6a1f1dSLionel Sambuc                                               OldRange.getEnd(),
5880*0a6a1f1dSLionel Sambuc                                               castExpr);
5881*0a6a1f1dSLionel Sambuc       if (IV->isFreeIvar() &&
5882*0a6a1f1dSLionel Sambuc           declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5883*0a6a1f1dSLionel Sambuc         MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5884*0a6a1f1dSLionel Sambuc                                                   IV->getLocation(),
5885*0a6a1f1dSLionel Sambuc                                                   D->getType(),
5886*0a6a1f1dSLionel Sambuc                                                   VK_LValue, OK_Ordinary);
5887*0a6a1f1dSLionel Sambuc         Replacement = ME;
5888*0a6a1f1dSLionel Sambuc       } else {
5889*0a6a1f1dSLionel Sambuc         IV->setBase(PE);
5890*0a6a1f1dSLionel Sambuc       }
5891*0a6a1f1dSLionel Sambuc     }
5892*0a6a1f1dSLionel Sambuc   } else { // we are outside a method.
5893*0a6a1f1dSLionel Sambuc     assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5894*0a6a1f1dSLionel Sambuc 
5895*0a6a1f1dSLionel Sambuc     // Explicit ivar refs need to have a cast inserted.
5896*0a6a1f1dSLionel Sambuc     // FIXME: consider sharing some of this code with the code above.
5897*0a6a1f1dSLionel Sambuc     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5898*0a6a1f1dSLionel Sambuc       const ObjCInterfaceType *iFaceDecl =
5899*0a6a1f1dSLionel Sambuc       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5900*0a6a1f1dSLionel Sambuc       // lookup which class implements the instance variable.
5901*0a6a1f1dSLionel Sambuc       ObjCInterfaceDecl *clsDeclared = nullptr;
5902*0a6a1f1dSLionel Sambuc       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5903*0a6a1f1dSLionel Sambuc                                                    clsDeclared);
5904*0a6a1f1dSLionel Sambuc       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5905*0a6a1f1dSLionel Sambuc 
5906*0a6a1f1dSLionel Sambuc       // Synthesize an explicit cast to gain access to the ivar.
5907*0a6a1f1dSLionel Sambuc       std::string RecName = clsDeclared->getIdentifier()->getName();
5908*0a6a1f1dSLionel Sambuc       RecName += "_IMPL";
5909*0a6a1f1dSLionel Sambuc       IdentifierInfo *II = &Context->Idents.get(RecName);
5910*0a6a1f1dSLionel Sambuc       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5911*0a6a1f1dSLionel Sambuc                                           SourceLocation(), SourceLocation(),
5912*0a6a1f1dSLionel Sambuc                                           II);
5913*0a6a1f1dSLionel Sambuc       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5914*0a6a1f1dSLionel Sambuc       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5915*0a6a1f1dSLionel Sambuc       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5916*0a6a1f1dSLionel Sambuc                                                     CK_BitCast,
5917*0a6a1f1dSLionel Sambuc                                                     IV->getBase());
5918*0a6a1f1dSLionel Sambuc       // Don't forget the parens to enforce the proper binding.
5919*0a6a1f1dSLionel Sambuc       ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5920*0a6a1f1dSLionel Sambuc                                               IV->getBase()->getLocEnd(), castExpr);
5921*0a6a1f1dSLionel Sambuc       // Cannot delete IV->getBase(), since PE points to it.
5922*0a6a1f1dSLionel Sambuc       // Replace the old base with the cast. This is important when doing
5923*0a6a1f1dSLionel Sambuc       // embedded rewrites. For example, [newInv->_container addObject:0].
5924*0a6a1f1dSLionel Sambuc       IV->setBase(PE);
5925*0a6a1f1dSLionel Sambuc     }
5926*0a6a1f1dSLionel Sambuc   }
5927*0a6a1f1dSLionel Sambuc 
5928*0a6a1f1dSLionel Sambuc   ReplaceStmtWithRange(IV, Replacement, OldRange);
5929*0a6a1f1dSLionel Sambuc   return Replacement;
5930*0a6a1f1dSLionel Sambuc }
5931*0a6a1f1dSLionel Sambuc 
5932*0a6a1f1dSLionel Sambuc #endif
5933