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