1//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Hacks and fun related to the code rewriter.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Rewrite/Frontend/ASTConsumers.h"
14#include "clang/AST/AST.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/Basic/CharInfo.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Config/config.h"
24#include "clang/Lex/Lexer.h"
25#include "clang/Rewrite/Core/Rewriter.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
31#include <memory>
32
33#if CLANG_ENABLE_OBJC_REWRITER
34
35using namespace clang;
36using llvm::utostr;
37
38namespace {
39  class RewriteModernObjC : public ASTConsumer {
40  protected:
41
42    enum {
43      BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
44                                        block, ... */
45      BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
46      BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
47                                        __block variable */
48      BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
49                                        helpers */
50      BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
51                                        support routines */
52      BLOCK_BYREF_CURRENT_MAX = 256
53    };
54
55    enum {
56      BLOCK_NEEDS_FREE =        (1 << 24),
57      BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
58      BLOCK_HAS_CXX_OBJ =       (1 << 26),
59      BLOCK_IS_GC =             (1 << 27),
60      BLOCK_IS_GLOBAL =         (1 << 28),
61      BLOCK_HAS_DESCRIPTOR =    (1 << 29)
62    };
63
64    Rewriter Rewrite;
65    DiagnosticsEngine &Diags;
66    const LangOptions &LangOpts;
67    ASTContext *Context;
68    SourceManager *SM;
69    TranslationUnitDecl *TUDecl;
70    FileID MainFileID;
71    const char *MainFileStart, *MainFileEnd;
72    Stmt *CurrentBody;
73    ParentMap *PropParentMap; // created lazily.
74    std::string InFileName;
75    std::unique_ptr<raw_ostream> OutFile;
76    std::string Preamble;
77
78    TypeDecl *ProtocolTypeDecl;
79    VarDecl *GlobalVarDecl;
80    Expr *GlobalConstructionExp;
81    unsigned RewriteFailedDiag;
82    unsigned GlobalBlockRewriteFailedDiag;
83    // ObjC string constant support.
84    unsigned NumObjCStringLiterals;
85    VarDecl *ConstantStringClassReference;
86    RecordDecl *NSStringRecord;
87
88    // ObjC foreach break/continue generation support.
89    int BcLabelCount;
90
91    unsigned TryFinallyContainsReturnDiag;
92    // Needed for super.
93    ObjCMethodDecl *CurMethodDef;
94    RecordDecl *SuperStructDecl;
95    RecordDecl *ConstantStringDecl;
96
97    FunctionDecl *MsgSendFunctionDecl;
98    FunctionDecl *MsgSendSuperFunctionDecl;
99    FunctionDecl *MsgSendStretFunctionDecl;
100    FunctionDecl *MsgSendSuperStretFunctionDecl;
101    FunctionDecl *MsgSendFpretFunctionDecl;
102    FunctionDecl *GetClassFunctionDecl;
103    FunctionDecl *GetMetaClassFunctionDecl;
104    FunctionDecl *GetSuperClassFunctionDecl;
105    FunctionDecl *SelGetUidFunctionDecl;
106    FunctionDecl *CFStringFunctionDecl;
107    FunctionDecl *SuperConstructorFunctionDecl;
108    FunctionDecl *CurFunctionDef;
109
110    /* Misc. containers needed for meta-data rewrite. */
111    SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112    SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114    llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116    llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117    SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118    /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119    SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120
121    /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122    SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123
124    SmallVector<Stmt *, 32> Stmts;
125    SmallVector<int, 8> ObjCBcLabelNo;
126    // Remember all the @protocol(<expr>) expressions.
127    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128
129    llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131    // Block expressions.
132    SmallVector<BlockExpr *, 32> Blocks;
133    SmallVector<int, 32> InnerDeclRefsCount;
134    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135
136    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137
138    // Block related declarations.
139    SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141    SmallVector<ValueDecl *, 8> BlockByRefDecls;
142    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
148    llvm::DenseMap<ObjCInterfaceDecl *,
149                    llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
150
151    // ivar bitfield grouping containers
152    llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153    llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154    // This container maps an <class, group number for ivar> tuple to the type
155    // of the struct where the bitfield belongs.
156    llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
157    SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
158
159    // This maps an original source AST to it's rewritten form. This allows
160    // us to avoid rewriting the same node twice (which is very uncommon).
161    // This is needed to support some of the exotic property rewriting.
162    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164    // Needed for header files being rewritten
165    bool IsHeader;
166    bool SilenceRewriteMacroWarning;
167    bool GenerateLineInfo;
168    bool objc_impl_method;
169
170    bool DisableReplaceStmt;
171    class DisableReplaceStmtScope {
172      RewriteModernObjC &R;
173      bool SavedValue;
174
175    public:
176      DisableReplaceStmtScope(RewriteModernObjC &R)
177        : R(R), SavedValue(R.DisableReplaceStmt) {
178        R.DisableReplaceStmt = true;
179      }
180      ~DisableReplaceStmtScope() {
181        R.DisableReplaceStmt = SavedValue;
182      }
183    };
184    void InitializeCommon(ASTContext &context);
185
186  public:
187    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
188
189    // Top Level Driver code.
190    bool HandleTopLevelDecl(DeclGroupRef D) override {
191      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192        if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193          if (!Class->isThisDeclarationADefinition()) {
194            RewriteForwardClassDecl(D);
195            break;
196          } else {
197            // Keep track of all interface declarations seen.
198            ObjCInterfacesSeen.push_back(Class);
199            break;
200          }
201        }
202
203        if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204          if (!Proto->isThisDeclarationADefinition()) {
205            RewriteForwardProtocolDecl(D);
206            break;
207          }
208        }
209
210        if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211          // Under modern abi, we cannot translate body of the function
212          // yet until all class extensions and its implementation is seen.
213          // This is because they may introduce new bitfields which must go
214          // into their grouping struct.
215          if (FDecl->isThisDeclarationADefinition() &&
216              // Not c functions defined inside an objc container.
217              !FDecl->isTopLevelDeclInObjCContainer()) {
218            FunctionDefinitionsSeen.push_back(FDecl);
219            break;
220          }
221        }
222        HandleTopLevelSingleDecl(*I);
223      }
224      return true;
225    }
226
227    void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230          if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231            RewriteBlockPointerDecl(TD);
232          else if (TD->getUnderlyingType()->isFunctionPointerType())
233            CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234          else
235            RewriteObjCQualifiedInterfaceTypes(TD);
236        }
237      }
238    }
239
240    void HandleTopLevelSingleDecl(Decl *D);
241    void HandleDeclInMainFile(Decl *D);
242    RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243                      DiagnosticsEngine &D, const LangOptions &LOpts,
244                      bool silenceMacroWarn, bool LineInfo);
245
246    ~RewriteModernObjC() override {}
247
248    void HandleTranslationUnit(ASTContext &C) override;
249
250    void ReplaceStmt(Stmt *Old, Stmt *New) {
251      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
252    }
253
254    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
256
257      Stmt *ReplacingStmt = ReplacedNodes[Old];
258      if (ReplacingStmt)
259        return; // We can't rewrite the same node twice.
260
261      if (DisableReplaceStmt)
262        return;
263
264      // Measure the old text.
265      int Size = Rewrite.getRangeSize(SrcRange);
266      if (Size == -1) {
267        Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268            << Old->getSourceRange();
269        return;
270      }
271      // Get the new text.
272      std::string SStr;
273      llvm::raw_string_ostream S(SStr);
274      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
275      const std::string &Str = S.str();
276
277      // If replacement succeeded or warning disabled return with no warning.
278      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279        ReplacedNodes[Old] = New;
280        return;
281      }
282      if (SilenceRewriteMacroWarning)
283        return;
284      Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285          << Old->getSourceRange();
286    }
287
288    void InsertText(SourceLocation Loc, StringRef Str,
289                    bool InsertAfter = true) {
290      // If insertion succeeded or warning disabled return with no warning.
291      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292          SilenceRewriteMacroWarning)
293        return;
294
295      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296    }
297
298    void ReplaceText(SourceLocation Start, unsigned OrigLength,
299                     StringRef Str) {
300      // If removal succeeded or warning disabled return with no warning.
301      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302          SilenceRewriteMacroWarning)
303        return;
304
305      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306    }
307
308    // Syntactic Rewriting.
309    void RewriteRecordBody(RecordDecl *RD);
310    void RewriteInclude();
311    void RewriteLineDirective(const Decl *D);
312    void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313                                              std::string &LineString);
314    void RewriteForwardClassDecl(DeclGroupRef D);
315    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
316    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317                                     const std::string &typedefString);
318    void RewriteImplementations();
319    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320                                 ObjCImplementationDecl *IMD,
321                                 ObjCCategoryImplDecl *CID);
322    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323    void RewriteImplementationDecl(Decl *Dcl);
324    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325                               ObjCMethodDecl *MDecl, std::string &ResultStr);
326    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327                               const FunctionType *&FPRetType);
328    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329                            ValueDecl *VD, bool def=false);
330    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332    void RewriteForwardProtocolDecl(DeclGroupRef D);
333    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
334    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335    void RewriteProperty(ObjCPropertyDecl *prop);
336    void RewriteFunctionDecl(FunctionDecl *FD);
337    void RewriteBlockPointerType(std::string& Str, QualType Type);
338    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
339    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
340    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341    void RewriteTypeOfDecl(VarDecl *VD);
342    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
343
344    std::string getIvarAccessString(ObjCIvarDecl *D);
345
346    // Expression Rewriting.
347    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
354    Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
355    Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
356    Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
357    Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
358    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
359    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
360    Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
361    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364                                       SourceLocation OrigEnd);
365    Stmt *RewriteBreakStmt(BreakStmt *S);
366    Stmt *RewriteContinueStmt(ContinueStmt *S);
367    void RewriteCastExpr(CStyleCastExpr *CE);
368    void RewriteImplicitCastObjCExpr(CastExpr *IE);
369
370    // Computes ivar bitfield group no.
371    unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372    // Names field decl. for ivar bitfield group.
373    void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374    // Names struct type for ivar bitfield group.
375    void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376    // Names symbol for ivar bitfield group field offset.
377    void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378    // Given an ivar bitfield, it builds (or finds) its group record type.
379    QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380    QualType SynthesizeBitfieldGroupStructType(
381                                    ObjCIvarDecl *IV,
382                                    SmallVectorImpl<ObjCIvarDecl *> &IVars);
383
384    // Block rewriting.
385    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386
387    // Block specific rewrite rules.
388    void RewriteBlockPointerDecl(NamedDecl *VD);
389    void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
390    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
391    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393
394    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395                                      std::string &Result);
396
397    void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
398    bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
399                                 bool &IsNamedDefinition);
400    void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401                                              std::string &Result);
402
403    bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404
405    void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406                                  std::string &Result);
407
408    void Initialize(ASTContext &context) override;
409
410    // Misc. AST transformation routines. Sometimes they end up calling
411    // rewriting routines on the new ASTs.
412    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
413                                           ArrayRef<Expr *> Args,
414                                           SourceLocation StartLoc=SourceLocation(),
415                                           SourceLocation EndLoc=SourceLocation());
416
417    Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
418                                        QualType returnType,
419                                        SmallVectorImpl<QualType> &ArgTypes,
420                                        SmallVectorImpl<Expr*> &MsgExprs,
421                                        ObjCMethodDecl *Method);
422
423    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424                           SourceLocation StartLoc=SourceLocation(),
425                           SourceLocation EndLoc=SourceLocation());
426
427    void SynthCountByEnumWithState(std::string &buf);
428    void SynthMsgSendFunctionDecl();
429    void SynthMsgSendSuperFunctionDecl();
430    void SynthMsgSendStretFunctionDecl();
431    void SynthMsgSendFpretFunctionDecl();
432    void SynthMsgSendSuperStretFunctionDecl();
433    void SynthGetClassFunctionDecl();
434    void SynthGetMetaClassFunctionDecl();
435    void SynthGetSuperClassFunctionDecl();
436    void SynthSelGetUidFunctionDecl();
437    void SynthSuperConstructorFunctionDecl();
438
439    // Rewriting metadata
440    template<typename MethodIterator>
441    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442                                    MethodIterator MethodEnd,
443                                    bool IsInstanceMethod,
444                                    StringRef prefix,
445                                    StringRef ClassName,
446                                    std::string &Result);
447    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448                                     std::string &Result);
449    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
450                                          std::string &Result);
451    void RewriteClassSetupInitHook(std::string &Result);
452
453    void RewriteMetaDataIntoBuffer(std::string &Result);
454    void WriteImageInfo(std::string &Result);
455    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
456                                             std::string &Result);
457    void RewriteCategorySetupInitHook(std::string &Result);
458
459    // Rewriting ivar
460    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
461                                              std::string &Result);
462    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
463
464
465    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467                                      StringRef funcName, std::string Tag);
468    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469                                      StringRef funcName, std::string Tag);
470    std::string SynthesizeBlockImpl(BlockExpr *CE,
471                                    std::string Tag, std::string Desc);
472    std::string SynthesizeBlockDescriptor(std::string DescTag,
473                                          std::string ImplTag,
474                                          int i, StringRef funcName,
475                                          unsigned hasCopy);
476    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478                                 StringRef FunName);
479    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
481                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
482
483    // Misc. helper routines.
484    QualType getProtocolType();
485    void WarnAboutReturnGotoStmts(Stmt *S);
486    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491    void CollectBlockDeclRefInfo(BlockExpr *Exp);
492    void GetBlockDeclRefExprs(Stmt *S);
493    void GetInnerBlockDeclRefExprs(Stmt *S,
494                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
495                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
496
497    // We avoid calling Type::isBlockPointerType(), since it operates on the
498    // canonical type. We only care if the top-level type is a closure pointer.
499    bool isTopLevelBlockPointerType(QualType T) {
500      return isa<BlockPointerType>(T);
501    }
502
503    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504    /// to a function pointer type and upon success, returns true; false
505    /// otherwise.
506    bool convertBlockPointerToFunctionPointer(QualType &T) {
507      if (isTopLevelBlockPointerType(T)) {
508        const auto *BPT = T->castAs<BlockPointerType>();
509        T = Context->getPointerType(BPT->getPointeeType());
510        return true;
511      }
512      return false;
513    }
514
515    bool convertObjCTypeToCStyleType(QualType &T);
516
517    bool needToScanForQualifiers(QualType T);
518    QualType getSuperStructType();
519    QualType getConstantStringStructType();
520    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521
522    void convertToUnqualifiedObjCType(QualType &T) {
523      if (T->isObjCQualifiedIdType()) {
524        bool isConst = T.isConstQualified();
525        T = isConst ? Context->getObjCIdType().withConst()
526                    : Context->getObjCIdType();
527      }
528      else if (T->isObjCQualifiedClassType())
529        T = Context->getObjCClassType();
530      else if (T->isObjCObjectPointerType() &&
531               T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532        if (const ObjCObjectPointerType * OBJPT =
533              T->getAsObjCInterfacePointerType()) {
534          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535          T = QualType(IFaceT, 0);
536          T = Context->getPointerType(T);
537        }
538     }
539    }
540
541    // FIXME: This predicate seems like it would be useful to add to ASTContext.
542    bool isObjCType(QualType T) {
543      if (!LangOpts.ObjC)
544        return false;
545
546      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549          OCT == Context->getCanonicalType(Context->getObjCClassType()))
550        return true;
551
552      if (const PointerType *PT = OCT->getAs<PointerType>()) {
553        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554            PT->getPointeeType()->isObjCQualifiedIdType())
555          return true;
556      }
557      return false;
558    }
559
560    bool PointerTypeTakesAnyBlockArguments(QualType QT);
561    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562    void GetExtentOfArgList(const char *Name, const char *&LParen,
563                            const char *&RParen);
564
565    void QuoteDoublequotes(std::string &From, std::string &To) {
566      for (unsigned i = 0; i < From.length(); i++) {
567        if (From[i] == '"')
568          To += "\\\"";
569        else
570          To += From[i];
571      }
572    }
573
574    QualType getSimpleFunctionType(QualType result,
575                                   ArrayRef<QualType> args,
576                                   bool variadic = false) {
577      if (result == Context->getObjCInstanceType())
578        result =  Context->getObjCIdType();
579      FunctionProtoType::ExtProtoInfo fpi;
580      fpi.Variadic = variadic;
581      return Context->getFunctionType(result, args, fpi);
582    }
583
584    // Helper function: create a CStyleCastExpr with trivial type source info.
585    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586                                             CastKind Kind, Expr *E) {
587      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589                                    TInfo, SourceLocation(), SourceLocation());
590    }
591
592    bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593      IdentifierInfo* II = &Context->Idents.get("load");
594      Selector LoadSel = Context->Selectors.getSelector(0, &II);
595      return OD->getClassMethod(LoadSel) != nullptr;
596    }
597
598    StringLiteral *getStringLiteral(StringRef Str) {
599      QualType StrType = Context->getConstantArrayType(
600          Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
601          ArrayType::Normal, 0);
602      return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603                                   /*Pascal=*/false, StrType, SourceLocation());
604    }
605  };
606} // end anonymous namespace
607
608void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609                                                   NamedDecl *D) {
610  if (const FunctionProtoType *fproto
611      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
612    for (const auto &I : fproto->param_types())
613      if (isTopLevelBlockPointerType(I)) {
614        // All the args are checked/rewritten. Don't call twice!
615        RewriteBlockPointerDecl(D);
616        break;
617      }
618  }
619}
620
621void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622  const PointerType *PT = funcType->getAs<PointerType>();
623  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625}
626
627static bool IsHeaderFile(const std::string &Filename) {
628  std::string::size_type DotPos = Filename.rfind('.');
629
630  if (DotPos == std::string::npos) {
631    // no file extension
632    return false;
633  }
634
635  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636  // C header: .h
637  // C++ header: .hh or .H;
638  return Ext == "h" || Ext == "hh" || Ext == "H";
639}
640
641RewriteModernObjC::RewriteModernObjC(std::string inFile,
642                                     std::unique_ptr<raw_ostream> OS,
643                                     DiagnosticsEngine &D,
644                                     const LangOptions &LOpts,
645                                     bool silenceMacroWarn, bool LineInfo)
646    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647      SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
648  IsHeader = IsHeaderFile(inFile);
649  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650               "rewriting sub-expression within a macro (may not be correct)");
651  // FIXME. This should be an error. But if block is not called, it is OK. And it
652  // may break including some headers.
653  GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654    "rewriting block literal declared in global scope is not implemented");
655
656  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657               DiagnosticsEngine::Warning,
658               "rewriter doesn't support user-specified control flow semantics "
659               "for @try/@finally (code may not execute properly)");
660}
661
662std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
663    const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664    DiagnosticsEngine &Diags, const LangOptions &LOpts,
665    bool SilenceRewriteMacroWarning, bool LineInfo) {
666  return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
667                                              LOpts, SilenceRewriteMacroWarning,
668                                              LineInfo);
669}
670
671void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672  Context = &context;
673  SM = &Context->getSourceManager();
674  TUDecl = Context->getTranslationUnitDecl();
675  MsgSendFunctionDecl = nullptr;
676  MsgSendSuperFunctionDecl = nullptr;
677  MsgSendStretFunctionDecl = nullptr;
678  MsgSendSuperStretFunctionDecl = nullptr;
679  MsgSendFpretFunctionDecl = nullptr;
680  GetClassFunctionDecl = nullptr;
681  GetMetaClassFunctionDecl = nullptr;
682  GetSuperClassFunctionDecl = nullptr;
683  SelGetUidFunctionDecl = nullptr;
684  CFStringFunctionDecl = nullptr;
685  ConstantStringClassReference = nullptr;
686  NSStringRecord = nullptr;
687  CurMethodDef = nullptr;
688  CurFunctionDef = nullptr;
689  GlobalVarDecl = nullptr;
690  GlobalConstructionExp = nullptr;
691  SuperStructDecl = nullptr;
692  ProtocolTypeDecl = nullptr;
693  ConstantStringDecl = nullptr;
694  BcLabelCount = 0;
695  SuperConstructorFunctionDecl = nullptr;
696  NumObjCStringLiterals = 0;
697  PropParentMap = nullptr;
698  CurrentBody = nullptr;
699  DisableReplaceStmt = false;
700  objc_impl_method = false;
701
702  // Get the ID and start/end of the main file.
703  MainFileID = SM->getMainFileID();
704  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705  MainFileStart = MainBuf->getBufferStart();
706  MainFileEnd = MainBuf->getBufferEnd();
707
708  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
709}
710
711//===----------------------------------------------------------------------===//
712// Top Level Driver Code
713//===----------------------------------------------------------------------===//
714
715void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716  if (Diags.hasErrorOccurred())
717    return;
718
719  // Two cases: either the decl could be in the main file, or it could be in a
720  // #included file.  If the former, rewrite it now.  If the later, check to see
721  // if we rewrote the #include/#import.
722  SourceLocation Loc = D->getLocation();
723  Loc = SM->getExpansionLoc(Loc);
724
725  // If this is for a builtin, ignore it.
726  if (Loc.isInvalid()) return;
727
728  // Look for built-in declarations that we need to refer during the rewrite.
729  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730    RewriteFunctionDecl(FD);
731  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732    // declared in <Foundation/NSString.h>
733    if (FVD->getName() == "_NSConstantStringClassReference") {
734      ConstantStringClassReference = FVD;
735      return;
736    }
737  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738    RewriteCategoryDecl(CD);
739  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740    if (PD->isThisDeclarationADefinition())
741      RewriteProtocolDecl(PD);
742  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743    // Recurse into linkage specifications
744    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745                                 DIEnd = LSD->decls_end();
746         DI != DIEnd; ) {
747      if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748        if (!IFace->isThisDeclarationADefinition()) {
749          SmallVector<Decl *, 8> DG;
750          SourceLocation StartLoc = IFace->getBeginLoc();
751          do {
752            if (isa<ObjCInterfaceDecl>(*DI) &&
753                !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
754                StartLoc == (*DI)->getBeginLoc())
755              DG.push_back(*DI);
756            else
757              break;
758
759            ++DI;
760          } while (DI != DIEnd);
761          RewriteForwardClassDecl(DG);
762          continue;
763        }
764        else {
765          // Keep track of all interface declarations seen.
766          ObjCInterfacesSeen.push_back(IFace);
767          ++DI;
768          continue;
769        }
770      }
771
772      if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773        if (!Proto->isThisDeclarationADefinition()) {
774          SmallVector<Decl *, 8> DG;
775          SourceLocation StartLoc = Proto->getBeginLoc();
776          do {
777            if (isa<ObjCProtocolDecl>(*DI) &&
778                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
779                StartLoc == (*DI)->getBeginLoc())
780              DG.push_back(*DI);
781            else
782              break;
783
784            ++DI;
785          } while (DI != DIEnd);
786          RewriteForwardProtocolDecl(DG);
787          continue;
788        }
789      }
790
791      HandleTopLevelSingleDecl(*DI);
792      ++DI;
793    }
794  }
795  // If we have a decl in the main file, see if we should rewrite it.
796  if (SM->isWrittenInMainFile(Loc))
797    return HandleDeclInMainFile(D);
798}
799
800//===----------------------------------------------------------------------===//
801// Syntactic (non-AST) Rewriting Code
802//===----------------------------------------------------------------------===//
803
804void RewriteModernObjC::RewriteInclude() {
805  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806  StringRef MainBuf = SM->getBufferData(MainFileID);
807  const char *MainBufStart = MainBuf.begin();
808  const char *MainBufEnd = MainBuf.end();
809  size_t ImportLen = strlen("import");
810
811  // Loop over the whole file, looking for includes.
812  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
813    if (*BufPtr == '#') {
814      if (++BufPtr == MainBufEnd)
815        return;
816      while (*BufPtr == ' ' || *BufPtr == '\t')
817        if (++BufPtr == MainBufEnd)
818          return;
819      if (!strncmp(BufPtr, "import", ImportLen)) {
820        // replace import with include
821        SourceLocation ImportLoc =
822          LocStart.getLocWithOffset(BufPtr-MainBufStart);
823        ReplaceText(ImportLoc, ImportLen, "include");
824        BufPtr += ImportLen;
825      }
826    }
827  }
828}
829
830static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831                                  ObjCIvarDecl *IvarDecl, std::string &Result) {
832  Result += "OBJC_IVAR_$_";
833  Result += IDecl->getName();
834  Result += "$";
835  Result += IvarDecl->getName();
836}
837
838std::string
839RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840  const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
841
842  // Build name of symbol holding ivar offset.
843  std::string IvarOffsetName;
844  if (D->isBitField())
845    ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846  else
847    WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
848
849  std::string S = "(*(";
850  QualType IvarT = D->getType();
851  if (D->isBitField())
852    IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
853
854  if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
855    RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
856    RD = RD->getDefinition();
857    if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858      // decltype(((Foo_IMPL*)0)->bar) *
859      auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
860      // ivar in class extensions requires special treatment.
861      if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862        CDecl = CatDecl->getClassInterface();
863      std::string RecName = std::string(CDecl->getName());
864      RecName += "_IMPL";
865      RecordDecl *RD =
866          RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
867                             SourceLocation(), &Context->Idents.get(RecName));
868      QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869      unsigned UnsignedIntSize =
870      static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871      Expr *Zero = IntegerLiteral::Create(*Context,
872                                          llvm::APInt(UnsignedIntSize, 0),
873                                          Context->UnsignedIntTy, SourceLocation());
874      Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875      ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876                                              Zero);
877      FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
878                                        SourceLocation(),
879                                        &Context->Idents.get(D->getNameAsString()),
880                                        IvarT, nullptr,
881                                        /*BitWidth=*/nullptr, /*Mutable=*/true,
882                                        ICIS_NoInit);
883      MemberExpr *ME = MemberExpr::CreateImplicit(
884          *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
885      IvarT = Context->getDecltypeType(ME, ME->getType());
886    }
887  }
888  convertObjCTypeToCStyleType(IvarT);
889  QualType castT = Context->getPointerType(IvarT);
890  std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891  S += TypeString;
892  S += ")";
893
894  // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895  S += "((char *)self + ";
896  S += IvarOffsetName;
897  S += "))";
898  if (D->isBitField()) {
899    S += ".";
900    S += D->getNameAsString();
901  }
902  ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
903  return S;
904}
905
906/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907/// been found in the class implementation. In this case, it must be synthesized.
908static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909                                             ObjCPropertyDecl *PD,
910                                             bool getter) {
911  auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
912                                            : PD->getSetterName());
913  return !OMD || OMD->isSynthesizedAccessorStub();
914}
915
916void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917                                          ObjCImplementationDecl *IMD,
918                                          ObjCCategoryImplDecl *CID) {
919  static bool objcGetPropertyDefined = false;
920  static bool objcSetPropertyDefined = false;
921  SourceLocation startGetterSetterLoc;
922
923  if (PID->getBeginLoc().isValid()) {
924    SourceLocation startLoc = PID->getBeginLoc();
925    InsertText(startLoc, "// ");
926    const char *startBuf = SM->getCharacterData(startLoc);
927    assert((*startBuf == '@') && "bogus @synthesize location");
928    const char *semiBuf = strchr(startBuf, ';');
929    assert((*semiBuf == ';') && "@synthesize: can't find ';'");
930    startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
931  } else
932    startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
933
934  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935    return; // FIXME: is this correct?
936
937  // Generate the 'getter' function.
938  ObjCPropertyDecl *PD = PID->getPropertyDecl();
939  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
940  assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
941
942  unsigned Attributes = PD->getPropertyAttributes();
943  if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
944    bool GenGetProperty =
945        !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
946        (Attributes & (ObjCPropertyAttribute::kind_retain |
947                       ObjCPropertyAttribute::kind_copy));
948    std::string Getr;
949    if (GenGetProperty && !objcGetPropertyDefined) {
950      objcGetPropertyDefined = true;
951      // FIXME. Is this attribute correct in all cases?
952      Getr = "\nextern \"C\" __declspec(dllimport) "
953            "id objc_getProperty(id, SEL, long, bool);\n";
954    }
955    RewriteObjCMethodDecl(OID->getContainingInterface(),
956                          PID->getGetterMethodDecl(), Getr);
957    Getr += "{ ";
958    // Synthesize an explicit cast to gain access to the ivar.
959    // See objc-act.c:objc_synthesize_new_getter() for details.
960    if (GenGetProperty) {
961      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
962      Getr += "typedef ";
963      const FunctionType *FPRetType = nullptr;
964      RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
965                            FPRetType);
966      Getr += " _TYPE";
967      if (FPRetType) {
968        Getr += ")"; // close the precedence "scope" for "*".
969
970        // Now, emit the argument types (if any).
971        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
972          Getr += "(";
973          for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
974            if (i) Getr += ", ";
975            std::string ParamStr =
976                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
977            Getr += ParamStr;
978          }
979          if (FT->isVariadic()) {
980            if (FT->getNumParams())
981              Getr += ", ";
982            Getr += "...";
983          }
984          Getr += ")";
985        } else
986          Getr += "()";
987      }
988      Getr += ";\n";
989      Getr += "return (_TYPE)";
990      Getr += "objc_getProperty(self, _cmd, ";
991      RewriteIvarOffsetComputation(OID, Getr);
992      Getr += ", 1)";
993    }
994    else
995      Getr += "return " + getIvarAccessString(OID);
996    Getr += "; }";
997    InsertText(startGetterSetterLoc, Getr);
998  }
999
1000  if (PD->isReadOnly() ||
1001      !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1002    return;
1003
1004  // Generate the 'setter' function.
1005  std::string Setr;
1006  bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
1007                                      ObjCPropertyAttribute::kind_copy);
1008  if (GenSetProperty && !objcSetPropertyDefined) {
1009    objcSetPropertyDefined = true;
1010    // FIXME. Is this attribute correct in all cases?
1011    Setr = "\nextern \"C\" __declspec(dllimport) "
1012    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1013  }
1014
1015  RewriteObjCMethodDecl(OID->getContainingInterface(),
1016                        PID->getSetterMethodDecl(), Setr);
1017  Setr += "{ ";
1018  // Synthesize an explicit cast to initialize the ivar.
1019  // See objc-act.c:objc_synthesize_new_setter() for details.
1020  if (GenSetProperty) {
1021    Setr += "objc_setProperty (self, _cmd, ";
1022    RewriteIvarOffsetComputation(OID, Setr);
1023    Setr += ", (id)";
1024    Setr += PD->getName();
1025    Setr += ", ";
1026    if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
1027      Setr += "0, ";
1028    else
1029      Setr += "1, ";
1030    if (Attributes & ObjCPropertyAttribute::kind_copy)
1031      Setr += "1)";
1032    else
1033      Setr += "0)";
1034  }
1035  else {
1036    Setr += getIvarAccessString(OID) + " = ";
1037    Setr += PD->getName();
1038  }
1039  Setr += "; }\n";
1040  InsertText(startGetterSetterLoc, Setr);
1041}
1042
1043static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1044                                       std::string &typedefString) {
1045  typedefString += "\n#ifndef _REWRITER_typedef_";
1046  typedefString += ForwardDecl->getNameAsString();
1047  typedefString += "\n";
1048  typedefString += "#define _REWRITER_typedef_";
1049  typedefString += ForwardDecl->getNameAsString();
1050  typedefString += "\n";
1051  typedefString += "typedef struct objc_object ";
1052  typedefString += ForwardDecl->getNameAsString();
1053  // typedef struct { } _objc_exc_Classname;
1054  typedefString += ";\ntypedef struct {} _objc_exc_";
1055  typedefString += ForwardDecl->getNameAsString();
1056  typedefString += ";\n#endif\n";
1057}
1058
1059void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1060                                              const std::string &typedefString) {
1061  SourceLocation startLoc = ClassDecl->getBeginLoc();
1062  const char *startBuf = SM->getCharacterData(startLoc);
1063  const char *semiPtr = strchr(startBuf, ';');
1064  // Replace the @class with typedefs corresponding to the classes.
1065  ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1066}
1067
1068void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1069  std::string typedefString;
1070  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1071    if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1072      if (I == D.begin()) {
1073        // Translate to typedef's that forward reference structs with the same name
1074        // as the class. As a convenience, we include the original declaration
1075        // as a comment.
1076        typedefString += "// @class ";
1077        typedefString += ForwardDecl->getNameAsString();
1078        typedefString += ";";
1079      }
1080      RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1081    }
1082    else
1083      HandleTopLevelSingleDecl(*I);
1084  }
1085  DeclGroupRef::iterator I = D.begin();
1086  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1087}
1088
1089void RewriteModernObjC::RewriteForwardClassDecl(
1090                                const SmallVectorImpl<Decl *> &D) {
1091  std::string typedefString;
1092  for (unsigned i = 0; i < D.size(); i++) {
1093    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1094    if (i == 0) {
1095      typedefString += "// @class ";
1096      typedefString += ForwardDecl->getNameAsString();
1097      typedefString += ";";
1098    }
1099    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1100  }
1101  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1102}
1103
1104void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1105  // When method is a synthesized one, such as a getter/setter there is
1106  // nothing to rewrite.
1107  if (Method->isImplicit())
1108    return;
1109  SourceLocation LocStart = Method->getBeginLoc();
1110  SourceLocation LocEnd = Method->getEndLoc();
1111
1112  if (SM->getExpansionLineNumber(LocEnd) >
1113      SM->getExpansionLineNumber(LocStart)) {
1114    InsertText(LocStart, "#if 0\n");
1115    ReplaceText(LocEnd, 1, ";\n#endif\n");
1116  } else {
1117    InsertText(LocStart, "// ");
1118  }
1119}
1120
1121void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1122  SourceLocation Loc = prop->getAtLoc();
1123
1124  ReplaceText(Loc, 0, "// ");
1125  // FIXME: handle properties that are declared across multiple lines.
1126}
1127
1128void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1129  SourceLocation LocStart = CatDecl->getBeginLoc();
1130
1131  // FIXME: handle category headers that are declared across multiple lines.
1132  if (CatDecl->getIvarRBraceLoc().isValid()) {
1133    ReplaceText(LocStart, 1, "/** ");
1134    ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1135  }
1136  else {
1137    ReplaceText(LocStart, 0, "// ");
1138  }
1139
1140  for (auto *I : CatDecl->instance_properties())
1141    RewriteProperty(I);
1142
1143  for (auto *I : CatDecl->instance_methods())
1144    RewriteMethodDeclaration(I);
1145  for (auto *I : CatDecl->class_methods())
1146    RewriteMethodDeclaration(I);
1147
1148  // Lastly, comment out the @end.
1149  ReplaceText(CatDecl->getAtEndRange().getBegin(),
1150              strlen("@end"), "/* @end */\n");
1151}
1152
1153void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1154  SourceLocation LocStart = PDecl->getBeginLoc();
1155  assert(PDecl->isThisDeclarationADefinition());
1156
1157  // FIXME: handle protocol headers that are declared across multiple lines.
1158  ReplaceText(LocStart, 0, "// ");
1159
1160  for (auto *I : PDecl->instance_methods())
1161    RewriteMethodDeclaration(I);
1162  for (auto *I : PDecl->class_methods())
1163    RewriteMethodDeclaration(I);
1164  for (auto *I : PDecl->instance_properties())
1165    RewriteProperty(I);
1166
1167  // Lastly, comment out the @end.
1168  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1169  ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1170
1171  // Must comment out @optional/@required
1172  const char *startBuf = SM->getCharacterData(LocStart);
1173  const char *endBuf = SM->getCharacterData(LocEnd);
1174  for (const char *p = startBuf; p < endBuf; p++) {
1175    if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1176      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1177      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1178
1179    }
1180    else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1181      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1182      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1183
1184    }
1185  }
1186}
1187
1188void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1189  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1190  if (LocStart.isInvalid())
1191    llvm_unreachable("Invalid SourceLocation");
1192  // FIXME: handle forward protocol that are declared across multiple lines.
1193  ReplaceText(LocStart, 0, "// ");
1194}
1195
1196void
1197RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1198  SourceLocation LocStart = DG[0]->getBeginLoc();
1199  if (LocStart.isInvalid())
1200    llvm_unreachable("Invalid SourceLocation");
1201  // FIXME: handle forward protocol that are declared across multiple lines.
1202  ReplaceText(LocStart, 0, "// ");
1203}
1204
1205void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1206                                        const FunctionType *&FPRetType) {
1207  if (T->isObjCQualifiedIdType())
1208    ResultStr += "id";
1209  else if (T->isFunctionPointerType() ||
1210           T->isBlockPointerType()) {
1211    // needs special handling, since pointer-to-functions have special
1212    // syntax (where a decaration models use).
1213    QualType retType = T;
1214    QualType PointeeTy;
1215    if (const PointerType* PT = retType->getAs<PointerType>())
1216      PointeeTy = PT->getPointeeType();
1217    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1218      PointeeTy = BPT->getPointeeType();
1219    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1220      ResultStr +=
1221          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1222      ResultStr += "(*";
1223    }
1224  } else
1225    ResultStr += T.getAsString(Context->getPrintingPolicy());
1226}
1227
1228void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1229                                        ObjCMethodDecl *OMD,
1230                                        std::string &ResultStr) {
1231  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1232  const FunctionType *FPRetType = nullptr;
1233  ResultStr += "\nstatic ";
1234  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1235  ResultStr += " ";
1236
1237  // Unique method name
1238  std::string NameStr;
1239
1240  if (OMD->isInstanceMethod())
1241    NameStr += "_I_";
1242  else
1243    NameStr += "_C_";
1244
1245  NameStr += IDecl->getNameAsString();
1246  NameStr += "_";
1247
1248  if (ObjCCategoryImplDecl *CID =
1249      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1250    NameStr += CID->getNameAsString();
1251    NameStr += "_";
1252  }
1253  // Append selector names, replacing ':' with '_'
1254  {
1255    std::string selString = OMD->getSelector().getAsString();
1256    int len = selString.size();
1257    for (int i = 0; i < len; i++)
1258      if (selString[i] == ':')
1259        selString[i] = '_';
1260    NameStr += selString;
1261  }
1262  // Remember this name for metadata emission
1263  MethodInternalNames[OMD] = NameStr;
1264  ResultStr += NameStr;
1265
1266  // Rewrite arguments
1267  ResultStr += "(";
1268
1269  // invisible arguments
1270  if (OMD->isInstanceMethod()) {
1271    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1272    selfTy = Context->getPointerType(selfTy);
1273    if (!LangOpts.MicrosoftExt) {
1274      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1275        ResultStr += "struct ";
1276    }
1277    // When rewriting for Microsoft, explicitly omit the structure name.
1278    ResultStr += IDecl->getNameAsString();
1279    ResultStr += " *";
1280  }
1281  else
1282    ResultStr += Context->getObjCClassType().getAsString(
1283      Context->getPrintingPolicy());
1284
1285  ResultStr += " self, ";
1286  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1287  ResultStr += " _cmd";
1288
1289  // Method arguments.
1290  for (const auto *PDecl : OMD->parameters()) {
1291    ResultStr += ", ";
1292    if (PDecl->getType()->isObjCQualifiedIdType()) {
1293      ResultStr += "id ";
1294      ResultStr += PDecl->getNameAsString();
1295    } else {
1296      std::string Name = PDecl->getNameAsString();
1297      QualType QT = PDecl->getType();
1298      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1299      (void)convertBlockPointerToFunctionPointer(QT);
1300      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1301      ResultStr += Name;
1302    }
1303  }
1304  if (OMD->isVariadic())
1305    ResultStr += ", ...";
1306  ResultStr += ") ";
1307
1308  if (FPRetType) {
1309    ResultStr += ")"; // close the precedence "scope" for "*".
1310
1311    // Now, emit the argument types (if any).
1312    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1313      ResultStr += "(";
1314      for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1315        if (i) ResultStr += ", ";
1316        std::string ParamStr =
1317            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1318        ResultStr += ParamStr;
1319      }
1320      if (FT->isVariadic()) {
1321        if (FT->getNumParams())
1322          ResultStr += ", ";
1323        ResultStr += "...";
1324      }
1325      ResultStr += ")";
1326    } else {
1327      ResultStr += "()";
1328    }
1329  }
1330}
1331
1332void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1333  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1334  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1335  assert((IMD || CID) && "Unknown implementation type");
1336
1337  if (IMD) {
1338    if (IMD->getIvarRBraceLoc().isValid()) {
1339      ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1340      ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1341    }
1342    else {
1343      InsertText(IMD->getBeginLoc(), "// ");
1344    }
1345  }
1346  else
1347    InsertText(CID->getBeginLoc(), "// ");
1348
1349  for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1350    if (!OMD->getBody())
1351      continue;
1352    std::string ResultStr;
1353    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1354    SourceLocation LocStart = OMD->getBeginLoc();
1355    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1356
1357    const char *startBuf = SM->getCharacterData(LocStart);
1358    const char *endBuf = SM->getCharacterData(LocEnd);
1359    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1360  }
1361
1362  for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1363    if (!OMD->getBody())
1364      continue;
1365    std::string ResultStr;
1366    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1367    SourceLocation LocStart = OMD->getBeginLoc();
1368    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1369
1370    const char *startBuf = SM->getCharacterData(LocStart);
1371    const char *endBuf = SM->getCharacterData(LocEnd);
1372    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1373  }
1374  for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1375    RewritePropertyImplDecl(I, IMD, CID);
1376
1377  InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1378}
1379
1380void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1381  // Do not synthesize more than once.
1382  if (ObjCSynthesizedStructs.count(ClassDecl))
1383    return;
1384  // Make sure super class's are written before current class is written.
1385  ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1386  while (SuperClass) {
1387    RewriteInterfaceDecl(SuperClass);
1388    SuperClass = SuperClass->getSuperClass();
1389  }
1390  std::string ResultStr;
1391  if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1392    // we haven't seen a forward decl - generate a typedef.
1393    RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1394    RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1395
1396    RewriteObjCInternalStruct(ClassDecl, ResultStr);
1397    // Mark this typedef as having been written into its c++ equivalent.
1398    ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1399
1400    for (auto *I : ClassDecl->instance_properties())
1401      RewriteProperty(I);
1402    for (auto *I : ClassDecl->instance_methods())
1403      RewriteMethodDeclaration(I);
1404    for (auto *I : ClassDecl->class_methods())
1405      RewriteMethodDeclaration(I);
1406
1407    // Lastly, comment out the @end.
1408    ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1409                "/* @end */\n");
1410  }
1411}
1412
1413Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1414  SourceRange OldRange = PseudoOp->getSourceRange();
1415
1416  // We just magically know some things about the structure of this
1417  // expression.
1418  ObjCMessageExpr *OldMsg =
1419    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1420                            PseudoOp->getNumSemanticExprs() - 1));
1421
1422  // Because the rewriter doesn't allow us to rewrite rewritten code,
1423  // we need to suppress rewriting the sub-statements.
1424  Expr *Base;
1425  SmallVector<Expr*, 2> Args;
1426  {
1427    DisableReplaceStmtScope S(*this);
1428
1429    // Rebuild the base expression if we have one.
1430    Base = nullptr;
1431    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1432      Base = OldMsg->getInstanceReceiver();
1433      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1434      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1435    }
1436
1437    unsigned numArgs = OldMsg->getNumArgs();
1438    for (unsigned i = 0; i < numArgs; i++) {
1439      Expr *Arg = OldMsg->getArg(i);
1440      if (isa<OpaqueValueExpr>(Arg))
1441        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1442      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1443      Args.push_back(Arg);
1444    }
1445  }
1446
1447  // TODO: avoid this copy.
1448  SmallVector<SourceLocation, 1> SelLocs;
1449  OldMsg->getSelectorLocs(SelLocs);
1450
1451  ObjCMessageExpr *NewMsg = nullptr;
1452  switch (OldMsg->getReceiverKind()) {
1453  case ObjCMessageExpr::Class:
1454    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455                                     OldMsg->getValueKind(),
1456                                     OldMsg->getLeftLoc(),
1457                                     OldMsg->getClassReceiverTypeInfo(),
1458                                     OldMsg->getSelector(),
1459                                     SelLocs,
1460                                     OldMsg->getMethodDecl(),
1461                                     Args,
1462                                     OldMsg->getRightLoc(),
1463                                     OldMsg->isImplicit());
1464    break;
1465
1466  case ObjCMessageExpr::Instance:
1467    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1468                                     OldMsg->getValueKind(),
1469                                     OldMsg->getLeftLoc(),
1470                                     Base,
1471                                     OldMsg->getSelector(),
1472                                     SelLocs,
1473                                     OldMsg->getMethodDecl(),
1474                                     Args,
1475                                     OldMsg->getRightLoc(),
1476                                     OldMsg->isImplicit());
1477    break;
1478
1479  case ObjCMessageExpr::SuperClass:
1480  case ObjCMessageExpr::SuperInstance:
1481    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1482                                     OldMsg->getValueKind(),
1483                                     OldMsg->getLeftLoc(),
1484                                     OldMsg->getSuperLoc(),
1485                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1486                                     OldMsg->getSuperType(),
1487                                     OldMsg->getSelector(),
1488                                     SelLocs,
1489                                     OldMsg->getMethodDecl(),
1490                                     Args,
1491                                     OldMsg->getRightLoc(),
1492                                     OldMsg->isImplicit());
1493    break;
1494  }
1495
1496  Stmt *Replacement = SynthMessageExpr(NewMsg);
1497  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1498  return Replacement;
1499}
1500
1501Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1502  SourceRange OldRange = PseudoOp->getSourceRange();
1503
1504  // We just magically know some things about the structure of this
1505  // expression.
1506  ObjCMessageExpr *OldMsg =
1507    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1508
1509  // Because the rewriter doesn't allow us to rewrite rewritten code,
1510  // we need to suppress rewriting the sub-statements.
1511  Expr *Base = nullptr;
1512  SmallVector<Expr*, 1> Args;
1513  {
1514    DisableReplaceStmtScope S(*this);
1515    // Rebuild the base expression if we have one.
1516    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1517      Base = OldMsg->getInstanceReceiver();
1518      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1519      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1520    }
1521    unsigned numArgs = OldMsg->getNumArgs();
1522    for (unsigned i = 0; i < numArgs; i++) {
1523      Expr *Arg = OldMsg->getArg(i);
1524      if (isa<OpaqueValueExpr>(Arg))
1525        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1526      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1527      Args.push_back(Arg);
1528    }
1529  }
1530
1531  // Intentionally empty.
1532  SmallVector<SourceLocation, 1> SelLocs;
1533
1534  ObjCMessageExpr *NewMsg = nullptr;
1535  switch (OldMsg->getReceiverKind()) {
1536  case ObjCMessageExpr::Class:
1537    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1538                                     OldMsg->getValueKind(),
1539                                     OldMsg->getLeftLoc(),
1540                                     OldMsg->getClassReceiverTypeInfo(),
1541                                     OldMsg->getSelector(),
1542                                     SelLocs,
1543                                     OldMsg->getMethodDecl(),
1544                                     Args,
1545                                     OldMsg->getRightLoc(),
1546                                     OldMsg->isImplicit());
1547    break;
1548
1549  case ObjCMessageExpr::Instance:
1550    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1551                                     OldMsg->getValueKind(),
1552                                     OldMsg->getLeftLoc(),
1553                                     Base,
1554                                     OldMsg->getSelector(),
1555                                     SelLocs,
1556                                     OldMsg->getMethodDecl(),
1557                                     Args,
1558                                     OldMsg->getRightLoc(),
1559                                     OldMsg->isImplicit());
1560    break;
1561
1562  case ObjCMessageExpr::SuperClass:
1563  case ObjCMessageExpr::SuperInstance:
1564    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1565                                     OldMsg->getValueKind(),
1566                                     OldMsg->getLeftLoc(),
1567                                     OldMsg->getSuperLoc(),
1568                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1569                                     OldMsg->getSuperType(),
1570                                     OldMsg->getSelector(),
1571                                     SelLocs,
1572                                     OldMsg->getMethodDecl(),
1573                                     Args,
1574                                     OldMsg->getRightLoc(),
1575                                     OldMsg->isImplicit());
1576    break;
1577  }
1578
1579  Stmt *Replacement = SynthMessageExpr(NewMsg);
1580  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1581  return Replacement;
1582}
1583
1584/// SynthCountByEnumWithState - To print:
1585/// ((NSUInteger (*)
1586///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1587///  (void *)objc_msgSend)((id)l_collection,
1588///                        sel_registerName(
1589///                          "countByEnumeratingWithState:objects:count:"),
1590///                        &enumState,
1591///                        (id *)__rw_items, (NSUInteger)16)
1592///
1593void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1594  buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1595  "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1596  buf += "\n\t\t";
1597  buf += "((id)l_collection,\n\t\t";
1598  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1599  buf += "\n\t\t";
1600  buf += "&enumState, "
1601         "(id *)__rw_items, (_WIN_NSUInteger)16)";
1602}
1603
1604/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1605/// statement to exit to its outer synthesized loop.
1606///
1607Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1608  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1609    return S;
1610  // replace break with goto __break_label
1611  std::string buf;
1612
1613  SourceLocation startLoc = S->getBeginLoc();
1614  buf = "goto __break_label_";
1615  buf += utostr(ObjCBcLabelNo.back());
1616  ReplaceText(startLoc, strlen("break"), buf);
1617
1618  return nullptr;
1619}
1620
1621void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1622                                          SourceLocation Loc,
1623                                          std::string &LineString) {
1624  if (Loc.isFileID() && GenerateLineInfo) {
1625    LineString += "\n#line ";
1626    PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1627    LineString += utostr(PLoc.getLine());
1628    LineString += " \"";
1629    LineString += Lexer::Stringify(PLoc.getFilename());
1630    LineString += "\"\n";
1631  }
1632}
1633
1634/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1635/// statement to continue with its inner synthesized loop.
1636///
1637Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1638  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1639    return S;
1640  // replace continue with goto __continue_label
1641  std::string buf;
1642
1643  SourceLocation startLoc = S->getBeginLoc();
1644  buf = "goto __continue_label_";
1645  buf += utostr(ObjCBcLabelNo.back());
1646  ReplaceText(startLoc, strlen("continue"), buf);
1647
1648  return nullptr;
1649}
1650
1651/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1652///  It rewrites:
1653/// for ( type elem in collection) { stmts; }
1654
1655/// Into:
1656/// {
1657///   type elem;
1658///   struct __objcFastEnumerationState enumState = { 0 };
1659///   id __rw_items[16];
1660///   id l_collection = (id)collection;
1661///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1662///                                       objects:__rw_items count:16];
1663/// if (limit) {
1664///   unsigned long startMutations = *enumState.mutationsPtr;
1665///   do {
1666///        unsigned long counter = 0;
1667///        do {
1668///             if (startMutations != *enumState.mutationsPtr)
1669///               objc_enumerationMutation(l_collection);
1670///             elem = (type)enumState.itemsPtr[counter++];
1671///             stmts;
1672///             __continue_label: ;
1673///        } while (counter < limit);
1674///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1675///                                  objects:__rw_items count:16]));
1676///   elem = nil;
1677///   __break_label: ;
1678///  }
1679///  else
1680///       elem = nil;
1681///  }
1682///
1683Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1684                                                SourceLocation OrigEnd) {
1685  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1686  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1687         "ObjCForCollectionStmt Statement stack mismatch");
1688  assert(!ObjCBcLabelNo.empty() &&
1689         "ObjCForCollectionStmt - Label No stack empty");
1690
1691  SourceLocation startLoc = S->getBeginLoc();
1692  const char *startBuf = SM->getCharacterData(startLoc);
1693  StringRef elementName;
1694  std::string elementTypeAsString;
1695  std::string buf;
1696  // line directive first.
1697  SourceLocation ForEachLoc = S->getForLoc();
1698  ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1699  buf += "{\n\t";
1700  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1701    // type elem;
1702    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1703    QualType ElementType = cast<ValueDecl>(D)->getType();
1704    if (ElementType->isObjCQualifiedIdType() ||
1705        ElementType->isObjCQualifiedInterfaceType())
1706      // Simply use 'id' for all qualified types.
1707      elementTypeAsString = "id";
1708    else
1709      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1710    buf += elementTypeAsString;
1711    buf += " ";
1712    elementName = D->getName();
1713    buf += elementName;
1714    buf += ";\n\t";
1715  }
1716  else {
1717    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1718    elementName = DR->getDecl()->getName();
1719    ValueDecl *VD = DR->getDecl();
1720    if (VD->getType()->isObjCQualifiedIdType() ||
1721        VD->getType()->isObjCQualifiedInterfaceType())
1722      // Simply use 'id' for all qualified types.
1723      elementTypeAsString = "id";
1724    else
1725      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1726  }
1727
1728  // struct __objcFastEnumerationState enumState = { 0 };
1729  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1730  // id __rw_items[16];
1731  buf += "id __rw_items[16];\n\t";
1732  // id l_collection = (id)
1733  buf += "id l_collection = (id)";
1734  // Find start location of 'collection' the hard way!
1735  const char *startCollectionBuf = startBuf;
1736  startCollectionBuf += 3;  // skip 'for'
1737  startCollectionBuf = strchr(startCollectionBuf, '(');
1738  startCollectionBuf++; // skip '('
1739  // find 'in' and skip it.
1740  while (*startCollectionBuf != ' ' ||
1741         *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1742         (*(startCollectionBuf+3) != ' ' &&
1743          *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1744    startCollectionBuf++;
1745  startCollectionBuf += 3;
1746
1747  // Replace: "for (type element in" with string constructed thus far.
1748  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1749  // Replace ')' in for '(' type elem in collection ')' with ';'
1750  SourceLocation rightParenLoc = S->getRParenLoc();
1751  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1752  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1753  buf = ";\n\t";
1754
1755  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1756  //                                   objects:__rw_items count:16];
1757  // which is synthesized into:
1758  // NSUInteger limit =
1759  // ((NSUInteger (*)
1760  //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1761  //  (void *)objc_msgSend)((id)l_collection,
1762  //                        sel_registerName(
1763  //                          "countByEnumeratingWithState:objects:count:"),
1764  //                        (struct __objcFastEnumerationState *)&state,
1765  //                        (id *)__rw_items, (NSUInteger)16);
1766  buf += "_WIN_NSUInteger limit =\n\t\t";
1767  SynthCountByEnumWithState(buf);
1768  buf += ";\n\t";
1769  /// if (limit) {
1770  ///   unsigned long startMutations = *enumState.mutationsPtr;
1771  ///   do {
1772  ///        unsigned long counter = 0;
1773  ///        do {
1774  ///             if (startMutations != *enumState.mutationsPtr)
1775  ///               objc_enumerationMutation(l_collection);
1776  ///             elem = (type)enumState.itemsPtr[counter++];
1777  buf += "if (limit) {\n\t";
1778  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1779  buf += "do {\n\t\t";
1780  buf += "unsigned long counter = 0;\n\t\t";
1781  buf += "do {\n\t\t\t";
1782  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1783  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1784  buf += elementName;
1785  buf += " = (";
1786  buf += elementTypeAsString;
1787  buf += ")enumState.itemsPtr[counter++];";
1788  // Replace ')' in for '(' type elem in collection ')' with all of these.
1789  ReplaceText(lparenLoc, 1, buf);
1790
1791  ///            __continue_label: ;
1792  ///        } while (counter < limit);
1793  ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1794  ///                                  objects:__rw_items count:16]));
1795  ///   elem = nil;
1796  ///   __break_label: ;
1797  ///  }
1798  ///  else
1799  ///       elem = nil;
1800  ///  }
1801  ///
1802  buf = ";\n\t";
1803  buf += "__continue_label_";
1804  buf += utostr(ObjCBcLabelNo.back());
1805  buf += ": ;";
1806  buf += "\n\t\t";
1807  buf += "} while (counter < limit);\n\t";
1808  buf += "} while ((limit = ";
1809  SynthCountByEnumWithState(buf);
1810  buf += "));\n\t";
1811  buf += elementName;
1812  buf += " = ((";
1813  buf += elementTypeAsString;
1814  buf += ")0);\n\t";
1815  buf += "__break_label_";
1816  buf += utostr(ObjCBcLabelNo.back());
1817  buf += ": ;\n\t";
1818  buf += "}\n\t";
1819  buf += "else\n\t\t";
1820  buf += elementName;
1821  buf += " = ((";
1822  buf += elementTypeAsString;
1823  buf += ")0);\n\t";
1824  buf += "}\n";
1825
1826  // Insert all these *after* the statement body.
1827  // FIXME: If this should support Obj-C++, support CXXTryStmt
1828  if (isa<CompoundStmt>(S->getBody())) {
1829    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1830    InsertText(endBodyLoc, buf);
1831  } else {
1832    /* Need to treat single statements specially. For example:
1833     *
1834     *     for (A *a in b) if (stuff()) break;
1835     *     for (A *a in b) xxxyy;
1836     *
1837     * The following code simply scans ahead to the semi to find the actual end.
1838     */
1839    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1840    const char *semiBuf = strchr(stmtBuf, ';');
1841    assert(semiBuf && "Can't find ';'");
1842    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1843    InsertText(endBodyLoc, buf);
1844  }
1845  Stmts.pop_back();
1846  ObjCBcLabelNo.pop_back();
1847  return nullptr;
1848}
1849
1850static void Write_RethrowObject(std::string &buf) {
1851  buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1852  buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1853  buf += "\tid rethrow;\n";
1854  buf += "\t} _fin_force_rethow(_rethrow);";
1855}
1856
1857/// RewriteObjCSynchronizedStmt -
1858/// This routine rewrites @synchronized(expr) stmt;
1859/// into:
1860/// objc_sync_enter(expr);
1861/// @try stmt @finally { objc_sync_exit(expr); }
1862///
1863Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1864  // Get the start location and compute the semi location.
1865  SourceLocation startLoc = S->getBeginLoc();
1866  const char *startBuf = SM->getCharacterData(startLoc);
1867
1868  assert((*startBuf == '@') && "bogus @synchronized location");
1869
1870  std::string buf;
1871  SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1872  ConvertSourceLocationToLineDirective(SynchLoc, buf);
1873  buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1874
1875  const char *lparenBuf = startBuf;
1876  while (*lparenBuf != '(') lparenBuf++;
1877  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1878
1879  buf = "; objc_sync_enter(_sync_obj);\n";
1880  buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1881  buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1882  buf += "\n\tid sync_exit;";
1883  buf += "\n\t} _sync_exit(_sync_obj);\n";
1884
1885  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1886  // the sync expression is typically a message expression that's already
1887  // been rewritten! (which implies the SourceLocation's are invalid).
1888  SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1889  const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1890  while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1891  RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1892
1893  SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1894  const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1895  assert (*LBraceLocBuf == '{');
1896  ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1897
1898  SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1899  assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1900         "bogus @synchronized block");
1901
1902  buf = "} catch (id e) {_rethrow = e;}\n";
1903  Write_RethrowObject(buf);
1904  buf += "}\n";
1905  buf += "}\n";
1906
1907  ReplaceText(startRBraceLoc, 1, buf);
1908
1909  return nullptr;
1910}
1911
1912void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1913{
1914  // Perform a bottom up traversal of all children.
1915  for (Stmt *SubStmt : S->children())
1916    if (SubStmt)
1917      WarnAboutReturnGotoStmts(SubStmt);
1918
1919  if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1920    Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1921                 TryFinallyContainsReturnDiag);
1922  }
1923}
1924
1925Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1926  SourceLocation startLoc = S->getAtLoc();
1927  ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1928  ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1929              "{ __AtAutoreleasePool __autoreleasepool; ");
1930
1931  return nullptr;
1932}
1933
1934Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1935  ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1936  bool noCatch = S->getNumCatchStmts() == 0;
1937  std::string buf;
1938  SourceLocation TryLocation = S->getAtTryLoc();
1939  ConvertSourceLocationToLineDirective(TryLocation, buf);
1940
1941  if (finalStmt) {
1942    if (noCatch)
1943      buf += "{ id volatile _rethrow = 0;\n";
1944    else {
1945      buf += "{ id volatile _rethrow = 0;\ntry {\n";
1946    }
1947  }
1948  // Get the start location and compute the semi location.
1949  SourceLocation startLoc = S->getBeginLoc();
1950  const char *startBuf = SM->getCharacterData(startLoc);
1951
1952  assert((*startBuf == '@') && "bogus @try location");
1953  if (finalStmt)
1954    ReplaceText(startLoc, 1, buf);
1955  else
1956    // @try -> try
1957    ReplaceText(startLoc, 1, "");
1958
1959  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1960    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1961    VarDecl *catchDecl = Catch->getCatchParamDecl();
1962
1963    startLoc = Catch->getBeginLoc();
1964    bool AtRemoved = false;
1965    if (catchDecl) {
1966      QualType t = catchDecl->getType();
1967      if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1968        // Should be a pointer to a class.
1969        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1970        if (IDecl) {
1971          std::string Result;
1972          ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1973
1974          startBuf = SM->getCharacterData(startLoc);
1975          assert((*startBuf == '@') && "bogus @catch location");
1976          SourceLocation rParenLoc = Catch->getRParenLoc();
1977          const char *rParenBuf = SM->getCharacterData(rParenLoc);
1978
1979          // _objc_exc_Foo *_e as argument to catch.
1980          Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1981          Result += " *_"; Result += catchDecl->getNameAsString();
1982          Result += ")";
1983          ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1984          // Foo *e = (Foo *)_e;
1985          Result.clear();
1986          Result = "{ ";
1987          Result += IDecl->getNameAsString();
1988          Result += " *"; Result += catchDecl->getNameAsString();
1989          Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1990          Result += "_"; Result += catchDecl->getNameAsString();
1991
1992          Result += "; ";
1993          SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1994          ReplaceText(lBraceLoc, 1, Result);
1995          AtRemoved = true;
1996        }
1997      }
1998    }
1999    if (!AtRemoved)
2000      // @catch -> catch
2001      ReplaceText(startLoc, 1, "");
2002
2003  }
2004  if (finalStmt) {
2005    buf.clear();
2006    SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2007
2008    if (noCatch) {
2009      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2010      buf += "catch (id e) {_rethrow = e;}\n";
2011    }
2012    else {
2013      buf += "}\n";
2014      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2015      buf += "catch (id e) {_rethrow = e;}\n";
2016    }
2017
2018    SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2019    ReplaceText(startFinalLoc, 8, buf);
2020    Stmt *body = finalStmt->getFinallyBody();
2021    SourceLocation startFinalBodyLoc = body->getBeginLoc();
2022    buf.clear();
2023    Write_RethrowObject(buf);
2024    ReplaceText(startFinalBodyLoc, 1, buf);
2025
2026    SourceLocation endFinalBodyLoc = body->getEndLoc();
2027    ReplaceText(endFinalBodyLoc, 1, "}\n}");
2028    // Now check for any return/continue/go statements within the @try.
2029    WarnAboutReturnGotoStmts(S->getTryBody());
2030  }
2031
2032  return nullptr;
2033}
2034
2035// This can't be done with ReplaceStmt(S, ThrowExpr), since
2036// the throw expression is typically a message expression that's already
2037// been rewritten! (which implies the SourceLocation's are invalid).
2038Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2039  // Get the start location and compute the semi location.
2040  SourceLocation startLoc = S->getBeginLoc();
2041  const char *startBuf = SM->getCharacterData(startLoc);
2042
2043  assert((*startBuf == '@') && "bogus @throw location");
2044
2045  std::string buf;
2046  /* void objc_exception_throw(id) __attribute__((noreturn)); */
2047  if (S->getThrowExpr())
2048    buf = "objc_exception_throw(";
2049  else
2050    buf = "throw";
2051
2052  // handle "@  throw" correctly.
2053  const char *wBuf = strchr(startBuf, 'w');
2054  assert((*wBuf == 'w') && "@throw: can't find 'w'");
2055  ReplaceText(startLoc, wBuf-startBuf+1, buf);
2056
2057  SourceLocation endLoc = S->getEndLoc();
2058  const char *endBuf = SM->getCharacterData(endLoc);
2059  const char *semiBuf = strchr(endBuf, ';');
2060  assert((*semiBuf == ';') && "@throw: can't find ';'");
2061  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2062  if (S->getThrowExpr())
2063    ReplaceText(semiLoc, 1, ");");
2064  return nullptr;
2065}
2066
2067Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2068  // Create a new string expression.
2069  std::string StrEncoding;
2070  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2071  Expr *Replacement = getStringLiteral(StrEncoding);
2072  ReplaceStmt(Exp, Replacement);
2073
2074  // Replace this subexpr in the parent.
2075  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2076  return Replacement;
2077}
2078
2079Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2080  if (!SelGetUidFunctionDecl)
2081    SynthSelGetUidFunctionDecl();
2082  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2083  // Create a call to sel_registerName("selName").
2084  SmallVector<Expr*, 8> SelExprs;
2085  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2086  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2087                                                  SelExprs);
2088  ReplaceStmt(Exp, SelExp);
2089  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2090  return SelExp;
2091}
2092
2093CallExpr *
2094RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2095                                                ArrayRef<Expr *> Args,
2096                                                SourceLocation StartLoc,
2097                                                SourceLocation EndLoc) {
2098  // Get the type, we will need to reference it in a couple spots.
2099  QualType msgSendType = FD->getType();
2100
2101  // Create a reference to the objc_msgSend() declaration.
2102  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2103                                               VK_LValue, SourceLocation());
2104
2105  // Now, we cast the reference to a pointer to the objc_msgSend type.
2106  QualType pToFunc = Context->getPointerType(msgSendType);
2107  ImplicitCastExpr *ICE =
2108    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2109                             DRE, nullptr, VK_RValue);
2110
2111  const auto *FT = msgSendType->castAs<FunctionType>();
2112  CallExpr *Exp = CallExpr::Create(
2113      *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2114  return Exp;
2115}
2116
2117static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2118                                const char *&startRef, const char *&endRef) {
2119  while (startBuf < endBuf) {
2120    if (*startBuf == '<')
2121      startRef = startBuf; // mark the start.
2122    if (*startBuf == '>') {
2123      if (startRef && *startRef == '<') {
2124        endRef = startBuf; // mark the end.
2125        return true;
2126      }
2127      return false;
2128    }
2129    startBuf++;
2130  }
2131  return false;
2132}
2133
2134static void scanToNextArgument(const char *&argRef) {
2135  int angle = 0;
2136  while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2137    if (*argRef == '<')
2138      angle++;
2139    else if (*argRef == '>')
2140      angle--;
2141    argRef++;
2142  }
2143  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2144}
2145
2146bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2147  if (T->isObjCQualifiedIdType())
2148    return true;
2149  if (const PointerType *PT = T->getAs<PointerType>()) {
2150    if (PT->getPointeeType()->isObjCQualifiedIdType())
2151      return true;
2152  }
2153  if (T->isObjCObjectPointerType()) {
2154    T = T->getPointeeType();
2155    return T->isObjCQualifiedInterfaceType();
2156  }
2157  if (T->isArrayType()) {
2158    QualType ElemTy = Context->getBaseElementType(T);
2159    return needToScanForQualifiers(ElemTy);
2160  }
2161  return false;
2162}
2163
2164void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2165  QualType Type = E->getType();
2166  if (needToScanForQualifiers(Type)) {
2167    SourceLocation Loc, EndLoc;
2168
2169    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2170      Loc = ECE->getLParenLoc();
2171      EndLoc = ECE->getRParenLoc();
2172    } else {
2173      Loc = E->getBeginLoc();
2174      EndLoc = E->getEndLoc();
2175    }
2176    // This will defend against trying to rewrite synthesized expressions.
2177    if (Loc.isInvalid() || EndLoc.isInvalid())
2178      return;
2179
2180    const char *startBuf = SM->getCharacterData(Loc);
2181    const char *endBuf = SM->getCharacterData(EndLoc);
2182    const char *startRef = nullptr, *endRef = nullptr;
2183    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184      // Get the locations of the startRef, endRef.
2185      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2186      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2187      // Comment out the protocol references.
2188      InsertText(LessLoc, "/*");
2189      InsertText(GreaterLoc, "*/");
2190    }
2191  }
2192}
2193
2194void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2195  SourceLocation Loc;
2196  QualType Type;
2197  const FunctionProtoType *proto = nullptr;
2198  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2199    Loc = VD->getLocation();
2200    Type = VD->getType();
2201  }
2202  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2203    Loc = FD->getLocation();
2204    // Check for ObjC 'id' and class types that have been adorned with protocol
2205    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2206    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2207    assert(funcType && "missing function type");
2208    proto = dyn_cast<FunctionProtoType>(funcType);
2209    if (!proto)
2210      return;
2211    Type = proto->getReturnType();
2212  }
2213  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2214    Loc = FD->getLocation();
2215    Type = FD->getType();
2216  }
2217  else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2218    Loc = TD->getLocation();
2219    Type = TD->getUnderlyingType();
2220  }
2221  else
2222    return;
2223
2224  if (needToScanForQualifiers(Type)) {
2225    // Since types are unique, we need to scan the buffer.
2226
2227    const char *endBuf = SM->getCharacterData(Loc);
2228    const char *startBuf = endBuf;
2229    while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2230      startBuf--; // scan backward (from the decl location) for return type.
2231    const char *startRef = nullptr, *endRef = nullptr;
2232    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233      // Get the locations of the startRef, endRef.
2234      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2235      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2236      // Comment out the protocol references.
2237      InsertText(LessLoc, "/*");
2238      InsertText(GreaterLoc, "*/");
2239    }
2240  }
2241  if (!proto)
2242      return; // most likely, was a variable
2243  // Now check arguments.
2244  const char *startBuf = SM->getCharacterData(Loc);
2245  const char *startFuncBuf = startBuf;
2246  for (unsigned i = 0; i < proto->getNumParams(); i++) {
2247    if (needToScanForQualifiers(proto->getParamType(i))) {
2248      // Since types are unique, we need to scan the buffer.
2249
2250      const char *endBuf = startBuf;
2251      // scan forward (from the decl location) for argument types.
2252      scanToNextArgument(endBuf);
2253      const char *startRef = nullptr, *endRef = nullptr;
2254      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255        // Get the locations of the startRef, endRef.
2256        SourceLocation LessLoc =
2257          Loc.getLocWithOffset(startRef-startFuncBuf);
2258        SourceLocation GreaterLoc =
2259          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2260        // Comment out the protocol references.
2261        InsertText(LessLoc, "/*");
2262        InsertText(GreaterLoc, "*/");
2263      }
2264      startBuf = ++endBuf;
2265    }
2266    else {
2267      // If the function name is derived from a macro expansion, then the
2268      // argument buffer will not follow the name. Need to speak with Chris.
2269      while (*startBuf && *startBuf != ')' && *startBuf != ',')
2270        startBuf++; // scan forward (from the decl location) for argument types.
2271      startBuf++;
2272    }
2273  }
2274}
2275
2276void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2277  QualType QT = ND->getType();
2278  const Type* TypePtr = QT->getAs<Type>();
2279  if (!isa<TypeOfExprType>(TypePtr))
2280    return;
2281  while (isa<TypeOfExprType>(TypePtr)) {
2282    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2283    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2284    TypePtr = QT->getAs<Type>();
2285  }
2286  // FIXME. This will not work for multiple declarators; as in:
2287  // __typeof__(a) b,c,d;
2288  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2289  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2290  const char *startBuf = SM->getCharacterData(DeclLoc);
2291  if (ND->getInit()) {
2292    std::string Name(ND->getNameAsString());
2293    TypeAsString += " " + Name + " = ";
2294    Expr *E = ND->getInit();
2295    SourceLocation startLoc;
2296    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2297      startLoc = ECE->getLParenLoc();
2298    else
2299      startLoc = E->getBeginLoc();
2300    startLoc = SM->getExpansionLoc(startLoc);
2301    const char *endBuf = SM->getCharacterData(startLoc);
2302    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2303  }
2304  else {
2305    SourceLocation X = ND->getEndLoc();
2306    X = SM->getExpansionLoc(X);
2307    const char *endBuf = SM->getCharacterData(X);
2308    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2309  }
2310}
2311
2312// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2313void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2314  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2315  SmallVector<QualType, 16> ArgTys;
2316  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2317  QualType getFuncType =
2318    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2319  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2320                                               SourceLocation(),
2321                                               SourceLocation(),
2322                                               SelGetUidIdent, getFuncType,
2323                                               nullptr, SC_Extern);
2324}
2325
2326void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2327  // declared in <objc/objc.h>
2328  if (FD->getIdentifier() &&
2329      FD->getName() == "sel_registerName") {
2330    SelGetUidFunctionDecl = FD;
2331    return;
2332  }
2333  RewriteObjCQualifiedInterfaceTypes(FD);
2334}
2335
2336void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2337  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2338  const char *argPtr = TypeString.c_str();
2339  if (!strchr(argPtr, '^')) {
2340    Str += TypeString;
2341    return;
2342  }
2343  while (*argPtr) {
2344    Str += (*argPtr == '^' ? '*' : *argPtr);
2345    argPtr++;
2346  }
2347}
2348
2349// FIXME. Consolidate this routine with RewriteBlockPointerType.
2350void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2351                                                  ValueDecl *VD) {
2352  QualType Type = VD->getType();
2353  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2354  const char *argPtr = TypeString.c_str();
2355  int paren = 0;
2356  while (*argPtr) {
2357    switch (*argPtr) {
2358      case '(':
2359        Str += *argPtr;
2360        paren++;
2361        break;
2362      case ')':
2363        Str += *argPtr;
2364        paren--;
2365        break;
2366      case '^':
2367        Str += '*';
2368        if (paren == 1)
2369          Str += VD->getNameAsString();
2370        break;
2371      default:
2372        Str += *argPtr;
2373        break;
2374    }
2375    argPtr++;
2376  }
2377}
2378
2379void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2380  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2381  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2382  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2383  if (!proto)
2384    return;
2385  QualType Type = proto->getReturnType();
2386  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2387  FdStr += " ";
2388  FdStr += FD->getName();
2389  FdStr +=  "(";
2390  unsigned numArgs = proto->getNumParams();
2391  for (unsigned i = 0; i < numArgs; i++) {
2392    QualType ArgType = proto->getParamType(i);
2393  RewriteBlockPointerType(FdStr, ArgType);
2394  if (i+1 < numArgs)
2395    FdStr += ", ";
2396  }
2397  if (FD->isVariadic()) {
2398    FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
2399  }
2400  else
2401    FdStr +=  ");\n";
2402  InsertText(FunLocStart, FdStr);
2403}
2404
2405// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2406void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2407  if (SuperConstructorFunctionDecl)
2408    return;
2409  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2410  SmallVector<QualType, 16> ArgTys;
2411  QualType argT = Context->getObjCIdType();
2412  assert(!argT.isNull() && "Can't find 'id' type");
2413  ArgTys.push_back(argT);
2414  ArgTys.push_back(argT);
2415  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2416                                               ArgTys);
2417  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2418                                                     SourceLocation(),
2419                                                     SourceLocation(),
2420                                                     msgSendIdent, msgSendType,
2421                                                     nullptr, SC_Extern);
2422}
2423
2424// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2425void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2426  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2427  SmallVector<QualType, 16> ArgTys;
2428  QualType argT = Context->getObjCIdType();
2429  assert(!argT.isNull() && "Can't find 'id' type");
2430  ArgTys.push_back(argT);
2431  argT = Context->getObjCSelType();
2432  assert(!argT.isNull() && "Can't find 'SEL' type");
2433  ArgTys.push_back(argT);
2434  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2435                                               ArgTys, /*variadic=*/true);
2436  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2437                                             SourceLocation(),
2438                                             SourceLocation(),
2439                                             msgSendIdent, msgSendType, nullptr,
2440                                             SC_Extern);
2441}
2442
2443// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2444void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2445  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2446  SmallVector<QualType, 2> ArgTys;
2447  ArgTys.push_back(Context->VoidTy);
2448  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2449                                               ArgTys, /*variadic=*/true);
2450  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2451                                                  SourceLocation(),
2452                                                  SourceLocation(),
2453                                                  msgSendIdent, msgSendType,
2454                                                  nullptr, SC_Extern);
2455}
2456
2457// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2459  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2460  SmallVector<QualType, 16> ArgTys;
2461  QualType argT = Context->getObjCIdType();
2462  assert(!argT.isNull() && "Can't find 'id' type");
2463  ArgTys.push_back(argT);
2464  argT = Context->getObjCSelType();
2465  assert(!argT.isNull() && "Can't find 'SEL' type");
2466  ArgTys.push_back(argT);
2467  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2468                                               ArgTys, /*variadic=*/true);
2469  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2470                                                  SourceLocation(),
2471                                                  SourceLocation(),
2472                                                  msgSendIdent, msgSendType,
2473                                                  nullptr, SC_Extern);
2474}
2475
2476// SynthMsgSendSuperStretFunctionDecl -
2477// id objc_msgSendSuper_stret(void);
2478void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2479  IdentifierInfo *msgSendIdent =
2480    &Context->Idents.get("objc_msgSendSuper_stret");
2481  SmallVector<QualType, 2> ArgTys;
2482  ArgTys.push_back(Context->VoidTy);
2483  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2484                                               ArgTys, /*variadic=*/true);
2485  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2486                                                       SourceLocation(),
2487                                                       SourceLocation(),
2488                                                       msgSendIdent,
2489                                                       msgSendType, nullptr,
2490                                                       SC_Extern);
2491}
2492
2493// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2494void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2495  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2496  SmallVector<QualType, 16> ArgTys;
2497  QualType argT = Context->getObjCIdType();
2498  assert(!argT.isNull() && "Can't find 'id' type");
2499  ArgTys.push_back(argT);
2500  argT = Context->getObjCSelType();
2501  assert(!argT.isNull() && "Can't find 'SEL' type");
2502  ArgTys.push_back(argT);
2503  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2504                                               ArgTys, /*variadic=*/true);
2505  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2506                                                  SourceLocation(),
2507                                                  SourceLocation(),
2508                                                  msgSendIdent, msgSendType,
2509                                                  nullptr, SC_Extern);
2510}
2511
2512// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2513void RewriteModernObjC::SynthGetClassFunctionDecl() {
2514  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2515  SmallVector<QualType, 16> ArgTys;
2516  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2517  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2518                                                ArgTys);
2519  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2520                                              SourceLocation(),
2521                                              SourceLocation(),
2522                                              getClassIdent, getClassType,
2523                                              nullptr, SC_Extern);
2524}
2525
2526// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2527void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2528  IdentifierInfo *getSuperClassIdent =
2529    &Context->Idents.get("class_getSuperclass");
2530  SmallVector<QualType, 16> ArgTys;
2531  ArgTys.push_back(Context->getObjCClassType());
2532  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2533                                                ArgTys);
2534  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2535                                                   SourceLocation(),
2536                                                   SourceLocation(),
2537                                                   getSuperClassIdent,
2538                                                   getClassType, nullptr,
2539                                                   SC_Extern);
2540}
2541
2542// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2543void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2544  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2545  SmallVector<QualType, 16> ArgTys;
2546  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2547  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2548                                                ArgTys);
2549  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2550                                                  SourceLocation(),
2551                                                  SourceLocation(),
2552                                                  getClassIdent, getClassType,
2553                                                  nullptr, SC_Extern);
2554}
2555
2556Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2557  assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2558  QualType strType = getConstantStringStructType();
2559
2560  std::string S = "__NSConstantStringImpl_";
2561
2562  std::string tmpName = InFileName;
2563  unsigned i;
2564  for (i=0; i < tmpName.length(); i++) {
2565    char c = tmpName.at(i);
2566    // replace any non-alphanumeric characters with '_'.
2567    if (!isAlphanumeric(c))
2568      tmpName[i] = '_';
2569  }
2570  S += tmpName;
2571  S += "_";
2572  S += utostr(NumObjCStringLiterals++);
2573
2574  Preamble += "static __NSConstantStringImpl " + S;
2575  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2576  Preamble += "0x000007c8,"; // utf8_str
2577  // The pretty printer for StringLiteral handles escape characters properly.
2578  std::string prettyBufS;
2579  llvm::raw_string_ostream prettyBuf(prettyBufS);
2580  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2581  Preamble += prettyBuf.str();
2582  Preamble += ",";
2583  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2584
2585  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2586                                   SourceLocation(), &Context->Idents.get(S),
2587                                   strType, nullptr, SC_Static);
2588  DeclRefExpr *DRE = new (Context)
2589      DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2590  Expr *Unop = UnaryOperator::Create(
2591      const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2592      Context->getPointerType(DRE->getType()), VK_RValue, OK_Ordinary,
2593      SourceLocation(), false, FPOptionsOverride());
2594  // cast to NSConstantString *
2595  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2596                                            CK_CPointerToObjCPointerCast, Unop);
2597  ReplaceStmt(Exp, cast);
2598  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2599  return cast;
2600}
2601
2602Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2603  unsigned IntSize =
2604    static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2605
2606  Expr *FlagExp = IntegerLiteral::Create(*Context,
2607                                         llvm::APInt(IntSize, Exp->getValue()),
2608                                         Context->IntTy, Exp->getLocation());
2609  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2610                                            CK_BitCast, FlagExp);
2611  ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2612                                          cast);
2613  ReplaceStmt(Exp, PE);
2614  return PE;
2615}
2616
2617Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2618  // synthesize declaration of helper functions needed in this routine.
2619  if (!SelGetUidFunctionDecl)
2620    SynthSelGetUidFunctionDecl();
2621  // use objc_msgSend() for all.
2622  if (!MsgSendFunctionDecl)
2623    SynthMsgSendFunctionDecl();
2624  if (!GetClassFunctionDecl)
2625    SynthGetClassFunctionDecl();
2626
2627  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2628  SourceLocation StartLoc = Exp->getBeginLoc();
2629  SourceLocation EndLoc = Exp->getEndLoc();
2630
2631  // Synthesize a call to objc_msgSend().
2632  SmallVector<Expr*, 4> MsgExprs;
2633  SmallVector<Expr*, 4> ClsExprs;
2634
2635  // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2636  ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2637  ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2638
2639  IdentifierInfo *clsName = BoxingClass->getIdentifier();
2640  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2641  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2642                                               StartLoc, EndLoc);
2643  MsgExprs.push_back(Cls);
2644
2645  // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2646  // it will be the 2nd argument.
2647  SmallVector<Expr*, 4> SelExprs;
2648  SelExprs.push_back(
2649      getStringLiteral(BoxingMethod->getSelector().getAsString()));
2650  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2651                                                  SelExprs, StartLoc, EndLoc);
2652  MsgExprs.push_back(SelExp);
2653
2654  // User provided sub-expression is the 3rd, and last, argument.
2655  Expr *subExpr  = Exp->getSubExpr();
2656  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2657    QualType type = ICE->getType();
2658    const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2659    CastKind CK = CK_BitCast;
2660    if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2661      CK = CK_IntegralToBoolean;
2662    subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2663  }
2664  MsgExprs.push_back(subExpr);
2665
2666  SmallVector<QualType, 4> ArgTypes;
2667  ArgTypes.push_back(Context->getObjCClassType());
2668  ArgTypes.push_back(Context->getObjCSelType());
2669  for (const auto PI : BoxingMethod->parameters())
2670    ArgTypes.push_back(PI->getType());
2671
2672  QualType returnType = Exp->getType();
2673  // Get the type, we will need to reference it in a couple spots.
2674  QualType msgSendType = MsgSendFlavor->getType();
2675
2676  // Create a reference to the objc_msgSend() declaration.
2677  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2678      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2679
2680  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2681      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2682
2683  // Now do the "normal" pointer to function cast.
2684  QualType castType =
2685    getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2686  castType = Context->getPointerType(castType);
2687  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2688                                  cast);
2689
2690  // Don't forget the parens to enforce the proper binding.
2691  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2692
2693  auto *FT = msgSendType->castAs<FunctionType>();
2694  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2695                                  VK_RValue, EndLoc);
2696  ReplaceStmt(Exp, CE);
2697  return CE;
2698}
2699
2700Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2701  // synthesize declaration of helper functions needed in this routine.
2702  if (!SelGetUidFunctionDecl)
2703    SynthSelGetUidFunctionDecl();
2704  // use objc_msgSend() for all.
2705  if (!MsgSendFunctionDecl)
2706    SynthMsgSendFunctionDecl();
2707  if (!GetClassFunctionDecl)
2708    SynthGetClassFunctionDecl();
2709
2710  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2711  SourceLocation StartLoc = Exp->getBeginLoc();
2712  SourceLocation EndLoc = Exp->getEndLoc();
2713
2714  // Build the expression: __NSContainer_literal(int, ...).arr
2715  QualType IntQT = Context->IntTy;
2716  QualType NSArrayFType =
2717    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2718  std::string NSArrayFName("__NSContainer_literal");
2719  FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2720  DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2721      *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
2722
2723  SmallVector<Expr*, 16> InitExprs;
2724  unsigned NumElements = Exp->getNumElements();
2725  unsigned UnsignedIntSize =
2726    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2727  Expr *count = IntegerLiteral::Create(*Context,
2728                                       llvm::APInt(UnsignedIntSize, NumElements),
2729                                       Context->UnsignedIntTy, SourceLocation());
2730  InitExprs.push_back(count);
2731  for (unsigned i = 0; i < NumElements; i++)
2732    InitExprs.push_back(Exp->getElement(i));
2733  Expr *NSArrayCallExpr =
2734      CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2735                       SourceLocation());
2736
2737  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2738                                    SourceLocation(),
2739                                    &Context->Idents.get("arr"),
2740                                    Context->getPointerType(Context->VoidPtrTy),
2741                                    nullptr, /*BitWidth=*/nullptr,
2742                                    /*Mutable=*/true, ICIS_NoInit);
2743  MemberExpr *ArrayLiteralME =
2744      MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2745                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2746  QualType ConstIdT = Context->getObjCIdType().withConst();
2747  CStyleCastExpr * ArrayLiteralObjects =
2748    NoTypeInfoCStyleCastExpr(Context,
2749                             Context->getPointerType(ConstIdT),
2750                             CK_BitCast,
2751                             ArrayLiteralME);
2752
2753  // Synthesize a call to objc_msgSend().
2754  SmallVector<Expr*, 32> MsgExprs;
2755  SmallVector<Expr*, 4> ClsExprs;
2756  QualType expType = Exp->getType();
2757
2758  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2759  ObjCInterfaceDecl *Class =
2760    expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2761
2762  IdentifierInfo *clsName = Class->getIdentifier();
2763  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2764  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2765                                               StartLoc, EndLoc);
2766  MsgExprs.push_back(Cls);
2767
2768  // Create a call to sel_registerName("arrayWithObjects:count:").
2769  // it will be the 2nd argument.
2770  SmallVector<Expr*, 4> SelExprs;
2771  ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2772  SelExprs.push_back(
2773      getStringLiteral(ArrayMethod->getSelector().getAsString()));
2774  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2775                                                  SelExprs, StartLoc, EndLoc);
2776  MsgExprs.push_back(SelExp);
2777
2778  // (const id [])objects
2779  MsgExprs.push_back(ArrayLiteralObjects);
2780
2781  // (NSUInteger)cnt
2782  Expr *cnt = IntegerLiteral::Create(*Context,
2783                                     llvm::APInt(UnsignedIntSize, NumElements),
2784                                     Context->UnsignedIntTy, SourceLocation());
2785  MsgExprs.push_back(cnt);
2786
2787  SmallVector<QualType, 4> ArgTypes;
2788  ArgTypes.push_back(Context->getObjCClassType());
2789  ArgTypes.push_back(Context->getObjCSelType());
2790  for (const auto *PI : ArrayMethod->parameters())
2791    ArgTypes.push_back(PI->getType());
2792
2793  QualType returnType = Exp->getType();
2794  // Get the type, we will need to reference it in a couple spots.
2795  QualType msgSendType = MsgSendFlavor->getType();
2796
2797  // Create a reference to the objc_msgSend() declaration.
2798  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2799      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2800
2801  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2802      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2803
2804  // Now do the "normal" pointer to function cast.
2805  QualType castType =
2806  getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2807  castType = Context->getPointerType(castType);
2808  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2809                                  cast);
2810
2811  // Don't forget the parens to enforce the proper binding.
2812  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2813
2814  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2815  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2816                                  VK_RValue, EndLoc);
2817  ReplaceStmt(Exp, CE);
2818  return CE;
2819}
2820
2821Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2822  // synthesize declaration of helper functions needed in this routine.
2823  if (!SelGetUidFunctionDecl)
2824    SynthSelGetUidFunctionDecl();
2825  // use objc_msgSend() for all.
2826  if (!MsgSendFunctionDecl)
2827    SynthMsgSendFunctionDecl();
2828  if (!GetClassFunctionDecl)
2829    SynthGetClassFunctionDecl();
2830
2831  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2832  SourceLocation StartLoc = Exp->getBeginLoc();
2833  SourceLocation EndLoc = Exp->getEndLoc();
2834
2835  // Build the expression: __NSContainer_literal(int, ...).arr
2836  QualType IntQT = Context->IntTy;
2837  QualType NSDictFType =
2838    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2839  std::string NSDictFName("__NSContainer_literal");
2840  FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2841  DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2842      *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
2843
2844  SmallVector<Expr*, 16> KeyExprs;
2845  SmallVector<Expr*, 16> ValueExprs;
2846
2847  unsigned NumElements = Exp->getNumElements();
2848  unsigned UnsignedIntSize =
2849    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2850  Expr *count = IntegerLiteral::Create(*Context,
2851                                       llvm::APInt(UnsignedIntSize, NumElements),
2852                                       Context->UnsignedIntTy, SourceLocation());
2853  KeyExprs.push_back(count);
2854  ValueExprs.push_back(count);
2855  for (unsigned i = 0; i < NumElements; i++) {
2856    ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2857    KeyExprs.push_back(Element.Key);
2858    ValueExprs.push_back(Element.Value);
2859  }
2860
2861  // (const id [])objects
2862  Expr *NSValueCallExpr =
2863      CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2864                       SourceLocation());
2865
2866  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2867                                       SourceLocation(),
2868                                       &Context->Idents.get("arr"),
2869                                       Context->getPointerType(Context->VoidPtrTy),
2870                                       nullptr, /*BitWidth=*/nullptr,
2871                                       /*Mutable=*/true, ICIS_NoInit);
2872  MemberExpr *DictLiteralValueME =
2873      MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2874                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2875  QualType ConstIdT = Context->getObjCIdType().withConst();
2876  CStyleCastExpr * DictValueObjects =
2877    NoTypeInfoCStyleCastExpr(Context,
2878                             Context->getPointerType(ConstIdT),
2879                             CK_BitCast,
2880                             DictLiteralValueME);
2881  // (const id <NSCopying> [])keys
2882  Expr *NSKeyCallExpr = CallExpr::Create(
2883      *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
2884
2885  MemberExpr *DictLiteralKeyME =
2886      MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2887                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2888
2889  CStyleCastExpr * DictKeyObjects =
2890    NoTypeInfoCStyleCastExpr(Context,
2891                             Context->getPointerType(ConstIdT),
2892                             CK_BitCast,
2893                             DictLiteralKeyME);
2894
2895  // Synthesize a call to objc_msgSend().
2896  SmallVector<Expr*, 32> MsgExprs;
2897  SmallVector<Expr*, 4> ClsExprs;
2898  QualType expType = Exp->getType();
2899
2900  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2901  ObjCInterfaceDecl *Class =
2902  expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2903
2904  IdentifierInfo *clsName = Class->getIdentifier();
2905  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2906  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2907                                               StartLoc, EndLoc);
2908  MsgExprs.push_back(Cls);
2909
2910  // Create a call to sel_registerName("arrayWithObjects:count:").
2911  // it will be the 2nd argument.
2912  SmallVector<Expr*, 4> SelExprs;
2913  ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2914  SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2915  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2916                                                  SelExprs, StartLoc, EndLoc);
2917  MsgExprs.push_back(SelExp);
2918
2919  // (const id [])objects
2920  MsgExprs.push_back(DictValueObjects);
2921
2922  // (const id <NSCopying> [])keys
2923  MsgExprs.push_back(DictKeyObjects);
2924
2925  // (NSUInteger)cnt
2926  Expr *cnt = IntegerLiteral::Create(*Context,
2927                                     llvm::APInt(UnsignedIntSize, NumElements),
2928                                     Context->UnsignedIntTy, SourceLocation());
2929  MsgExprs.push_back(cnt);
2930
2931  SmallVector<QualType, 8> ArgTypes;
2932  ArgTypes.push_back(Context->getObjCClassType());
2933  ArgTypes.push_back(Context->getObjCSelType());
2934  for (const auto *PI : DictMethod->parameters()) {
2935    QualType T = PI->getType();
2936    if (const PointerType* PT = T->getAs<PointerType>()) {
2937      QualType PointeeTy = PT->getPointeeType();
2938      convertToUnqualifiedObjCType(PointeeTy);
2939      T = Context->getPointerType(PointeeTy);
2940    }
2941    ArgTypes.push_back(T);
2942  }
2943
2944  QualType returnType = Exp->getType();
2945  // Get the type, we will need to reference it in a couple spots.
2946  QualType msgSendType = MsgSendFlavor->getType();
2947
2948  // Create a reference to the objc_msgSend() declaration.
2949  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2950      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2951
2952  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2953      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2954
2955  // Now do the "normal" pointer to function cast.
2956  QualType castType =
2957  getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2958  castType = Context->getPointerType(castType);
2959  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2960                                  cast);
2961
2962  // Don't forget the parens to enforce the proper binding.
2963  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2964
2965  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2966  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2967                                  VK_RValue, EndLoc);
2968  ReplaceStmt(Exp, CE);
2969  return CE;
2970}
2971
2972// struct __rw_objc_super {
2973//   struct objc_object *object; struct objc_object *superClass;
2974// };
2975QualType RewriteModernObjC::getSuperStructType() {
2976  if (!SuperStructDecl) {
2977    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2978                                         SourceLocation(), SourceLocation(),
2979                                         &Context->Idents.get("__rw_objc_super"));
2980    QualType FieldTypes[2];
2981
2982    // struct objc_object *object;
2983    FieldTypes[0] = Context->getObjCIdType();
2984    // struct objc_object *superClass;
2985    FieldTypes[1] = Context->getObjCIdType();
2986
2987    // Create fields
2988    for (unsigned i = 0; i < 2; ++i) {
2989      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2990                                                 SourceLocation(),
2991                                                 SourceLocation(), nullptr,
2992                                                 FieldTypes[i], nullptr,
2993                                                 /*BitWidth=*/nullptr,
2994                                                 /*Mutable=*/false,
2995                                                 ICIS_NoInit));
2996    }
2997
2998    SuperStructDecl->completeDefinition();
2999  }
3000  return Context->getTagDeclType(SuperStructDecl);
3001}
3002
3003QualType RewriteModernObjC::getConstantStringStructType() {
3004  if (!ConstantStringDecl) {
3005    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3006                                            SourceLocation(), SourceLocation(),
3007                         &Context->Idents.get("__NSConstantStringImpl"));
3008    QualType FieldTypes[4];
3009
3010    // struct objc_object *receiver;
3011    FieldTypes[0] = Context->getObjCIdType();
3012    // int flags;
3013    FieldTypes[1] = Context->IntTy;
3014    // char *str;
3015    FieldTypes[2] = Context->getPointerType(Context->CharTy);
3016    // long length;
3017    FieldTypes[3] = Context->LongTy;
3018
3019    // Create fields
3020    for (unsigned i = 0; i < 4; ++i) {
3021      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3022                                                    ConstantStringDecl,
3023                                                    SourceLocation(),
3024                                                    SourceLocation(), nullptr,
3025                                                    FieldTypes[i], nullptr,
3026                                                    /*BitWidth=*/nullptr,
3027                                                    /*Mutable=*/true,
3028                                                    ICIS_NoInit));
3029    }
3030
3031    ConstantStringDecl->completeDefinition();
3032  }
3033  return Context->getTagDeclType(ConstantStringDecl);
3034}
3035
3036/// getFunctionSourceLocation - returns start location of a function
3037/// definition. Complication arises when function has declared as
3038/// extern "C" or extern "C" {...}
3039static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3040                                                 FunctionDecl *FD) {
3041  if (FD->isExternC()  && !FD->isMain()) {
3042    const DeclContext *DC = FD->getDeclContext();
3043    if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3044      // if it is extern "C" {...}, return function decl's own location.
3045      if (!LSD->getRBraceLoc().isValid())
3046        return LSD->getExternLoc();
3047  }
3048  if (FD->getStorageClass() != SC_None)
3049    R.RewriteBlockLiteralFunctionDecl(FD);
3050  return FD->getTypeSpecStartLoc();
3051}
3052
3053void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3054
3055  SourceLocation Location = D->getLocation();
3056
3057  if (Location.isFileID() && GenerateLineInfo) {
3058    std::string LineString("\n#line ");
3059    PresumedLoc PLoc = SM->getPresumedLoc(Location);
3060    LineString += utostr(PLoc.getLine());
3061    LineString += " \"";
3062    LineString += Lexer::Stringify(PLoc.getFilename());
3063    if (isa<ObjCMethodDecl>(D))
3064      LineString += "\"";
3065    else LineString += "\"\n";
3066
3067    Location = D->getBeginLoc();
3068    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3069      if (FD->isExternC()  && !FD->isMain()) {
3070        const DeclContext *DC = FD->getDeclContext();
3071        if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3072          // if it is extern "C" {...}, return function decl's own location.
3073          if (!LSD->getRBraceLoc().isValid())
3074            Location = LSD->getExternLoc();
3075      }
3076    }
3077    InsertText(Location, LineString);
3078  }
3079}
3080
3081/// SynthMsgSendStretCallExpr - This routine translates message expression
3082/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3083/// nil check on receiver must be performed before calling objc_msgSend_stret.
3084/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3085/// msgSendType - function type of objc_msgSend_stret(...)
3086/// returnType - Result type of the method being synthesized.
3087/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3088/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3089/// starting with receiver.
3090/// Method - Method being rewritten.
3091Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3092                                                 QualType returnType,
3093                                                 SmallVectorImpl<QualType> &ArgTypes,
3094                                                 SmallVectorImpl<Expr*> &MsgExprs,
3095                                                 ObjCMethodDecl *Method) {
3096  // Now do the "normal" pointer to function cast.
3097  QualType FuncType = getSimpleFunctionType(
3098      returnType, ArgTypes, Method ? Method->isVariadic() : false);
3099  QualType castType = Context->getPointerType(FuncType);
3100
3101  // build type for containing the objc_msgSend_stret object.
3102  static unsigned stretCount=0;
3103  std::string name = "__Stret"; name += utostr(stretCount);
3104  std::string str =
3105    "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3106  str += "namespace {\n";
3107  str += "struct "; str += name;
3108  str += " {\n\t";
3109  str += name;
3110  str += "(id receiver, SEL sel";
3111  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3112    std::string ArgName = "arg"; ArgName += utostr(i);
3113    ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3114    str += ", "; str += ArgName;
3115  }
3116  // could be vararg.
3117  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3118    std::string ArgName = "arg"; ArgName += utostr(i);
3119    MsgExprs[i]->getType().getAsStringInternal(ArgName,
3120                                               Context->getPrintingPolicy());
3121    str += ", "; str += ArgName;
3122  }
3123
3124  str += ") {\n";
3125  str += "\t  unsigned size = sizeof(";
3126  str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3127
3128  str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3129
3130  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3131  str += ")(void *)objc_msgSend)(receiver, sel";
3132  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3133    str += ", arg"; str += utostr(i);
3134  }
3135  // could be vararg.
3136  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3137    str += ", arg"; str += utostr(i);
3138  }
3139  str+= ");\n";
3140
3141  str += "\t  else if (receiver == 0)\n";
3142  str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3143  str += "\t  else\n";
3144
3145  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3146  str += ")(void *)objc_msgSend_stret)(receiver, sel";
3147  for (unsigned i = 2; i < ArgTypes.size(); i++) {
3148    str += ", arg"; str += utostr(i);
3149  }
3150  // could be vararg.
3151  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3152    str += ", arg"; str += utostr(i);
3153  }
3154  str += ");\n";
3155
3156  str += "\t}\n";
3157  str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3158  str += " s;\n";
3159  str += "};\n};\n\n";
3160  SourceLocation FunLocStart;
3161  if (CurFunctionDef)
3162    FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3163  else {
3164    assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3165    FunLocStart = CurMethodDef->getBeginLoc();
3166  }
3167
3168  InsertText(FunLocStart, str);
3169  ++stretCount;
3170
3171  // AST for __Stretn(receiver, args).s;
3172  IdentifierInfo *ID = &Context->Idents.get(name);
3173  FunctionDecl *FD =
3174      FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3175                           ID, FuncType, nullptr, SC_Extern, false, false);
3176  DeclRefExpr *DRE = new (Context)
3177      DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3178  CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3179                                    VK_LValue, SourceLocation());
3180
3181  FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3182                                    SourceLocation(),
3183                                    &Context->Idents.get("s"),
3184                                    returnType, nullptr,
3185                                    /*BitWidth=*/nullptr,
3186                                    /*Mutable=*/true, ICIS_NoInit);
3187  MemberExpr *ME = MemberExpr::CreateImplicit(
3188      *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3189
3190  return ME;
3191}
3192
3193Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3194                                    SourceLocation StartLoc,
3195                                    SourceLocation EndLoc) {
3196  if (!SelGetUidFunctionDecl)
3197    SynthSelGetUidFunctionDecl();
3198  if (!MsgSendFunctionDecl)
3199    SynthMsgSendFunctionDecl();
3200  if (!MsgSendSuperFunctionDecl)
3201    SynthMsgSendSuperFunctionDecl();
3202  if (!MsgSendStretFunctionDecl)
3203    SynthMsgSendStretFunctionDecl();
3204  if (!MsgSendSuperStretFunctionDecl)
3205    SynthMsgSendSuperStretFunctionDecl();
3206  if (!MsgSendFpretFunctionDecl)
3207    SynthMsgSendFpretFunctionDecl();
3208  if (!GetClassFunctionDecl)
3209    SynthGetClassFunctionDecl();
3210  if (!GetSuperClassFunctionDecl)
3211    SynthGetSuperClassFunctionDecl();
3212  if (!GetMetaClassFunctionDecl)
3213    SynthGetMetaClassFunctionDecl();
3214
3215  // default to objc_msgSend().
3216  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3217  // May need to use objc_msgSend_stret() as well.
3218  FunctionDecl *MsgSendStretFlavor = nullptr;
3219  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3220    QualType resultType = mDecl->getReturnType();
3221    if (resultType->isRecordType())
3222      MsgSendStretFlavor = MsgSendStretFunctionDecl;
3223    else if (resultType->isRealFloatingType())
3224      MsgSendFlavor = MsgSendFpretFunctionDecl;
3225  }
3226
3227  // Synthesize a call to objc_msgSend().
3228  SmallVector<Expr*, 8> MsgExprs;
3229  switch (Exp->getReceiverKind()) {
3230  case ObjCMessageExpr::SuperClass: {
3231    MsgSendFlavor = MsgSendSuperFunctionDecl;
3232    if (MsgSendStretFlavor)
3233      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3234    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3235
3236    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3237
3238    SmallVector<Expr*, 4> InitExprs;
3239
3240    // set the receiver to self, the first argument to all methods.
3241    InitExprs.push_back(
3242      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3243                               CK_BitCast,
3244                   new (Context) DeclRefExpr(*Context,
3245                                             CurMethodDef->getSelfDecl(),
3246                                             false,
3247                                             Context->getObjCIdType(),
3248                                             VK_RValue,
3249                                             SourceLocation()))
3250                        ); // set the 'receiver'.
3251
3252    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3253    SmallVector<Expr*, 8> ClsExprs;
3254    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3255    // (Class)objc_getClass("CurrentClass")
3256    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3257                                                 ClsExprs, StartLoc, EndLoc);
3258    ClsExprs.clear();
3259    ClsExprs.push_back(Cls);
3260    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3261                                       StartLoc, EndLoc);
3262
3263    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3264    // To turn off a warning, type-cast to 'id'
3265    InitExprs.push_back( // set 'super class', using class_getSuperclass().
3266                        NoTypeInfoCStyleCastExpr(Context,
3267                                                 Context->getObjCIdType(),
3268                                                 CK_BitCast, Cls));
3269    // struct __rw_objc_super
3270    QualType superType = getSuperStructType();
3271    Expr *SuperRep;
3272
3273    if (LangOpts.MicrosoftExt) {
3274      SynthSuperConstructorFunctionDecl();
3275      // Simulate a constructor call...
3276      DeclRefExpr *DRE = new (Context)
3277          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3278                      VK_LValue, SourceLocation());
3279      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3280                                  VK_LValue, SourceLocation());
3281      // The code for super is a little tricky to prevent collision with
3282      // the structure definition in the header. The rewriter has it's own
3283      // internal definition (__rw_objc_super) that is uses. This is why
3284      // we need the cast below. For example:
3285      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3286      //
3287      SuperRep = UnaryOperator::Create(
3288          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3289          Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
3290          SourceLocation(), false, FPOptionsOverride());
3291      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3292                                          Context->getPointerType(superType),
3293                                          CK_BitCast, SuperRep);
3294    } else {
3295      // (struct __rw_objc_super) { <exprs from above> }
3296      InitListExpr *ILE =
3297        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3298                                   SourceLocation());
3299      TypeSourceInfo *superTInfo
3300        = Context->getTrivialTypeSourceInfo(superType);
3301      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3302                                                   superType, VK_LValue,
3303                                                   ILE, false);
3304      // struct __rw_objc_super *
3305      SuperRep = UnaryOperator::Create(
3306          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3307          Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
3308          SourceLocation(), false, FPOptionsOverride());
3309    }
3310    MsgExprs.push_back(SuperRep);
3311    break;
3312  }
3313
3314  case ObjCMessageExpr::Class: {
3315    SmallVector<Expr*, 8> ClsExprs;
3316    ObjCInterfaceDecl *Class
3317      = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3318    IdentifierInfo *clsName = Class->getIdentifier();
3319    ClsExprs.push_back(getStringLiteral(clsName->getName()));
3320    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3321                                                 StartLoc, EndLoc);
3322    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3323                                                 Context->getObjCIdType(),
3324                                                 CK_BitCast, Cls);
3325    MsgExprs.push_back(ArgExpr);
3326    break;
3327  }
3328
3329  case ObjCMessageExpr::SuperInstance:{
3330    MsgSendFlavor = MsgSendSuperFunctionDecl;
3331    if (MsgSendStretFlavor)
3332      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3333    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3334    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3335    SmallVector<Expr*, 4> InitExprs;
3336
3337    InitExprs.push_back(
3338      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3339                               CK_BitCast,
3340                   new (Context) DeclRefExpr(*Context,
3341                                             CurMethodDef->getSelfDecl(),
3342                                             false,
3343                                             Context->getObjCIdType(),
3344                                             VK_RValue, SourceLocation()))
3345                        ); // set the 'receiver'.
3346
3347    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3348    SmallVector<Expr*, 8> ClsExprs;
3349    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3350    // (Class)objc_getClass("CurrentClass")
3351    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3352                                                 StartLoc, EndLoc);
3353    ClsExprs.clear();
3354    ClsExprs.push_back(Cls);
3355    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3356                                       StartLoc, EndLoc);
3357
3358    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3359    // To turn off a warning, type-cast to 'id'
3360    InitExprs.push_back(
3361      // set 'super class', using class_getSuperclass().
3362      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3363                               CK_BitCast, Cls));
3364    // struct __rw_objc_super
3365    QualType superType = getSuperStructType();
3366    Expr *SuperRep;
3367
3368    if (LangOpts.MicrosoftExt) {
3369      SynthSuperConstructorFunctionDecl();
3370      // Simulate a constructor call...
3371      DeclRefExpr *DRE = new (Context)
3372          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3373                      VK_LValue, SourceLocation());
3374      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3375                                  VK_LValue, SourceLocation());
3376      // The code for super is a little tricky to prevent collision with
3377      // the structure definition in the header. The rewriter has it's own
3378      // internal definition (__rw_objc_super) that is uses. This is why
3379      // we need the cast below. For example:
3380      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3381      //
3382      SuperRep = UnaryOperator::Create(
3383          const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3384          Context->getPointerType(SuperRep->getType()), VK_RValue, OK_Ordinary,
3385          SourceLocation(), false, FPOptionsOverride());
3386      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3387                               Context->getPointerType(superType),
3388                               CK_BitCast, SuperRep);
3389    } else {
3390      // (struct __rw_objc_super) { <exprs from above> }
3391      InitListExpr *ILE =
3392        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3393                                   SourceLocation());
3394      TypeSourceInfo *superTInfo
3395        = Context->getTrivialTypeSourceInfo(superType);
3396      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3397                                                   superType, VK_RValue, ILE,
3398                                                   false);
3399    }
3400    MsgExprs.push_back(SuperRep);
3401    break;
3402  }
3403
3404  case ObjCMessageExpr::Instance: {
3405    // Remove all type-casts because it may contain objc-style types; e.g.
3406    // Foo<Proto> *.
3407    Expr *recExpr = Exp->getInstanceReceiver();
3408    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3409      recExpr = CE->getSubExpr();
3410    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3411                    ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3412                                     ? CK_BlockPointerToObjCPointerCast
3413                                     : CK_CPointerToObjCPointerCast;
3414
3415    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3416                                       CK, recExpr);
3417    MsgExprs.push_back(recExpr);
3418    break;
3419  }
3420  }
3421
3422  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3423  SmallVector<Expr*, 8> SelExprs;
3424  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3425  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3426                                                  SelExprs, StartLoc, EndLoc);
3427  MsgExprs.push_back(SelExp);
3428
3429  // Now push any user supplied arguments.
3430  for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3431    Expr *userExpr = Exp->getArg(i);
3432    // Make all implicit casts explicit...ICE comes in handy:-)
3433    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3434      // Reuse the ICE type, it is exactly what the doctor ordered.
3435      QualType type = ICE->getType();
3436      if (needToScanForQualifiers(type))
3437        type = Context->getObjCIdType();
3438      // Make sure we convert "type (^)(...)" to "type (*)(...)".
3439      (void)convertBlockPointerToFunctionPointer(type);
3440      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3441      CastKind CK;
3442      if (SubExpr->getType()->isIntegralType(*Context) &&
3443          type->isBooleanType()) {
3444        CK = CK_IntegralToBoolean;
3445      } else if (type->isObjCObjectPointerType()) {
3446        if (SubExpr->getType()->isBlockPointerType()) {
3447          CK = CK_BlockPointerToObjCPointerCast;
3448        } else if (SubExpr->getType()->isPointerType()) {
3449          CK = CK_CPointerToObjCPointerCast;
3450        } else {
3451          CK = CK_BitCast;
3452        }
3453      } else {
3454        CK = CK_BitCast;
3455      }
3456
3457      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3458    }
3459    // Make id<P...> cast into an 'id' cast.
3460    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3461      if (CE->getType()->isObjCQualifiedIdType()) {
3462        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3463          userExpr = CE->getSubExpr();
3464        CastKind CK;
3465        if (userExpr->getType()->isIntegralType(*Context)) {
3466          CK = CK_IntegralToPointer;
3467        } else if (userExpr->getType()->isBlockPointerType()) {
3468          CK = CK_BlockPointerToObjCPointerCast;
3469        } else if (userExpr->getType()->isPointerType()) {
3470          CK = CK_CPointerToObjCPointerCast;
3471        } else {
3472          CK = CK_BitCast;
3473        }
3474        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3475                                            CK, userExpr);
3476      }
3477    }
3478    MsgExprs.push_back(userExpr);
3479    // We've transferred the ownership to MsgExprs. For now, we *don't* null
3480    // out the argument in the original expression (since we aren't deleting
3481    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3482    //Exp->setArg(i, 0);
3483  }
3484  // Generate the funky cast.
3485  CastExpr *cast;
3486  SmallVector<QualType, 8> ArgTypes;
3487  QualType returnType;
3488
3489  // Push 'id' and 'SEL', the 2 implicit arguments.
3490  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3491    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3492  else
3493    ArgTypes.push_back(Context->getObjCIdType());
3494  ArgTypes.push_back(Context->getObjCSelType());
3495  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3496    // Push any user argument types.
3497    for (const auto *PI : OMD->parameters()) {
3498      QualType t = PI->getType()->isObjCQualifiedIdType()
3499                     ? Context->getObjCIdType()
3500                     : PI->getType();
3501      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3502      (void)convertBlockPointerToFunctionPointer(t);
3503      ArgTypes.push_back(t);
3504    }
3505    returnType = Exp->getType();
3506    convertToUnqualifiedObjCType(returnType);
3507    (void)convertBlockPointerToFunctionPointer(returnType);
3508  } else {
3509    returnType = Context->getObjCIdType();
3510  }
3511  // Get the type, we will need to reference it in a couple spots.
3512  QualType msgSendType = MsgSendFlavor->getType();
3513
3514  // Create a reference to the objc_msgSend() declaration.
3515  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3516      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3517
3518  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3519  // If we don't do this cast, we get the following bizarre warning/note:
3520  // xx.m:13: warning: function called through a non-compatible type
3521  // xx.m:13: note: if this code is reached, the program will abort
3522  cast = NoTypeInfoCStyleCastExpr(Context,
3523                                  Context->getPointerType(Context->VoidTy),
3524                                  CK_BitCast, DRE);
3525
3526  // Now do the "normal" pointer to function cast.
3527  // If we don't have a method decl, force a variadic cast.
3528  const ObjCMethodDecl *MD = Exp->getMethodDecl();
3529  QualType castType =
3530    getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3531  castType = Context->getPointerType(castType);
3532  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3533                                  cast);
3534
3535  // Don't forget the parens to enforce the proper binding.
3536  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3537
3538  const FunctionType *FT = msgSendType->castAs<FunctionType>();
3539  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3540                                  VK_RValue, EndLoc);
3541  Stmt *ReplacingStmt = CE;
3542  if (MsgSendStretFlavor) {
3543    // We have the method which returns a struct/union. Must also generate
3544    // call to objc_msgSend_stret and hang both varieties on a conditional
3545    // expression which dictate which one to envoke depending on size of
3546    // method's return type.
3547
3548    Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3549                                           returnType,
3550                                           ArgTypes, MsgExprs,
3551                                           Exp->getMethodDecl());
3552    ReplacingStmt = STCE;
3553  }
3554  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3555  return ReplacingStmt;
3556}
3557
3558Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3559  Stmt *ReplacingStmt =
3560      SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3561
3562  // Now do the actual rewrite.
3563  ReplaceStmt(Exp, ReplacingStmt);
3564
3565  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3566  return ReplacingStmt;
3567}
3568
3569// typedef struct objc_object Protocol;
3570QualType RewriteModernObjC::getProtocolType() {
3571  if (!ProtocolTypeDecl) {
3572    TypeSourceInfo *TInfo
3573      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3574    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3575                                           SourceLocation(), SourceLocation(),
3576                                           &Context->Idents.get("Protocol"),
3577                                           TInfo);
3578  }
3579  return Context->getTypeDeclType(ProtocolTypeDecl);
3580}
3581
3582/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3583/// a synthesized/forward data reference (to the protocol's metadata).
3584/// The forward references (and metadata) are generated in
3585/// RewriteModernObjC::HandleTranslationUnit().
3586Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3587  std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3588                      Exp->getProtocol()->getNameAsString();
3589  IdentifierInfo *ID = &Context->Idents.get(Name);
3590  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3591                                SourceLocation(), ID, getProtocolType(),
3592                                nullptr, SC_Extern);
3593  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3594      *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3595  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3596      Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3597  ReplaceStmt(Exp, castExpr);
3598  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3599  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3600  return castExpr;
3601}
3602
3603/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3604/// is defined inside an objective-c class. If so, it returns true.
3605bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3606                                                TagDecl *Tag,
3607                                                bool &IsNamedDefinition) {
3608  if (!IDecl)
3609    return false;
3610  SourceLocation TagLocation;
3611  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3612    RD = RD->getDefinition();
3613    if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3614      return false;
3615    IsNamedDefinition = true;
3616    TagLocation = RD->getLocation();
3617    return Context->getSourceManager().isBeforeInTranslationUnit(
3618                                          IDecl->getLocation(), TagLocation);
3619  }
3620  if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3621    if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3622      return false;
3623    IsNamedDefinition = true;
3624    TagLocation = ED->getLocation();
3625    return Context->getSourceManager().isBeforeInTranslationUnit(
3626                                          IDecl->getLocation(), TagLocation);
3627  }
3628  return false;
3629}
3630
3631/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3632/// It handles elaborated types, as well as enum types in the process.
3633bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3634                                                 std::string &Result) {
3635  if (isa<TypedefType>(Type)) {
3636    Result += "\t";
3637    return false;
3638  }
3639
3640  if (Type->isArrayType()) {
3641    QualType ElemTy = Context->getBaseElementType(Type);
3642    return RewriteObjCFieldDeclType(ElemTy, Result);
3643  }
3644  else if (Type->isRecordType()) {
3645    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3646    if (RD->isCompleteDefinition()) {
3647      if (RD->isStruct())
3648        Result += "\n\tstruct ";
3649      else if (RD->isUnion())
3650        Result += "\n\tunion ";
3651      else
3652        assert(false && "class not allowed as an ivar type");
3653
3654      Result += RD->getName();
3655      if (GlobalDefinedTags.count(RD)) {
3656        // struct/union is defined globally, use it.
3657        Result += " ";
3658        return true;
3659      }
3660      Result += " {\n";
3661      for (auto *FD : RD->fields())
3662        RewriteObjCFieldDecl(FD, Result);
3663      Result += "\t} ";
3664      return true;
3665    }
3666  }
3667  else if (Type->isEnumeralType()) {
3668    EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3669    if (ED->isCompleteDefinition()) {
3670      Result += "\n\tenum ";
3671      Result += ED->getName();
3672      if (GlobalDefinedTags.count(ED)) {
3673        // Enum is globall defined, use it.
3674        Result += " ";
3675        return true;
3676      }
3677
3678      Result += " {\n";
3679      for (const auto *EC : ED->enumerators()) {
3680        Result += "\t"; Result += EC->getName(); Result += " = ";
3681        llvm::APSInt Val = EC->getInitVal();
3682        Result += Val.toString(10);
3683        Result += ",\n";
3684      }
3685      Result += "\t} ";
3686      return true;
3687    }
3688  }
3689
3690  Result += "\t";
3691  convertObjCTypeToCStyleType(Type);
3692  return false;
3693}
3694
3695
3696/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3697/// It handles elaborated types, as well as enum types in the process.
3698void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3699                                             std::string &Result) {
3700  QualType Type = fieldDecl->getType();
3701  std::string Name = fieldDecl->getNameAsString();
3702
3703  bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3704  if (!EleboratedType)
3705    Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3706  Result += Name;
3707  if (fieldDecl->isBitField()) {
3708    Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3709  }
3710  else if (EleboratedType && Type->isArrayType()) {
3711    const ArrayType *AT = Context->getAsArrayType(Type);
3712    do {
3713      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3714        Result += "[";
3715        llvm::APInt Dim = CAT->getSize();
3716        Result += utostr(Dim.getZExtValue());
3717        Result += "]";
3718      }
3719      AT = Context->getAsArrayType(AT->getElementType());
3720    } while (AT);
3721  }
3722
3723  Result += ";\n";
3724}
3725
3726/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3727/// named aggregate types into the input buffer.
3728void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3729                                             std::string &Result) {
3730  QualType Type = fieldDecl->getType();
3731  if (isa<TypedefType>(Type))
3732    return;
3733  if (Type->isArrayType())
3734    Type = Context->getBaseElementType(Type);
3735
3736  auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3737
3738  TagDecl *TD = nullptr;
3739  if (Type->isRecordType()) {
3740    TD = Type->castAs<RecordType>()->getDecl();
3741  }
3742  else if (Type->isEnumeralType()) {
3743    TD = Type->castAs<EnumType>()->getDecl();
3744  }
3745
3746  if (TD) {
3747    if (GlobalDefinedTags.count(TD))
3748      return;
3749
3750    bool IsNamedDefinition = false;
3751    if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3752      RewriteObjCFieldDeclType(Type, Result);
3753      Result += ";";
3754    }
3755    if (IsNamedDefinition)
3756      GlobalDefinedTags.insert(TD);
3757  }
3758}
3759
3760unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3761  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3762  if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3763    return IvarGroupNumber[IV];
3764  }
3765  unsigned GroupNo = 0;
3766  SmallVector<const ObjCIvarDecl *, 8> IVars;
3767  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3768       IVD; IVD = IVD->getNextIvar())
3769    IVars.push_back(IVD);
3770
3771  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3772    if (IVars[i]->isBitField()) {
3773      IvarGroupNumber[IVars[i++]] = ++GroupNo;
3774      while (i < e && IVars[i]->isBitField())
3775        IvarGroupNumber[IVars[i++]] = GroupNo;
3776      if (i < e)
3777        --i;
3778    }
3779
3780  ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3781  return IvarGroupNumber[IV];
3782}
3783
3784QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3785                              ObjCIvarDecl *IV,
3786                              SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3787  std::string StructTagName;
3788  ObjCIvarBitfieldGroupType(IV, StructTagName);
3789  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3790                                      Context->getTranslationUnitDecl(),
3791                                      SourceLocation(), SourceLocation(),
3792                                      &Context->Idents.get(StructTagName));
3793  for (unsigned i=0, e = IVars.size(); i < e; i++) {
3794    ObjCIvarDecl *Ivar = IVars[i];
3795    RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3796                                  &Context->Idents.get(Ivar->getName()),
3797                                  Ivar->getType(),
3798                                  nullptr, /*Expr *BW */Ivar->getBitWidth(),
3799                                  false, ICIS_NoInit));
3800  }
3801  RD->completeDefinition();
3802  return Context->getTagDeclType(RD);
3803}
3804
3805QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3806  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3807  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3808  std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3809  if (GroupRecordType.count(tuple))
3810    return GroupRecordType[tuple];
3811
3812  SmallVector<ObjCIvarDecl *, 8> IVars;
3813  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3814       IVD; IVD = IVD->getNextIvar()) {
3815    if (IVD->isBitField())
3816      IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3817    else {
3818      if (!IVars.empty()) {
3819        unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3820        // Generate the struct type for this group of bitfield ivars.
3821        GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3822          SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3823        IVars.clear();
3824      }
3825    }
3826  }
3827  if (!IVars.empty()) {
3828    // Do the last one.
3829    unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3830    GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3831      SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3832  }
3833  QualType RetQT = GroupRecordType[tuple];
3834  assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3835
3836  return RetQT;
3837}
3838
3839/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3840/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3841void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3842                                                  std::string &Result) {
3843  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3844  Result += CDecl->getName();
3845  Result += "__GRBF_";
3846  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3847  Result += utostr(GroupNo);
3848}
3849
3850/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3851/// Name of the struct would be: classname__T_n where n is the group number for
3852/// this ivar.
3853void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3854                                                  std::string &Result) {
3855  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3856  Result += CDecl->getName();
3857  Result += "__T_";
3858  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3859  Result += utostr(GroupNo);
3860}
3861
3862/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3863/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3864/// this ivar.
3865void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3866                                                    std::string &Result) {
3867  Result += "OBJC_IVAR_$_";
3868  ObjCIvarBitfieldGroupDecl(IV, Result);
3869}
3870
3871#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3872      while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3873        ++IX; \
3874      if (IX < ENDIX) \
3875        --IX; \
3876}
3877
3878/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3879/// an objective-c class with ivars.
3880void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3881                                               std::string &Result) {
3882  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3883  assert(CDecl->getName() != "" &&
3884         "Name missing in SynthesizeObjCInternalStruct");
3885  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3886  SmallVector<ObjCIvarDecl *, 8> IVars;
3887  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3888       IVD; IVD = IVD->getNextIvar())
3889    IVars.push_back(IVD);
3890
3891  SourceLocation LocStart = CDecl->getBeginLoc();
3892  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3893
3894  const char *startBuf = SM->getCharacterData(LocStart);
3895  const char *endBuf = SM->getCharacterData(LocEnd);
3896
3897  // If no ivars and no root or if its root, directly or indirectly,
3898  // have no ivars (thus not synthesized) then no need to synthesize this class.
3899  if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3900      (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3901    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3902    ReplaceText(LocStart, endBuf-startBuf, Result);
3903    return;
3904  }
3905
3906  // Insert named struct/union definitions inside class to
3907  // outer scope. This follows semantics of locally defined
3908  // struct/unions in objective-c classes.
3909  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3910    RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3911
3912  // Insert named structs which are syntheized to group ivar bitfields
3913  // to outer scope as well.
3914  for (unsigned i = 0, e = IVars.size(); i < e; i++)
3915    if (IVars[i]->isBitField()) {
3916      ObjCIvarDecl *IV = IVars[i];
3917      QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3918      RewriteObjCFieldDeclType(QT, Result);
3919      Result += ";";
3920      // skip over ivar bitfields in this group.
3921      SKIP_BITFIELDS(i , e, IVars);
3922    }
3923
3924  Result += "\nstruct ";
3925  Result += CDecl->getNameAsString();
3926  Result += "_IMPL {\n";
3927
3928  if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3929    Result += "\tstruct "; Result += RCDecl->getNameAsString();
3930    Result += "_IMPL "; Result += RCDecl->getNameAsString();
3931    Result += "_IVARS;\n";
3932  }
3933
3934  for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3935    if (IVars[i]->isBitField()) {
3936      ObjCIvarDecl *IV = IVars[i];
3937      Result += "\tstruct ";
3938      ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3939      ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3940      // skip over ivar bitfields in this group.
3941      SKIP_BITFIELDS(i , e, IVars);
3942    }
3943    else
3944      RewriteObjCFieldDecl(IVars[i], Result);
3945  }
3946
3947  Result += "};\n";
3948  endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3949  ReplaceText(LocStart, endBuf-startBuf, Result);
3950  // Mark this struct as having been generated.
3951  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3952    llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3953}
3954
3955/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3956/// have been referenced in an ivar access expression.
3957void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3958                                                  std::string &Result) {
3959  // write out ivar offset symbols which have been referenced in an ivar
3960  // access expression.
3961  llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3962
3963  if (Ivars.empty())
3964    return;
3965
3966  llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3967  for (ObjCIvarDecl *IvarDecl : Ivars) {
3968    const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3969    unsigned GroupNo = 0;
3970    if (IvarDecl->isBitField()) {
3971      GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3972      if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3973        continue;
3974    }
3975    Result += "\n";
3976    if (LangOpts.MicrosoftExt)
3977      Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3978    Result += "extern \"C\" ";
3979    if (LangOpts.MicrosoftExt &&
3980        IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3981        IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3982        Result += "__declspec(dllimport) ";
3983
3984    Result += "unsigned long ";
3985    if (IvarDecl->isBitField()) {
3986      ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3987      GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3988    }
3989    else
3990      WriteInternalIvarName(CDecl, IvarDecl, Result);
3991    Result += ";";
3992  }
3993}
3994
3995//===----------------------------------------------------------------------===//
3996// Meta Data Emission
3997//===----------------------------------------------------------------------===//
3998
3999/// RewriteImplementations - This routine rewrites all method implementations
4000/// and emits meta-data.
4001
4002void RewriteModernObjC::RewriteImplementations() {
4003  int ClsDefCount = ClassImplementation.size();
4004  int CatDefCount = CategoryImplementation.size();
4005
4006  // Rewrite implemented methods
4007  for (int i = 0; i < ClsDefCount; i++) {
4008    ObjCImplementationDecl *OIMP = ClassImplementation[i];
4009    ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4010    if (CDecl->isImplicitInterfaceDecl())
4011      assert(false &&
4012             "Legacy implicit interface rewriting not supported in moder abi");
4013    RewriteImplementationDecl(OIMP);
4014  }
4015
4016  for (int i = 0; i < CatDefCount; i++) {
4017    ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4018    ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4019    if (CDecl->isImplicitInterfaceDecl())
4020      assert(false &&
4021             "Legacy implicit interface rewriting not supported in moder abi");
4022    RewriteImplementationDecl(CIMP);
4023  }
4024}
4025
4026void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4027                                     const std::string &Name,
4028                                     ValueDecl *VD, bool def) {
4029  assert(BlockByRefDeclNo.count(VD) &&
4030         "RewriteByRefString: ByRef decl missing");
4031  if (def)
4032    ResultStr += "struct ";
4033  ResultStr += "__Block_byref_" + Name +
4034    "_" + utostr(BlockByRefDeclNo[VD]) ;
4035}
4036
4037static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4038  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4039    return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4040  return false;
4041}
4042
4043std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4044                                                   StringRef funcName,
4045                                                   std::string Tag) {
4046  const FunctionType *AFT = CE->getFunctionType();
4047  QualType RT = AFT->getReturnType();
4048  std::string StructRef = "struct " + Tag;
4049  SourceLocation BlockLoc = CE->getExprLoc();
4050  std::string S;
4051  ConvertSourceLocationToLineDirective(BlockLoc, S);
4052
4053  S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4054         funcName.str() + "_block_func_" + utostr(i);
4055
4056  BlockDecl *BD = CE->getBlockDecl();
4057
4058  if (isa<FunctionNoProtoType>(AFT)) {
4059    // No user-supplied arguments. Still need to pass in a pointer to the
4060    // block (to reference imported block decl refs).
4061    S += "(" + StructRef + " *__cself)";
4062  } else if (BD->param_empty()) {
4063    S += "(" + StructRef + " *__cself)";
4064  } else {
4065    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4066    assert(FT && "SynthesizeBlockFunc: No function proto");
4067    S += '(';
4068    // first add the implicit argument.
4069    S += StructRef + " *__cself, ";
4070    std::string ParamStr;
4071    for (BlockDecl::param_iterator AI = BD->param_begin(),
4072         E = BD->param_end(); AI != E; ++AI) {
4073      if (AI != BD->param_begin()) S += ", ";
4074      ParamStr = (*AI)->getNameAsString();
4075      QualType QT = (*AI)->getType();
4076      (void)convertBlockPointerToFunctionPointer(QT);
4077      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4078      S += ParamStr;
4079    }
4080    if (FT->isVariadic()) {
4081      if (!BD->param_empty()) S += ", ";
4082      S += "...";
4083    }
4084    S += ')';
4085  }
4086  S += " {\n";
4087
4088  // Create local declarations to avoid rewriting all closure decl ref exprs.
4089  // First, emit a declaration for all "by ref" decls.
4090  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4091       E = BlockByRefDecls.end(); I != E; ++I) {
4092    S += "  ";
4093    std::string Name = (*I)->getNameAsString();
4094    std::string TypeString;
4095    RewriteByRefString(TypeString, Name, (*I));
4096    TypeString += " *";
4097    Name = TypeString + Name;
4098    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4099  }
4100  // Next, emit a declaration for all "by copy" declarations.
4101  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4102       E = BlockByCopyDecls.end(); I != E; ++I) {
4103    S += "  ";
4104    // Handle nested closure invocation. For example:
4105    //
4106    //   void (^myImportedClosure)(void);
4107    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4108    //
4109    //   void (^anotherClosure)(void);
4110    //   anotherClosure = ^(void) {
4111    //     myImportedClosure(); // import and invoke the closure
4112    //   };
4113    //
4114    if (isTopLevelBlockPointerType((*I)->getType())) {
4115      RewriteBlockPointerTypeVariable(S, (*I));
4116      S += " = (";
4117      RewriteBlockPointerType(S, (*I)->getType());
4118      S += ")";
4119      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4120    }
4121    else {
4122      std::string Name = (*I)->getNameAsString();
4123      QualType QT = (*I)->getType();
4124      if (HasLocalVariableExternalStorage(*I))
4125        QT = Context->getPointerType(QT);
4126      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4127      S += Name + " = __cself->" +
4128                              (*I)->getNameAsString() + "; // bound by copy\n";
4129    }
4130  }
4131  std::string RewrittenStr = RewrittenBlockExprs[CE];
4132  const char *cstr = RewrittenStr.c_str();
4133  while (*cstr++ != '{') ;
4134  S += cstr;
4135  S += "\n";
4136  return S;
4137}
4138
4139std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4140                                                   StringRef funcName,
4141                                                   std::string Tag) {
4142  std::string StructRef = "struct " + Tag;
4143  std::string S = "static void __";
4144
4145  S += funcName;
4146  S += "_block_copy_" + utostr(i);
4147  S += "(" + StructRef;
4148  S += "*dst, " + StructRef;
4149  S += "*src) {";
4150  for (ValueDecl *VD : ImportedBlockDecls) {
4151    S += "_Block_object_assign((void*)&dst->";
4152    S += VD->getNameAsString();
4153    S += ", (void*)src->";
4154    S += VD->getNameAsString();
4155    if (BlockByRefDeclsPtrSet.count(VD))
4156      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4157    else if (VD->getType()->isBlockPointerType())
4158      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4159    else
4160      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4161  }
4162  S += "}\n";
4163
4164  S += "\nstatic void __";
4165  S += funcName;
4166  S += "_block_dispose_" + utostr(i);
4167  S += "(" + StructRef;
4168  S += "*src) {";
4169  for (ValueDecl *VD : ImportedBlockDecls) {
4170    S += "_Block_object_dispose((void*)src->";
4171    S += VD->getNameAsString();
4172    if (BlockByRefDeclsPtrSet.count(VD))
4173      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4174    else if (VD->getType()->isBlockPointerType())
4175      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4176    else
4177      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4178  }
4179  S += "}\n";
4180  return S;
4181}
4182
4183std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4184                                             std::string Desc) {
4185  std::string S = "\nstruct " + Tag;
4186  std::string Constructor = "  " + Tag;
4187
4188  S += " {\n  struct __block_impl impl;\n";
4189  S += "  struct " + Desc;
4190  S += "* Desc;\n";
4191
4192  Constructor += "(void *fp, "; // Invoke function pointer.
4193  Constructor += "struct " + Desc; // Descriptor pointer.
4194  Constructor += " *desc";
4195
4196  if (BlockDeclRefs.size()) {
4197    // Output all "by copy" declarations.
4198    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4199         E = BlockByCopyDecls.end(); I != E; ++I) {
4200      S += "  ";
4201      std::string FieldName = (*I)->getNameAsString();
4202      std::string ArgName = "_" + FieldName;
4203      // Handle nested closure invocation. For example:
4204      //
4205      //   void (^myImportedBlock)(void);
4206      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4207      //
4208      //   void (^anotherBlock)(void);
4209      //   anotherBlock = ^(void) {
4210      //     myImportedBlock(); // import and invoke the closure
4211      //   };
4212      //
4213      if (isTopLevelBlockPointerType((*I)->getType())) {
4214        S += "struct __block_impl *";
4215        Constructor += ", void *" + ArgName;
4216      } else {
4217        QualType QT = (*I)->getType();
4218        if (HasLocalVariableExternalStorage(*I))
4219          QT = Context->getPointerType(QT);
4220        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4221        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4222        Constructor += ", " + ArgName;
4223      }
4224      S += FieldName + ";\n";
4225    }
4226    // Output all "by ref" declarations.
4227    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4228         E = BlockByRefDecls.end(); I != E; ++I) {
4229      S += "  ";
4230      std::string FieldName = (*I)->getNameAsString();
4231      std::string ArgName = "_" + FieldName;
4232      {
4233        std::string TypeString;
4234        RewriteByRefString(TypeString, FieldName, (*I));
4235        TypeString += " *";
4236        FieldName = TypeString + FieldName;
4237        ArgName = TypeString + ArgName;
4238        Constructor += ", " + ArgName;
4239      }
4240      S += FieldName + "; // by ref\n";
4241    }
4242    // Finish writing the constructor.
4243    Constructor += ", int flags=0)";
4244    // Initialize all "by copy" arguments.
4245    bool firsTime = true;
4246    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4247         E = BlockByCopyDecls.end(); I != E; ++I) {
4248      std::string Name = (*I)->getNameAsString();
4249        if (firsTime) {
4250          Constructor += " : ";
4251          firsTime = false;
4252        }
4253        else
4254          Constructor += ", ";
4255        if (isTopLevelBlockPointerType((*I)->getType()))
4256          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4257        else
4258          Constructor += Name + "(_" + Name + ")";
4259    }
4260    // Initialize all "by ref" arguments.
4261    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4262         E = BlockByRefDecls.end(); I != E; ++I) {
4263      std::string Name = (*I)->getNameAsString();
4264      if (firsTime) {
4265        Constructor += " : ";
4266        firsTime = false;
4267      }
4268      else
4269        Constructor += ", ";
4270      Constructor += Name + "(_" + Name + "->__forwarding)";
4271    }
4272
4273    Constructor += " {\n";
4274    if (GlobalVarDecl)
4275      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4276    else
4277      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4278    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4279
4280    Constructor += "    Desc = desc;\n";
4281  } else {
4282    // Finish writing the constructor.
4283    Constructor += ", int flags=0) {\n";
4284    if (GlobalVarDecl)
4285      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4286    else
4287      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4288    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4289    Constructor += "    Desc = desc;\n";
4290  }
4291  Constructor += "  ";
4292  Constructor += "}\n";
4293  S += Constructor;
4294  S += "};\n";
4295  return S;
4296}
4297
4298std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4299                                                   std::string ImplTag, int i,
4300                                                   StringRef FunName,
4301                                                   unsigned hasCopy) {
4302  std::string S = "\nstatic struct " + DescTag;
4303
4304  S += " {\n  size_t reserved;\n";
4305  S += "  size_t Block_size;\n";
4306  if (hasCopy) {
4307    S += "  void (*copy)(struct ";
4308    S += ImplTag; S += "*, struct ";
4309    S += ImplTag; S += "*);\n";
4310
4311    S += "  void (*dispose)(struct ";
4312    S += ImplTag; S += "*);\n";
4313  }
4314  S += "} ";
4315
4316  S += DescTag + "_DATA = { 0, sizeof(struct ";
4317  S += ImplTag + ")";
4318  if (hasCopy) {
4319    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4320    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4321  }
4322  S += "};\n";
4323  return S;
4324}
4325
4326void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4327                                          StringRef FunName) {
4328  bool RewriteSC = (GlobalVarDecl &&
4329                    !Blocks.empty() &&
4330                    GlobalVarDecl->getStorageClass() == SC_Static &&
4331                    GlobalVarDecl->getType().getCVRQualifiers());
4332  if (RewriteSC) {
4333    std::string SC(" void __");
4334    SC += GlobalVarDecl->getNameAsString();
4335    SC += "() {}";
4336    InsertText(FunLocStart, SC);
4337  }
4338
4339  // Insert closures that were part of the function.
4340  for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4341    CollectBlockDeclRefInfo(Blocks[i]);
4342    // Need to copy-in the inner copied-in variables not actually used in this
4343    // block.
4344    for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4345      DeclRefExpr *Exp = InnerDeclRefs[count++];
4346      ValueDecl *VD = Exp->getDecl();
4347      BlockDeclRefs.push_back(Exp);
4348      if (!VD->hasAttr<BlocksAttr>()) {
4349        if (!BlockByCopyDeclsPtrSet.count(VD)) {
4350          BlockByCopyDeclsPtrSet.insert(VD);
4351          BlockByCopyDecls.push_back(VD);
4352        }
4353        continue;
4354      }
4355
4356      if (!BlockByRefDeclsPtrSet.count(VD)) {
4357        BlockByRefDeclsPtrSet.insert(VD);
4358        BlockByRefDecls.push_back(VD);
4359      }
4360
4361      // imported objects in the inner blocks not used in the outer
4362      // blocks must be copied/disposed in the outer block as well.
4363      if (VD->getType()->isObjCObjectPointerType() ||
4364          VD->getType()->isBlockPointerType())
4365        ImportedBlockDecls.insert(VD);
4366    }
4367
4368    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4369    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4370
4371    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4372
4373    InsertText(FunLocStart, CI);
4374
4375    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4376
4377    InsertText(FunLocStart, CF);
4378
4379    if (ImportedBlockDecls.size()) {
4380      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4381      InsertText(FunLocStart, HF);
4382    }
4383    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4384                                               ImportedBlockDecls.size() > 0);
4385    InsertText(FunLocStart, BD);
4386
4387    BlockDeclRefs.clear();
4388    BlockByRefDecls.clear();
4389    BlockByRefDeclsPtrSet.clear();
4390    BlockByCopyDecls.clear();
4391    BlockByCopyDeclsPtrSet.clear();
4392    ImportedBlockDecls.clear();
4393  }
4394  if (RewriteSC) {
4395    // Must insert any 'const/volatile/static here. Since it has been
4396    // removed as result of rewriting of block literals.
4397    std::string SC;
4398    if (GlobalVarDecl->getStorageClass() == SC_Static)
4399      SC = "static ";
4400    if (GlobalVarDecl->getType().isConstQualified())
4401      SC += "const ";
4402    if (GlobalVarDecl->getType().isVolatileQualified())
4403      SC += "volatile ";
4404    if (GlobalVarDecl->getType().isRestrictQualified())
4405      SC += "restrict ";
4406    InsertText(FunLocStart, SC);
4407  }
4408  if (GlobalConstructionExp) {
4409    // extra fancy dance for global literal expression.
4410
4411    // Always the latest block expression on the block stack.
4412    std::string Tag = "__";
4413    Tag += FunName;
4414    Tag += "_block_impl_";
4415    Tag += utostr(Blocks.size()-1);
4416    std::string globalBuf = "static ";
4417    globalBuf += Tag; globalBuf += " ";
4418    std::string SStr;
4419
4420    llvm::raw_string_ostream constructorExprBuf(SStr);
4421    GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4422                                       PrintingPolicy(LangOpts));
4423    globalBuf += constructorExprBuf.str();
4424    globalBuf += ";\n";
4425    InsertText(FunLocStart, globalBuf);
4426    GlobalConstructionExp = nullptr;
4427  }
4428
4429  Blocks.clear();
4430  InnerDeclRefsCount.clear();
4431  InnerDeclRefs.clear();
4432  RewrittenBlockExprs.clear();
4433}
4434
4435void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4436  SourceLocation FunLocStart =
4437    (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4438                      : FD->getTypeSpecStartLoc();
4439  StringRef FuncName = FD->getName();
4440
4441  SynthesizeBlockLiterals(FunLocStart, FuncName);
4442}
4443
4444static void BuildUniqueMethodName(std::string &Name,
4445                                  ObjCMethodDecl *MD) {
4446  ObjCInterfaceDecl *IFace = MD->getClassInterface();
4447  Name = std::string(IFace->getName());
4448  Name += "__" + MD->getSelector().getAsString();
4449  // Convert colons to underscores.
4450  std::string::size_type loc = 0;
4451  while ((loc = Name.find(':', loc)) != std::string::npos)
4452    Name.replace(loc, 1, "_");
4453}
4454
4455void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4456  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4457  // SourceLocation FunLocStart = MD->getBeginLoc();
4458  SourceLocation FunLocStart = MD->getBeginLoc();
4459  std::string FuncName;
4460  BuildUniqueMethodName(FuncName, MD);
4461  SynthesizeBlockLiterals(FunLocStart, FuncName);
4462}
4463
4464void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4465  for (Stmt *SubStmt : S->children())
4466    if (SubStmt) {
4467      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4468        GetBlockDeclRefExprs(CBE->getBody());
4469      else
4470        GetBlockDeclRefExprs(SubStmt);
4471    }
4472  // Handle specific things.
4473  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4474    if (DRE->refersToEnclosingVariableOrCapture() ||
4475        HasLocalVariableExternalStorage(DRE->getDecl()))
4476      // FIXME: Handle enums.
4477      BlockDeclRefs.push_back(DRE);
4478}
4479
4480void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4481                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4482                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4483  for (Stmt *SubStmt : S->children())
4484    if (SubStmt) {
4485      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4486        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4487        GetInnerBlockDeclRefExprs(CBE->getBody(),
4488                                  InnerBlockDeclRefs,
4489                                  InnerContexts);
4490      }
4491      else
4492        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4493    }
4494  // Handle specific things.
4495  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4496    if (DRE->refersToEnclosingVariableOrCapture() ||
4497        HasLocalVariableExternalStorage(DRE->getDecl())) {
4498      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4499        InnerBlockDeclRefs.push_back(DRE);
4500      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4501        if (Var->isFunctionOrMethodVarDecl())
4502          ImportedLocalExternalDecls.insert(Var);
4503    }
4504  }
4505}
4506
4507/// convertObjCTypeToCStyleType - This routine converts such objc types
4508/// as qualified objects, and blocks to their closest c/c++ types that
4509/// it can. It returns true if input type was modified.
4510bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4511  QualType oldT = T;
4512  convertBlockPointerToFunctionPointer(T);
4513  if (T->isFunctionPointerType()) {
4514    QualType PointeeTy;
4515    if (const PointerType* PT = T->getAs<PointerType>()) {
4516      PointeeTy = PT->getPointeeType();
4517      if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4518        T = convertFunctionTypeOfBlocks(FT);
4519        T = Context->getPointerType(T);
4520      }
4521    }
4522  }
4523
4524  convertToUnqualifiedObjCType(T);
4525  return T != oldT;
4526}
4527
4528/// convertFunctionTypeOfBlocks - This routine converts a function type
4529/// whose result type may be a block pointer or whose argument type(s)
4530/// might be block pointers to an equivalent function type replacing
4531/// all block pointers to function pointers.
4532QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4533  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4534  // FTP will be null for closures that don't take arguments.
4535  // Generate a funky cast.
4536  SmallVector<QualType, 8> ArgTypes;
4537  QualType Res = FT->getReturnType();
4538  bool modified = convertObjCTypeToCStyleType(Res);
4539
4540  if (FTP) {
4541    for (auto &I : FTP->param_types()) {
4542      QualType t = I;
4543      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4544      if (convertObjCTypeToCStyleType(t))
4545        modified = true;
4546      ArgTypes.push_back(t);
4547    }
4548  }
4549  QualType FuncType;
4550  if (modified)
4551    FuncType = getSimpleFunctionType(Res, ArgTypes);
4552  else FuncType = QualType(FT, 0);
4553  return FuncType;
4554}
4555
4556Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4557  // Navigate to relevant type information.
4558  const BlockPointerType *CPT = nullptr;
4559
4560  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4561    CPT = DRE->getType()->getAs<BlockPointerType>();
4562  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4563    CPT = MExpr->getType()->getAs<BlockPointerType>();
4564  }
4565  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4566    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4567  }
4568  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4569    CPT = IEXPR->getType()->getAs<BlockPointerType>();
4570  else if (const ConditionalOperator *CEXPR =
4571            dyn_cast<ConditionalOperator>(BlockExp)) {
4572    Expr *LHSExp = CEXPR->getLHS();
4573    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4574    Expr *RHSExp = CEXPR->getRHS();
4575    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4576    Expr *CONDExp = CEXPR->getCond();
4577    ConditionalOperator *CondExpr =
4578      new (Context) ConditionalOperator(CONDExp,
4579                                      SourceLocation(), cast<Expr>(LHSStmt),
4580                                      SourceLocation(), cast<Expr>(RHSStmt),
4581                                      Exp->getType(), VK_RValue, OK_Ordinary);
4582    return CondExpr;
4583  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4584    CPT = IRE->getType()->getAs<BlockPointerType>();
4585  } else if (const PseudoObjectExpr *POE
4586               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4587    CPT = POE->getType()->castAs<BlockPointerType>();
4588  } else {
4589    assert(false && "RewriteBlockClass: Bad type");
4590  }
4591  assert(CPT && "RewriteBlockClass: Bad type");
4592  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4593  assert(FT && "RewriteBlockClass: Bad type");
4594  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4595  // FTP will be null for closures that don't take arguments.
4596
4597  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4598                                      SourceLocation(), SourceLocation(),
4599                                      &Context->Idents.get("__block_impl"));
4600  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4601
4602  // Generate a funky cast.
4603  SmallVector<QualType, 8> ArgTypes;
4604
4605  // Push the block argument type.
4606  ArgTypes.push_back(PtrBlock);
4607  if (FTP) {
4608    for (auto &I : FTP->param_types()) {
4609      QualType t = I;
4610      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4611      if (!convertBlockPointerToFunctionPointer(t))
4612        convertToUnqualifiedObjCType(t);
4613      ArgTypes.push_back(t);
4614    }
4615  }
4616  // Now do the pointer to function cast.
4617  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4618
4619  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4620
4621  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4622                                               CK_BitCast,
4623                                               const_cast<Expr*>(BlockExp));
4624  // Don't forget the parens to enforce the proper binding.
4625  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4626                                          BlkCast);
4627  //PE->dump();
4628
4629  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4630                                    SourceLocation(),
4631                                    &Context->Idents.get("FuncPtr"),
4632                                    Context->VoidPtrTy, nullptr,
4633                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4634                                    ICIS_NoInit);
4635  MemberExpr *ME = MemberExpr::CreateImplicit(
4636      *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4637
4638  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4639                                                CK_BitCast, ME);
4640  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4641
4642  SmallVector<Expr*, 8> BlkExprs;
4643  // Add the implicit argument.
4644  BlkExprs.push_back(BlkCast);
4645  // Add the user arguments.
4646  for (CallExpr::arg_iterator I = Exp->arg_begin(),
4647       E = Exp->arg_end(); I != E; ++I) {
4648    BlkExprs.push_back(*I);
4649  }
4650  CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4651                                  VK_RValue, SourceLocation());
4652  return CE;
4653}
4654
4655// We need to return the rewritten expression to handle cases where the
4656// DeclRefExpr is embedded in another expression being rewritten.
4657// For example:
4658//
4659// int main() {
4660//    __block Foo *f;
4661//    __block int i;
4662//
4663//    void (^myblock)() = ^() {
4664//        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4665//        i = 77;
4666//    };
4667//}
4668Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4669  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4670  // for each DeclRefExp where BYREFVAR is name of the variable.
4671  ValueDecl *VD = DeclRefExp->getDecl();
4672  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4673                 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4674
4675  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4676                                    SourceLocation(),
4677                                    &Context->Idents.get("__forwarding"),
4678                                    Context->VoidPtrTy, nullptr,
4679                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4680                                    ICIS_NoInit);
4681  MemberExpr *ME = MemberExpr::CreateImplicit(
4682      *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4683
4684  StringRef Name = VD->getName();
4685  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4686                         &Context->Idents.get(Name),
4687                         Context->VoidPtrTy, nullptr,
4688                         /*BitWidth=*/nullptr, /*Mutable=*/true,
4689                         ICIS_NoInit);
4690  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4691                                  VK_LValue, OK_Ordinary);
4692
4693  // Need parens to enforce precedence.
4694  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4695                                          DeclRefExp->getExprLoc(),
4696                                          ME);
4697  ReplaceStmt(DeclRefExp, PE);
4698  return PE;
4699}
4700
4701// Rewrites the imported local variable V with external storage
4702// (static, extern, etc.) as *V
4703//
4704Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4705  ValueDecl *VD = DRE->getDecl();
4706  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4707    if (!ImportedLocalExternalDecls.count(Var))
4708      return DRE;
4709  Expr *Exp = UnaryOperator::Create(
4710      const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
4711      VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
4712  // Need parens to enforce precedence.
4713  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4714                                          Exp);
4715  ReplaceStmt(DRE, PE);
4716  return PE;
4717}
4718
4719void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4720  SourceLocation LocStart = CE->getLParenLoc();
4721  SourceLocation LocEnd = CE->getRParenLoc();
4722
4723  // Need to avoid trying to rewrite synthesized casts.
4724  if (LocStart.isInvalid())
4725    return;
4726  // Need to avoid trying to rewrite casts contained in macros.
4727  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4728    return;
4729
4730  const char *startBuf = SM->getCharacterData(LocStart);
4731  const char *endBuf = SM->getCharacterData(LocEnd);
4732  QualType QT = CE->getType();
4733  const Type* TypePtr = QT->getAs<Type>();
4734  if (isa<TypeOfExprType>(TypePtr)) {
4735    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4736    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4737    std::string TypeAsString = "(";
4738    RewriteBlockPointerType(TypeAsString, QT);
4739    TypeAsString += ")";
4740    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4741    return;
4742  }
4743  // advance the location to startArgList.
4744  const char *argPtr = startBuf;
4745
4746  while (*argPtr++ && (argPtr < endBuf)) {
4747    switch (*argPtr) {
4748    case '^':
4749      // Replace the '^' with '*'.
4750      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4751      ReplaceText(LocStart, 1, "*");
4752      break;
4753    }
4754  }
4755}
4756
4757void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4758  CastKind CastKind = IC->getCastKind();
4759  if (CastKind != CK_BlockPointerToObjCPointerCast &&
4760      CastKind != CK_AnyPointerToBlockPointerCast)
4761    return;
4762
4763  QualType QT = IC->getType();
4764  (void)convertBlockPointerToFunctionPointer(QT);
4765  std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4766  std::string Str = "(";
4767  Str += TypeString;
4768  Str += ")";
4769  InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4770}
4771
4772void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4773  SourceLocation DeclLoc = FD->getLocation();
4774  unsigned parenCount = 0;
4775
4776  // We have 1 or more arguments that have closure pointers.
4777  const char *startBuf = SM->getCharacterData(DeclLoc);
4778  const char *startArgList = strchr(startBuf, '(');
4779
4780  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4781
4782  parenCount++;
4783  // advance the location to startArgList.
4784  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4785  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4786
4787  const char *argPtr = startArgList;
4788
4789  while (*argPtr++ && parenCount) {
4790    switch (*argPtr) {
4791    case '^':
4792      // Replace the '^' with '*'.
4793      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4794      ReplaceText(DeclLoc, 1, "*");
4795      break;
4796    case '(':
4797      parenCount++;
4798      break;
4799    case ')':
4800      parenCount--;
4801      break;
4802    }
4803  }
4804}
4805
4806bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4807  const FunctionProtoType *FTP;
4808  const PointerType *PT = QT->getAs<PointerType>();
4809  if (PT) {
4810    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4811  } else {
4812    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4813    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4814    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4815  }
4816  if (FTP) {
4817    for (const auto &I : FTP->param_types())
4818      if (isTopLevelBlockPointerType(I))
4819        return true;
4820  }
4821  return false;
4822}
4823
4824bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4825  const FunctionProtoType *FTP;
4826  const PointerType *PT = QT->getAs<PointerType>();
4827  if (PT) {
4828    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4829  } else {
4830    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4831    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4832    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4833  }
4834  if (FTP) {
4835    for (const auto &I : FTP->param_types()) {
4836      if (I->isObjCQualifiedIdType())
4837        return true;
4838      if (I->isObjCObjectPointerType() &&
4839          I->getPointeeType()->isObjCQualifiedInterfaceType())
4840        return true;
4841    }
4842
4843  }
4844  return false;
4845}
4846
4847void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4848                                     const char *&RParen) {
4849  const char *argPtr = strchr(Name, '(');
4850  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4851
4852  LParen = argPtr; // output the start.
4853  argPtr++; // skip past the left paren.
4854  unsigned parenCount = 1;
4855
4856  while (*argPtr && parenCount) {
4857    switch (*argPtr) {
4858    case '(': parenCount++; break;
4859    case ')': parenCount--; break;
4860    default: break;
4861    }
4862    if (parenCount) argPtr++;
4863  }
4864  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4865  RParen = argPtr; // output the end
4866}
4867
4868void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4869  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4870    RewriteBlockPointerFunctionArgs(FD);
4871    return;
4872  }
4873  // Handle Variables and Typedefs.
4874  SourceLocation DeclLoc = ND->getLocation();
4875  QualType DeclT;
4876  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4877    DeclT = VD->getType();
4878  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4879    DeclT = TDD->getUnderlyingType();
4880  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4881    DeclT = FD->getType();
4882  else
4883    llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4884
4885  const char *startBuf = SM->getCharacterData(DeclLoc);
4886  const char *endBuf = startBuf;
4887  // scan backward (from the decl location) for the end of the previous decl.
4888  while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4889    startBuf--;
4890  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4891  std::string buf;
4892  unsigned OrigLength=0;
4893  // *startBuf != '^' if we are dealing with a pointer to function that
4894  // may take block argument types (which will be handled below).
4895  if (*startBuf == '^') {
4896    // Replace the '^' with '*', computing a negative offset.
4897    buf = '*';
4898    startBuf++;
4899    OrigLength++;
4900  }
4901  while (*startBuf != ')') {
4902    buf += *startBuf;
4903    startBuf++;
4904    OrigLength++;
4905  }
4906  buf += ')';
4907  OrigLength++;
4908
4909  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4910      PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4911    // Replace the '^' with '*' for arguments.
4912    // Replace id<P> with id/*<>*/
4913    DeclLoc = ND->getLocation();
4914    startBuf = SM->getCharacterData(DeclLoc);
4915    const char *argListBegin, *argListEnd;
4916    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4917    while (argListBegin < argListEnd) {
4918      if (*argListBegin == '^')
4919        buf += '*';
4920      else if (*argListBegin ==  '<') {
4921        buf += "/*";
4922        buf += *argListBegin++;
4923        OrigLength++;
4924        while (*argListBegin != '>') {
4925          buf += *argListBegin++;
4926          OrigLength++;
4927        }
4928        buf += *argListBegin;
4929        buf += "*/";
4930      }
4931      else
4932        buf += *argListBegin;
4933      argListBegin++;
4934      OrigLength++;
4935    }
4936    buf += ')';
4937    OrigLength++;
4938  }
4939  ReplaceText(Start, OrigLength, buf);
4940}
4941
4942/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4943/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4944///                    struct Block_byref_id_object *src) {
4945///  _Block_object_assign (&_dest->object, _src->object,
4946///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4947///                        [|BLOCK_FIELD_IS_WEAK]) // object
4948///  _Block_object_assign(&_dest->object, _src->object,
4949///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4950///                       [|BLOCK_FIELD_IS_WEAK]) // block
4951/// }
4952/// And:
4953/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4954///  _Block_object_dispose(_src->object,
4955///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4956///                        [|BLOCK_FIELD_IS_WEAK]) // object
4957///  _Block_object_dispose(_src->object,
4958///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4959///                         [|BLOCK_FIELD_IS_WEAK]) // block
4960/// }
4961
4962std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4963                                                          int flag) {
4964  std::string S;
4965  if (CopyDestroyCache.count(flag))
4966    return S;
4967  CopyDestroyCache.insert(flag);
4968  S = "static void __Block_byref_id_object_copy_";
4969  S += utostr(flag);
4970  S += "(void *dst, void *src) {\n";
4971
4972  // offset into the object pointer is computed as:
4973  // void * + void* + int + int + void* + void *
4974  unsigned IntSize =
4975  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4976  unsigned VoidPtrSize =
4977  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4978
4979  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4980  S += " _Block_object_assign((char*)dst + ";
4981  S += utostr(offset);
4982  S += ", *(void * *) ((char*)src + ";
4983  S += utostr(offset);
4984  S += "), ";
4985  S += utostr(flag);
4986  S += ");\n}\n";
4987
4988  S += "static void __Block_byref_id_object_dispose_";
4989  S += utostr(flag);
4990  S += "(void *src) {\n";
4991  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4992  S += utostr(offset);
4993  S += "), ";
4994  S += utostr(flag);
4995  S += ");\n}\n";
4996  return S;
4997}
4998
4999/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5000/// the declaration into:
5001/// struct __Block_byref_ND {
5002/// void *__isa;                  // NULL for everything except __weak pointers
5003/// struct __Block_byref_ND *__forwarding;
5004/// int32_t __flags;
5005/// int32_t __size;
5006/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5007/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5008/// typex ND;
5009/// };
5010///
5011/// It then replaces declaration of ND variable with:
5012/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5013///                               __size=sizeof(struct __Block_byref_ND),
5014///                               ND=initializer-if-any};
5015///
5016///
5017void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5018                                        bool lastDecl) {
5019  int flag = 0;
5020  int isa = 0;
5021  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5022  if (DeclLoc.isInvalid())
5023    // If type location is missing, it is because of missing type (a warning).
5024    // Use variable's location which is good for this case.
5025    DeclLoc = ND->getLocation();
5026  const char *startBuf = SM->getCharacterData(DeclLoc);
5027  SourceLocation X = ND->getEndLoc();
5028  X = SM->getExpansionLoc(X);
5029  const char *endBuf = SM->getCharacterData(X);
5030  std::string Name(ND->getNameAsString());
5031  std::string ByrefType;
5032  RewriteByRefString(ByrefType, Name, ND, true);
5033  ByrefType += " {\n";
5034  ByrefType += "  void *__isa;\n";
5035  RewriteByRefString(ByrefType, Name, ND);
5036  ByrefType += " *__forwarding;\n";
5037  ByrefType += " int __flags;\n";
5038  ByrefType += " int __size;\n";
5039  // Add void *__Block_byref_id_object_copy;
5040  // void *__Block_byref_id_object_dispose; if needed.
5041  QualType Ty = ND->getType();
5042  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5043  if (HasCopyAndDispose) {
5044    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5045    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5046  }
5047
5048  QualType T = Ty;
5049  (void)convertBlockPointerToFunctionPointer(T);
5050  T.getAsStringInternal(Name, Context->getPrintingPolicy());
5051
5052  ByrefType += " " + Name + ";\n";
5053  ByrefType += "};\n";
5054  // Insert this type in global scope. It is needed by helper function.
5055  SourceLocation FunLocStart;
5056  if (CurFunctionDef)
5057     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5058  else {
5059    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5060    FunLocStart = CurMethodDef->getBeginLoc();
5061  }
5062  InsertText(FunLocStart, ByrefType);
5063
5064  if (Ty.isObjCGCWeak()) {
5065    flag |= BLOCK_FIELD_IS_WEAK;
5066    isa = 1;
5067  }
5068  if (HasCopyAndDispose) {
5069    flag = BLOCK_BYREF_CALLER;
5070    QualType Ty = ND->getType();
5071    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5072    if (Ty->isBlockPointerType())
5073      flag |= BLOCK_FIELD_IS_BLOCK;
5074    else
5075      flag |= BLOCK_FIELD_IS_OBJECT;
5076    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5077    if (!HF.empty())
5078      Preamble += HF;
5079  }
5080
5081  // struct __Block_byref_ND ND =
5082  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5083  //  initializer-if-any};
5084  bool hasInit = (ND->getInit() != nullptr);
5085  // FIXME. rewriter does not support __block c++ objects which
5086  // require construction.
5087  if (hasInit)
5088    if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5089      CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5090      if (CXXDecl && CXXDecl->isDefaultConstructor())
5091        hasInit = false;
5092    }
5093
5094  unsigned flags = 0;
5095  if (HasCopyAndDispose)
5096    flags |= BLOCK_HAS_COPY_DISPOSE;
5097  Name = ND->getNameAsString();
5098  ByrefType.clear();
5099  RewriteByRefString(ByrefType, Name, ND);
5100  std::string ForwardingCastType("(");
5101  ForwardingCastType += ByrefType + " *)";
5102  ByrefType += " " + Name + " = {(void*)";
5103  ByrefType += utostr(isa);
5104  ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5105  ByrefType += utostr(flags);
5106  ByrefType += ", ";
5107  ByrefType += "sizeof(";
5108  RewriteByRefString(ByrefType, Name, ND);
5109  ByrefType += ")";
5110  if (HasCopyAndDispose) {
5111    ByrefType += ", __Block_byref_id_object_copy_";
5112    ByrefType += utostr(flag);
5113    ByrefType += ", __Block_byref_id_object_dispose_";
5114    ByrefType += utostr(flag);
5115  }
5116
5117  if (!firstDecl) {
5118    // In multiple __block declarations, and for all but 1st declaration,
5119    // find location of the separating comma. This would be start location
5120    // where new text is to be inserted.
5121    DeclLoc = ND->getLocation();
5122    const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5123    const char *commaBuf = startDeclBuf;
5124    while (*commaBuf != ',')
5125      commaBuf--;
5126    assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5127    DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5128    startBuf = commaBuf;
5129  }
5130
5131  if (!hasInit) {
5132    ByrefType += "};\n";
5133    unsigned nameSize = Name.size();
5134    // for block or function pointer declaration. Name is already
5135    // part of the declaration.
5136    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5137      nameSize = 1;
5138    ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5139  }
5140  else {
5141    ByrefType += ", ";
5142    SourceLocation startLoc;
5143    Expr *E = ND->getInit();
5144    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5145      startLoc = ECE->getLParenLoc();
5146    else
5147      startLoc = E->getBeginLoc();
5148    startLoc = SM->getExpansionLoc(startLoc);
5149    endBuf = SM->getCharacterData(startLoc);
5150    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5151
5152    const char separator = lastDecl ? ';' : ',';
5153    const char *startInitializerBuf = SM->getCharacterData(startLoc);
5154    const char *separatorBuf = strchr(startInitializerBuf, separator);
5155    assert((*separatorBuf == separator) &&
5156           "RewriteByRefVar: can't find ';' or ','");
5157    SourceLocation separatorLoc =
5158      startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5159
5160    InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5161  }
5162}
5163
5164void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5165  // Add initializers for any closure decl refs.
5166  GetBlockDeclRefExprs(Exp->getBody());
5167  if (BlockDeclRefs.size()) {
5168    // Unique all "by copy" declarations.
5169    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5170      if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5171        if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5172          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5173          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5174        }
5175      }
5176    // Unique all "by ref" declarations.
5177    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5178      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5179        if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5180          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5181          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5182        }
5183      }
5184    // Find any imported blocks...they will need special attention.
5185    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5186      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5187          BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5188          BlockDeclRefs[i]->getType()->isBlockPointerType())
5189        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5190  }
5191}
5192
5193FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5194  IdentifierInfo *ID = &Context->Idents.get(name);
5195  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5196  return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5197                              SourceLocation(), ID, FType, nullptr, SC_Extern,
5198                              false, false);
5199}
5200
5201Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5202                     const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5203  const BlockDecl *block = Exp->getBlockDecl();
5204
5205  Blocks.push_back(Exp);
5206
5207  CollectBlockDeclRefInfo(Exp);
5208
5209  // Add inner imported variables now used in current block.
5210  int countOfInnerDecls = 0;
5211  if (!InnerBlockDeclRefs.empty()) {
5212    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5213      DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5214      ValueDecl *VD = Exp->getDecl();
5215      if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5216      // We need to save the copied-in variables in nested
5217      // blocks because it is needed at the end for some of the API generations.
5218      // See SynthesizeBlockLiterals routine.
5219        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5220        BlockDeclRefs.push_back(Exp);
5221        BlockByCopyDeclsPtrSet.insert(VD);
5222        BlockByCopyDecls.push_back(VD);
5223      }
5224      if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5225        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5226        BlockDeclRefs.push_back(Exp);
5227        BlockByRefDeclsPtrSet.insert(VD);
5228        BlockByRefDecls.push_back(VD);
5229      }
5230    }
5231    // Find any imported blocks...they will need special attention.
5232    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5233      if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5234          InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5235          InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5236        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5237  }
5238  InnerDeclRefsCount.push_back(countOfInnerDecls);
5239
5240  std::string FuncName;
5241
5242  if (CurFunctionDef)
5243    FuncName = CurFunctionDef->getNameAsString();
5244  else if (CurMethodDef)
5245    BuildUniqueMethodName(FuncName, CurMethodDef);
5246  else if (GlobalVarDecl)
5247    FuncName = std::string(GlobalVarDecl->getNameAsString());
5248
5249  bool GlobalBlockExpr =
5250    block->getDeclContext()->getRedeclContext()->isFileContext();
5251
5252  if (GlobalBlockExpr && !GlobalVarDecl) {
5253    Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5254    GlobalBlockExpr = false;
5255  }
5256
5257  std::string BlockNumber = utostr(Blocks.size()-1);
5258
5259  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5260
5261  // Get a pointer to the function type so we can cast appropriately.
5262  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5263  QualType FType = Context->getPointerType(BFT);
5264
5265  FunctionDecl *FD;
5266  Expr *NewRep;
5267
5268  // Simulate a constructor call...
5269  std::string Tag;
5270
5271  if (GlobalBlockExpr)
5272    Tag = "__global_";
5273  else
5274    Tag = "__";
5275  Tag += FuncName + "_block_impl_" + BlockNumber;
5276
5277  FD = SynthBlockInitFunctionDecl(Tag);
5278  DeclRefExpr *DRE = new (Context)
5279      DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
5280
5281  SmallVector<Expr*, 4> InitExprs;
5282
5283  // Initialize the block function.
5284  FD = SynthBlockInitFunctionDecl(Func);
5285  DeclRefExpr *Arg = new (Context) DeclRefExpr(
5286      *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5287  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5288                                                CK_BitCast, Arg);
5289  InitExprs.push_back(castExpr);
5290
5291  // Initialize the block descriptor.
5292  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5293
5294  VarDecl *NewVD = VarDecl::Create(
5295      *Context, TUDecl, SourceLocation(), SourceLocation(),
5296      &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5297  UnaryOperator *DescRefExpr = UnaryOperator::Create(
5298      const_cast<ASTContext &>(*Context),
5299      new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5300                                VK_LValue, SourceLocation()),
5301      UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5302      OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
5303  InitExprs.push_back(DescRefExpr);
5304
5305  // Add initializers for any closure decl refs.
5306  if (BlockDeclRefs.size()) {
5307    Expr *Exp;
5308    // Output all "by copy" declarations.
5309    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5310         E = BlockByCopyDecls.end(); I != E; ++I) {
5311      if (isObjCType((*I)->getType())) {
5312        // FIXME: Conform to ABI ([[obj retain] autorelease]).
5313        FD = SynthBlockInitFunctionDecl((*I)->getName());
5314        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5315                                        VK_LValue, SourceLocation());
5316        if (HasLocalVariableExternalStorage(*I)) {
5317          QualType QT = (*I)->getType();
5318          QT = Context->getPointerType(QT);
5319          Exp = UnaryOperator::Create(
5320              const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
5321              OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
5322        }
5323      } else if (isTopLevelBlockPointerType((*I)->getType())) {
5324        FD = SynthBlockInitFunctionDecl((*I)->getName());
5325        Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5326                                        VK_LValue, SourceLocation());
5327        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5328                                       CK_BitCast, Arg);
5329      } else {
5330        FD = SynthBlockInitFunctionDecl((*I)->getName());
5331        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5332                                        VK_LValue, SourceLocation());
5333        if (HasLocalVariableExternalStorage(*I)) {
5334          QualType QT = (*I)->getType();
5335          QT = Context->getPointerType(QT);
5336          Exp = UnaryOperator::Create(
5337              const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_RValue,
5338              OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
5339        }
5340
5341      }
5342      InitExprs.push_back(Exp);
5343    }
5344    // Output all "by ref" declarations.
5345    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5346         E = BlockByRefDecls.end(); I != E; ++I) {
5347      ValueDecl *ND = (*I);
5348      std::string Name(ND->getNameAsString());
5349      std::string RecName;
5350      RewriteByRefString(RecName, Name, ND, true);
5351      IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5352                                                + sizeof("struct"));
5353      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5354                                          SourceLocation(), SourceLocation(),
5355                                          II);
5356      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5357      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5358
5359      FD = SynthBlockInitFunctionDecl((*I)->getName());
5360      Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5361                                      VK_LValue, SourceLocation());
5362      bool isNestedCapturedVar = false;
5363      if (block)
5364        for (const auto &CI : block->captures()) {
5365          const VarDecl *variable = CI.getVariable();
5366          if (variable == ND && CI.isNested()) {
5367            assert (CI.isByRef() &&
5368                    "SynthBlockInitExpr - captured block variable is not byref");
5369            isNestedCapturedVar = true;
5370            break;
5371          }
5372        }
5373      // captured nested byref variable has its address passed. Do not take
5374      // its address again.
5375      if (!isNestedCapturedVar)
5376        Exp = UnaryOperator::Create(
5377            const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
5378            Context->getPointerType(Exp->getType()), VK_RValue, OK_Ordinary,
5379            SourceLocation(), false, FPOptionsOverride());
5380      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5381      InitExprs.push_back(Exp);
5382    }
5383  }
5384  if (ImportedBlockDecls.size()) {
5385    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5386    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5387    unsigned IntSize =
5388      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5389    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5390                                           Context->IntTy, SourceLocation());
5391    InitExprs.push_back(FlagExp);
5392  }
5393  NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5394                            SourceLocation());
5395
5396  if (GlobalBlockExpr) {
5397    assert (!GlobalConstructionExp &&
5398            "SynthBlockInitExpr - GlobalConstructionExp must be null");
5399    GlobalConstructionExp = NewRep;
5400    NewRep = DRE;
5401  }
5402
5403  NewRep = UnaryOperator::Create(
5404      const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
5405      Context->getPointerType(NewRep->getType()), VK_RValue, OK_Ordinary,
5406      SourceLocation(), false, FPOptionsOverride());
5407  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5408                                    NewRep);
5409  // Put Paren around the call.
5410  NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5411                                   NewRep);
5412
5413  BlockDeclRefs.clear();
5414  BlockByRefDecls.clear();
5415  BlockByRefDeclsPtrSet.clear();
5416  BlockByCopyDecls.clear();
5417  BlockByCopyDeclsPtrSet.clear();
5418  ImportedBlockDecls.clear();
5419  return NewRep;
5420}
5421
5422bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5423  if (const ObjCForCollectionStmt * CS =
5424      dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5425        return CS->getElement() == DS;
5426  return false;
5427}
5428
5429//===----------------------------------------------------------------------===//
5430// Function Body / Expression rewriting
5431//===----------------------------------------------------------------------===//
5432
5433Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5434  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5435      isa<DoStmt>(S) || isa<ForStmt>(S))
5436    Stmts.push_back(S);
5437  else if (isa<ObjCForCollectionStmt>(S)) {
5438    Stmts.push_back(S);
5439    ObjCBcLabelNo.push_back(++BcLabelCount);
5440  }
5441
5442  // Pseudo-object operations and ivar references need special
5443  // treatment because we're going to recursively rewrite them.
5444  if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5445    if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5446      return RewritePropertyOrImplicitSetter(PseudoOp);
5447    } else {
5448      return RewritePropertyOrImplicitGetter(PseudoOp);
5449    }
5450  } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5451    return RewriteObjCIvarRefExpr(IvarRefExpr);
5452  }
5453  else if (isa<OpaqueValueExpr>(S))
5454    S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5455
5456  SourceRange OrigStmtRange = S->getSourceRange();
5457
5458  // Perform a bottom up rewrite of all children.
5459  for (Stmt *&childStmt : S->children())
5460    if (childStmt) {
5461      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5462      if (newStmt) {
5463        childStmt = newStmt;
5464      }
5465    }
5466
5467  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5468    SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5469    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5470    InnerContexts.insert(BE->getBlockDecl());
5471    ImportedLocalExternalDecls.clear();
5472    GetInnerBlockDeclRefExprs(BE->getBody(),
5473                              InnerBlockDeclRefs, InnerContexts);
5474    // Rewrite the block body in place.
5475    Stmt *SaveCurrentBody = CurrentBody;
5476    CurrentBody = BE->getBody();
5477    PropParentMap = nullptr;
5478    // block literal on rhs of a property-dot-sytax assignment
5479    // must be replaced by its synthesize ast so getRewrittenText
5480    // works as expected. In this case, what actually ends up on RHS
5481    // is the blockTranscribed which is the helper function for the
5482    // block literal; as in: self.c = ^() {[ace ARR];};
5483    bool saveDisableReplaceStmt = DisableReplaceStmt;
5484    DisableReplaceStmt = false;
5485    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5486    DisableReplaceStmt = saveDisableReplaceStmt;
5487    CurrentBody = SaveCurrentBody;
5488    PropParentMap = nullptr;
5489    ImportedLocalExternalDecls.clear();
5490    // Now we snarf the rewritten text and stash it away for later use.
5491    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5492    RewrittenBlockExprs[BE] = Str;
5493
5494    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5495
5496    //blockTranscribed->dump();
5497    ReplaceStmt(S, blockTranscribed);
5498    return blockTranscribed;
5499  }
5500  // Handle specific things.
5501  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5502    return RewriteAtEncode(AtEncode);
5503
5504  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5505    return RewriteAtSelector(AtSelector);
5506
5507  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5508    return RewriteObjCStringLiteral(AtString);
5509
5510  if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5511    return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5512
5513  if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5514    return RewriteObjCBoxedExpr(BoxedExpr);
5515
5516  if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5517    return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5518
5519  if (ObjCDictionaryLiteral *DictionaryLitExpr =
5520        dyn_cast<ObjCDictionaryLiteral>(S))
5521    return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5522
5523  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5524#if 0
5525    // Before we rewrite it, put the original message expression in a comment.
5526    SourceLocation startLoc = MessExpr->getBeginLoc();
5527    SourceLocation endLoc = MessExpr->getEndLoc();
5528
5529    const char *startBuf = SM->getCharacterData(startLoc);
5530    const char *endBuf = SM->getCharacterData(endLoc);
5531
5532    std::string messString;
5533    messString += "// ";
5534    messString.append(startBuf, endBuf-startBuf+1);
5535    messString += "\n";
5536
5537    // FIXME: Missing definition of
5538    // InsertText(clang::SourceLocation, char const*, unsigned int).
5539    // InsertText(startLoc, messString);
5540    // Tried this, but it didn't work either...
5541    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5542#endif
5543    return RewriteMessageExpr(MessExpr);
5544  }
5545
5546  if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5547        dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5548    return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5549  }
5550
5551  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5552    return RewriteObjCTryStmt(StmtTry);
5553
5554  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5555    return RewriteObjCSynchronizedStmt(StmtTry);
5556
5557  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5558    return RewriteObjCThrowStmt(StmtThrow);
5559
5560  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5561    return RewriteObjCProtocolExpr(ProtocolExp);
5562
5563  if (ObjCForCollectionStmt *StmtForCollection =
5564        dyn_cast<ObjCForCollectionStmt>(S))
5565    return RewriteObjCForCollectionStmt(StmtForCollection,
5566                                        OrigStmtRange.getEnd());
5567  if (BreakStmt *StmtBreakStmt =
5568      dyn_cast<BreakStmt>(S))
5569    return RewriteBreakStmt(StmtBreakStmt);
5570  if (ContinueStmt *StmtContinueStmt =
5571      dyn_cast<ContinueStmt>(S))
5572    return RewriteContinueStmt(StmtContinueStmt);
5573
5574  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5575  // and cast exprs.
5576  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5577    // FIXME: What we're doing here is modifying the type-specifier that
5578    // precedes the first Decl.  In the future the DeclGroup should have
5579    // a separate type-specifier that we can rewrite.
5580    // NOTE: We need to avoid rewriting the DeclStmt if it is within
5581    // the context of an ObjCForCollectionStmt. For example:
5582    //   NSArray *someArray;
5583    //   for (id <FooProtocol> index in someArray) ;
5584    // This is because RewriteObjCForCollectionStmt() does textual rewriting
5585    // and it depends on the original text locations/positions.
5586    if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5587      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5588
5589    // Blocks rewrite rules.
5590    for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5591         DI != DE; ++DI) {
5592      Decl *SD = *DI;
5593      if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5594        if (isTopLevelBlockPointerType(ND->getType()))
5595          RewriteBlockPointerDecl(ND);
5596        else if (ND->getType()->isFunctionPointerType())
5597          CheckFunctionPointerDecl(ND->getType(), ND);
5598        if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5599          if (VD->hasAttr<BlocksAttr>()) {
5600            static unsigned uniqueByrefDeclCount = 0;
5601            assert(!BlockByRefDeclNo.count(ND) &&
5602              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5603            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5604            RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5605          }
5606          else
5607            RewriteTypeOfDecl(VD);
5608        }
5609      }
5610      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5611        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5612          RewriteBlockPointerDecl(TD);
5613        else if (TD->getUnderlyingType()->isFunctionPointerType())
5614          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5615      }
5616    }
5617  }
5618
5619  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5620    RewriteObjCQualifiedInterfaceTypes(CE);
5621
5622  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5623      isa<DoStmt>(S) || isa<ForStmt>(S)) {
5624    assert(!Stmts.empty() && "Statement stack is empty");
5625    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5626             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5627            && "Statement stack mismatch");
5628    Stmts.pop_back();
5629  }
5630  // Handle blocks rewriting.
5631  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5632    ValueDecl *VD = DRE->getDecl();
5633    if (VD->hasAttr<BlocksAttr>())
5634      return RewriteBlockDeclRefExpr(DRE);
5635    if (HasLocalVariableExternalStorage(VD))
5636      return RewriteLocalVariableExternalStorage(DRE);
5637  }
5638
5639  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5640    if (CE->getCallee()->getType()->isBlockPointerType()) {
5641      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5642      ReplaceStmt(S, BlockCall);
5643      return BlockCall;
5644    }
5645  }
5646  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5647    RewriteCastExpr(CE);
5648  }
5649  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5650    RewriteImplicitCastObjCExpr(ICE);
5651  }
5652#if 0
5653
5654  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5655    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5656                                                   ICE->getSubExpr(),
5657                                                   SourceLocation());
5658    // Get the new text.
5659    std::string SStr;
5660    llvm::raw_string_ostream Buf(SStr);
5661    Replacement->printPretty(Buf);
5662    const std::string &Str = Buf.str();
5663
5664    printf("CAST = %s\n", &Str[0]);
5665    InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5666    delete S;
5667    return Replacement;
5668  }
5669#endif
5670  // Return this stmt unmodified.
5671  return S;
5672}
5673
5674void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5675  for (auto *FD : RD->fields()) {
5676    if (isTopLevelBlockPointerType(FD->getType()))
5677      RewriteBlockPointerDecl(FD);
5678    if (FD->getType()->isObjCQualifiedIdType() ||
5679        FD->getType()->isObjCQualifiedInterfaceType())
5680      RewriteObjCQualifiedInterfaceTypes(FD);
5681  }
5682}
5683
5684/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5685/// main file of the input.
5686void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5687  switch (D->getKind()) {
5688    case Decl::Function: {
5689      FunctionDecl *FD = cast<FunctionDecl>(D);
5690      if (FD->isOverloadedOperator())
5691        return;
5692
5693      // Since function prototypes don't have ParmDecl's, we check the function
5694      // prototype. This enables us to rewrite function declarations and
5695      // definitions using the same code.
5696      RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5697
5698      if (!FD->isThisDeclarationADefinition())
5699        break;
5700
5701      // FIXME: If this should support Obj-C++, support CXXTryStmt
5702      if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5703        CurFunctionDef = FD;
5704        CurrentBody = Body;
5705        Body =
5706        cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5707        FD->setBody(Body);
5708        CurrentBody = nullptr;
5709        if (PropParentMap) {
5710          delete PropParentMap;
5711          PropParentMap = nullptr;
5712        }
5713        // This synthesizes and inserts the block "impl" struct, invoke function,
5714        // and any copy/dispose helper functions.
5715        InsertBlockLiteralsWithinFunction(FD);
5716        RewriteLineDirective(D);
5717        CurFunctionDef = nullptr;
5718      }
5719      break;
5720    }
5721    case Decl::ObjCMethod: {
5722      ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5723      if (CompoundStmt *Body = MD->getCompoundBody()) {
5724        CurMethodDef = MD;
5725        CurrentBody = Body;
5726        Body =
5727          cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5728        MD->setBody(Body);
5729        CurrentBody = nullptr;
5730        if (PropParentMap) {
5731          delete PropParentMap;
5732          PropParentMap = nullptr;
5733        }
5734        InsertBlockLiteralsWithinMethod(MD);
5735        RewriteLineDirective(D);
5736        CurMethodDef = nullptr;
5737      }
5738      break;
5739    }
5740    case Decl::ObjCImplementation: {
5741      ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5742      ClassImplementation.push_back(CI);
5743      break;
5744    }
5745    case Decl::ObjCCategoryImpl: {
5746      ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5747      CategoryImplementation.push_back(CI);
5748      break;
5749    }
5750    case Decl::Var: {
5751      VarDecl *VD = cast<VarDecl>(D);
5752      RewriteObjCQualifiedInterfaceTypes(VD);
5753      if (isTopLevelBlockPointerType(VD->getType()))
5754        RewriteBlockPointerDecl(VD);
5755      else if (VD->getType()->isFunctionPointerType()) {
5756        CheckFunctionPointerDecl(VD->getType(), VD);
5757        if (VD->getInit()) {
5758          if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5759            RewriteCastExpr(CE);
5760          }
5761        }
5762      } else if (VD->getType()->isRecordType()) {
5763        RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
5764        if (RD->isCompleteDefinition())
5765          RewriteRecordBody(RD);
5766      }
5767      if (VD->getInit()) {
5768        GlobalVarDecl = VD;
5769        CurrentBody = VD->getInit();
5770        RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5771        CurrentBody = nullptr;
5772        if (PropParentMap) {
5773          delete PropParentMap;
5774          PropParentMap = nullptr;
5775        }
5776        SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5777        GlobalVarDecl = nullptr;
5778
5779        // This is needed for blocks.
5780        if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5781            RewriteCastExpr(CE);
5782        }
5783      }
5784      break;
5785    }
5786    case Decl::TypeAlias:
5787    case Decl::Typedef: {
5788      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5789        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5790          RewriteBlockPointerDecl(TD);
5791        else if (TD->getUnderlyingType()->isFunctionPointerType())
5792          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5793        else
5794          RewriteObjCQualifiedInterfaceTypes(TD);
5795      }
5796      break;
5797    }
5798    case Decl::CXXRecord:
5799    case Decl::Record: {
5800      RecordDecl *RD = cast<RecordDecl>(D);
5801      if (RD->isCompleteDefinition())
5802        RewriteRecordBody(RD);
5803      break;
5804    }
5805    default:
5806      break;
5807  }
5808  // Nothing yet.
5809}
5810
5811/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5812/// protocol reference symbols in the for of:
5813/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5814static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5815                                                 ObjCProtocolDecl *PDecl,
5816                                                 std::string &Result) {
5817  // Also output .objc_protorefs$B section and its meta-data.
5818  if (Context->getLangOpts().MicrosoftExt)
5819    Result += "static ";
5820  Result += "struct _protocol_t *";
5821  Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5822  Result += PDecl->getNameAsString();
5823  Result += " = &";
5824  Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5825  Result += ";\n";
5826}
5827
5828void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5829  if (Diags.hasErrorOccurred())
5830    return;
5831
5832  RewriteInclude();
5833
5834  for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5835    // translation of function bodies were postponed until all class and
5836    // their extensions and implementations are seen. This is because, we
5837    // cannot build grouping structs for bitfields until they are all seen.
5838    FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5839    HandleTopLevelSingleDecl(FDecl);
5840  }
5841
5842  // Here's a great place to add any extra declarations that may be needed.
5843  // Write out meta data for each @protocol(<expr>).
5844  for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5845    RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5846    Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5847  }
5848
5849  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5850
5851  if (ClassImplementation.size() || CategoryImplementation.size())
5852    RewriteImplementations();
5853
5854  for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5855    ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5856    // Write struct declaration for the class matching its ivar declarations.
5857    // Note that for modern abi, this is postponed until the end of TU
5858    // because class extensions and the implementation might declare their own
5859    // private ivars.
5860    RewriteInterfaceDecl(CDecl);
5861  }
5862
5863  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5864  // we are done.
5865  if (const RewriteBuffer *RewriteBuf =
5866      Rewrite.getRewriteBufferFor(MainFileID)) {
5867    //printf("Changed:\n");
5868    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5869  } else {
5870    llvm::errs() << "No changes\n";
5871  }
5872
5873  if (ClassImplementation.size() || CategoryImplementation.size() ||
5874      ProtocolExprDecls.size()) {
5875    // Rewrite Objective-c meta data*
5876    std::string ResultStr;
5877    RewriteMetaDataIntoBuffer(ResultStr);
5878    // Emit metadata.
5879    *OutFile << ResultStr;
5880  }
5881  // Emit ImageInfo;
5882  {
5883    std::string ResultStr;
5884    WriteImageInfo(ResultStr);
5885    *OutFile << ResultStr;
5886  }
5887  OutFile->flush();
5888}
5889
5890void RewriteModernObjC::Initialize(ASTContext &context) {
5891  InitializeCommon(context);
5892
5893  Preamble += "#ifndef __OBJC2__\n";
5894  Preamble += "#define __OBJC2__\n";
5895  Preamble += "#endif\n";
5896
5897  // declaring objc_selector outside the parameter list removes a silly
5898  // scope related warning...
5899  if (IsHeader)
5900    Preamble = "#pragma once\n";
5901  Preamble += "struct objc_selector; struct objc_class;\n";
5902  Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5903  Preamble += "\n\tstruct objc_object *superClass; ";
5904  // Add a constructor for creating temporary objects.
5905  Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5906  Preamble += ": object(o), superClass(s) {} ";
5907  Preamble += "\n};\n";
5908
5909  if (LangOpts.MicrosoftExt) {
5910    // Define all sections using syntax that makes sense.
5911    // These are currently generated.
5912    Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5913    Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5914    Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5915    Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5916    Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5917    // These are generated but not necessary for functionality.
5918    Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5919    Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5920    Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5921    Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5922
5923    // These need be generated for performance. Currently they are not,
5924    // using API calls instead.
5925    Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5926    Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5927    Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5928
5929  }
5930  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5931  Preamble += "typedef struct objc_object Protocol;\n";
5932  Preamble += "#define _REWRITER_typedef_Protocol\n";
5933  Preamble += "#endif\n";
5934  if (LangOpts.MicrosoftExt) {
5935    Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5936    Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5937  }
5938  else
5939    Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5940
5941  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5942  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5943  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5944  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5945  Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5946
5947  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5948  Preamble += "(const char *);\n";
5949  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5950  Preamble += "(struct objc_class *);\n";
5951  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5952  Preamble += "(const char *);\n";
5953  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5954  // @synchronized hooks.
5955  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5956  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5957  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5958  Preamble += "#ifdef _WIN64\n";
5959  Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
5960  Preamble += "#else\n";
5961  Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5962  Preamble += "#endif\n";
5963  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5964  Preamble += "struct __objcFastEnumerationState {\n\t";
5965  Preamble += "unsigned long state;\n\t";
5966  Preamble += "void **itemsPtr;\n\t";
5967  Preamble += "unsigned long *mutationsPtr;\n\t";
5968  Preamble += "unsigned long extra[5];\n};\n";
5969  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5970  Preamble += "#define __FASTENUMERATIONSTATE\n";
5971  Preamble += "#endif\n";
5972  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5973  Preamble += "struct __NSConstantStringImpl {\n";
5974  Preamble += "  int *isa;\n";
5975  Preamble += "  int flags;\n";
5976  Preamble += "  char *str;\n";
5977  Preamble += "#if _WIN64\n";
5978  Preamble += "  long long length;\n";
5979  Preamble += "#else\n";
5980  Preamble += "  long length;\n";
5981  Preamble += "#endif\n";
5982  Preamble += "};\n";
5983  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5984  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5985  Preamble += "#else\n";
5986  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5987  Preamble += "#endif\n";
5988  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5989  Preamble += "#endif\n";
5990  // Blocks preamble.
5991  Preamble += "#ifndef BLOCK_IMPL\n";
5992  Preamble += "#define BLOCK_IMPL\n";
5993  Preamble += "struct __block_impl {\n";
5994  Preamble += "  void *isa;\n";
5995  Preamble += "  int Flags;\n";
5996  Preamble += "  int Reserved;\n";
5997  Preamble += "  void *FuncPtr;\n";
5998  Preamble += "};\n";
5999  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6000  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6001  Preamble += "extern \"C\" __declspec(dllexport) "
6002  "void _Block_object_assign(void *, const void *, const int);\n";
6003  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6004  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6005  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6006  Preamble += "#else\n";
6007  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6008  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6009  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6010  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6011  Preamble += "#endif\n";
6012  Preamble += "#endif\n";
6013  if (LangOpts.MicrosoftExt) {
6014    Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6015    Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6016    Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
6017    Preamble += "#define __attribute__(X)\n";
6018    Preamble += "#endif\n";
6019    Preamble += "#ifndef __weak\n";
6020    Preamble += "#define __weak\n";
6021    Preamble += "#endif\n";
6022    Preamble += "#ifndef __block\n";
6023    Preamble += "#define __block\n";
6024    Preamble += "#endif\n";
6025  }
6026  else {
6027    Preamble += "#define __block\n";
6028    Preamble += "#define __weak\n";
6029  }
6030
6031  // Declarations required for modern objective-c array and dictionary literals.
6032  Preamble += "\n#include <stdarg.h>\n";
6033  Preamble += "struct __NSContainer_literal {\n";
6034  Preamble += "  void * *arr;\n";
6035  Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
6036  Preamble += "\tva_list marker;\n";
6037  Preamble += "\tva_start(marker, count);\n";
6038  Preamble += "\tarr = new void *[count];\n";
6039  Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6040  Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6041  Preamble += "\tva_end( marker );\n";
6042  Preamble += "  };\n";
6043  Preamble += "  ~__NSContainer_literal() {\n";
6044  Preamble += "\tdelete[] arr;\n";
6045  Preamble += "  }\n";
6046  Preamble += "};\n";
6047
6048  // Declaration required for implementation of @autoreleasepool statement.
6049  Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6050  Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6051  Preamble += "struct __AtAutoreleasePool {\n";
6052  Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6053  Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6054  Preamble += "  void * atautoreleasepoolobj;\n";
6055  Preamble += "};\n";
6056
6057  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6058  // as this avoids warning in any 64bit/32bit compilation model.
6059  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6060}
6061
6062/// RewriteIvarOffsetComputation - This routine synthesizes computation of
6063/// ivar offset.
6064void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6065                                                         std::string &Result) {
6066  Result += "__OFFSETOFIVAR__(struct ";
6067  Result += ivar->getContainingInterface()->getNameAsString();
6068  if (LangOpts.MicrosoftExt)
6069    Result += "_IMPL";
6070  Result += ", ";
6071  if (ivar->isBitField())
6072    ObjCIvarBitfieldGroupDecl(ivar, Result);
6073  else
6074    Result += ivar->getNameAsString();
6075  Result += ")";
6076}
6077
6078/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6079/// struct _prop_t {
6080///   const char *name;
6081///   char *attributes;
6082/// }
6083
6084/// struct _prop_list_t {
6085///   uint32_t entsize;      // sizeof(struct _prop_t)
6086///   uint32_t count_of_properties;
6087///   struct _prop_t prop_list[count_of_properties];
6088/// }
6089
6090/// struct _protocol_t;
6091
6092/// struct _protocol_list_t {
6093///   long protocol_count;   // Note, this is 32/64 bit
6094///   struct _protocol_t * protocol_list[protocol_count];
6095/// }
6096
6097/// struct _objc_method {
6098///   SEL _cmd;
6099///   const char *method_type;
6100///   char *_imp;
6101/// }
6102
6103/// struct _method_list_t {
6104///   uint32_t entsize;  // sizeof(struct _objc_method)
6105///   uint32_t method_count;
6106///   struct _objc_method method_list[method_count];
6107/// }
6108
6109/// struct _protocol_t {
6110///   id isa;  // NULL
6111///   const char *protocol_name;
6112///   const struct _protocol_list_t * protocol_list; // super protocols
6113///   const struct method_list_t *instance_methods;
6114///   const struct method_list_t *class_methods;
6115///   const struct method_list_t *optionalInstanceMethods;
6116///   const struct method_list_t *optionalClassMethods;
6117///   const struct _prop_list_t * properties;
6118///   const uint32_t size;  // sizeof(struct _protocol_t)
6119///   const uint32_t flags;  // = 0
6120///   const char ** extendedMethodTypes;
6121/// }
6122
6123/// struct _ivar_t {
6124///   unsigned long int *offset;  // pointer to ivar offset location
6125///   const char *name;
6126///   const char *type;
6127///   uint32_t alignment;
6128///   uint32_t size;
6129/// }
6130
6131/// struct _ivar_list_t {
6132///   uint32 entsize;  // sizeof(struct _ivar_t)
6133///   uint32 count;
6134///   struct _ivar_t list[count];
6135/// }
6136
6137/// struct _class_ro_t {
6138///   uint32_t flags;
6139///   uint32_t instanceStart;
6140///   uint32_t instanceSize;
6141///   uint32_t reserved;  // only when building for 64bit targets
6142///   const uint8_t *ivarLayout;
6143///   const char *name;
6144///   const struct _method_list_t *baseMethods;
6145///   const struct _protocol_list_t *baseProtocols;
6146///   const struct _ivar_list_t *ivars;
6147///   const uint8_t *weakIvarLayout;
6148///   const struct _prop_list_t *properties;
6149/// }
6150
6151/// struct _class_t {
6152///   struct _class_t *isa;
6153///   struct _class_t *superclass;
6154///   void *cache;
6155///   IMP *vtable;
6156///   struct _class_ro_t *ro;
6157/// }
6158
6159/// struct _category_t {
6160///   const char *name;
6161///   struct _class_t *cls;
6162///   const struct _method_list_t *instance_methods;
6163///   const struct _method_list_t *class_methods;
6164///   const struct _protocol_list_t *protocols;
6165///   const struct _prop_list_t *properties;
6166/// }
6167
6168/// MessageRefTy - LLVM for:
6169/// struct _message_ref_t {
6170///   IMP messenger;
6171///   SEL name;
6172/// };
6173
6174/// SuperMessageRefTy - LLVM for:
6175/// struct _super_message_ref_t {
6176///   SUPER_IMP messenger;
6177///   SEL name;
6178/// };
6179
6180static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6181  static bool meta_data_declared = false;
6182  if (meta_data_declared)
6183    return;
6184
6185  Result += "\nstruct _prop_t {\n";
6186  Result += "\tconst char *name;\n";
6187  Result += "\tconst char *attributes;\n";
6188  Result += "};\n";
6189
6190  Result += "\nstruct _protocol_t;\n";
6191
6192  Result += "\nstruct _objc_method {\n";
6193  Result += "\tstruct objc_selector * _cmd;\n";
6194  Result += "\tconst char *method_type;\n";
6195  Result += "\tvoid  *_imp;\n";
6196  Result += "};\n";
6197
6198  Result += "\nstruct _protocol_t {\n";
6199  Result += "\tvoid * isa;  // NULL\n";
6200  Result += "\tconst char *protocol_name;\n";
6201  Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6202  Result += "\tconst struct method_list_t *instance_methods;\n";
6203  Result += "\tconst struct method_list_t *class_methods;\n";
6204  Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6205  Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6206  Result += "\tconst struct _prop_list_t * properties;\n";
6207  Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6208  Result += "\tconst unsigned int flags;  // = 0\n";
6209  Result += "\tconst char ** extendedMethodTypes;\n";
6210  Result += "};\n";
6211
6212  Result += "\nstruct _ivar_t {\n";
6213  Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6214  Result += "\tconst char *name;\n";
6215  Result += "\tconst char *type;\n";
6216  Result += "\tunsigned int alignment;\n";
6217  Result += "\tunsigned int  size;\n";
6218  Result += "};\n";
6219
6220  Result += "\nstruct _class_ro_t {\n";
6221  Result += "\tunsigned int flags;\n";
6222  Result += "\tunsigned int instanceStart;\n";
6223  Result += "\tunsigned int instanceSize;\n";
6224  const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6225  if (Triple.getArch() == llvm::Triple::x86_64)
6226    Result += "\tunsigned int reserved;\n";
6227  Result += "\tconst unsigned char *ivarLayout;\n";
6228  Result += "\tconst char *name;\n";
6229  Result += "\tconst struct _method_list_t *baseMethods;\n";
6230  Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6231  Result += "\tconst struct _ivar_list_t *ivars;\n";
6232  Result += "\tconst unsigned char *weakIvarLayout;\n";
6233  Result += "\tconst struct _prop_list_t *properties;\n";
6234  Result += "};\n";
6235
6236  Result += "\nstruct _class_t {\n";
6237  Result += "\tstruct _class_t *isa;\n";
6238  Result += "\tstruct _class_t *superclass;\n";
6239  Result += "\tvoid *cache;\n";
6240  Result += "\tvoid *vtable;\n";
6241  Result += "\tstruct _class_ro_t *ro;\n";
6242  Result += "};\n";
6243
6244  Result += "\nstruct _category_t {\n";
6245  Result += "\tconst char *name;\n";
6246  Result += "\tstruct _class_t *cls;\n";
6247  Result += "\tconst struct _method_list_t *instance_methods;\n";
6248  Result += "\tconst struct _method_list_t *class_methods;\n";
6249  Result += "\tconst struct _protocol_list_t *protocols;\n";
6250  Result += "\tconst struct _prop_list_t *properties;\n";
6251  Result += "};\n";
6252
6253  Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6254  Result += "#pragma warning(disable:4273)\n";
6255  meta_data_declared = true;
6256}
6257
6258static void Write_protocol_list_t_TypeDecl(std::string &Result,
6259                                           long super_protocol_count) {
6260  Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6261  Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6262  Result += "\tstruct _protocol_t *super_protocols[";
6263  Result += utostr(super_protocol_count); Result += "];\n";
6264  Result += "}";
6265}
6266
6267static void Write_method_list_t_TypeDecl(std::string &Result,
6268                                         unsigned int method_count) {
6269  Result += "struct /*_method_list_t*/"; Result += " {\n";
6270  Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6271  Result += "\tunsigned int method_count;\n";
6272  Result += "\tstruct _objc_method method_list[";
6273  Result += utostr(method_count); Result += "];\n";
6274  Result += "}";
6275}
6276
6277static void Write__prop_list_t_TypeDecl(std::string &Result,
6278                                        unsigned int property_count) {
6279  Result += "struct /*_prop_list_t*/"; Result += " {\n";
6280  Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6281  Result += "\tunsigned int count_of_properties;\n";
6282  Result += "\tstruct _prop_t prop_list[";
6283  Result += utostr(property_count); Result += "];\n";
6284  Result += "}";
6285}
6286
6287static void Write__ivar_list_t_TypeDecl(std::string &Result,
6288                                        unsigned int ivar_count) {
6289  Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6290  Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6291  Result += "\tunsigned int count;\n";
6292  Result += "\tstruct _ivar_t ivar_list[";
6293  Result += utostr(ivar_count); Result += "];\n";
6294  Result += "}";
6295}
6296
6297static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6298                                            ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6299                                            StringRef VarName,
6300                                            StringRef ProtocolName) {
6301  if (SuperProtocols.size() > 0) {
6302    Result += "\nstatic ";
6303    Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6304    Result += " "; Result += VarName;
6305    Result += ProtocolName;
6306    Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6307    Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6308    for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6309      ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6310      Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6311      Result += SuperPD->getNameAsString();
6312      if (i == e-1)
6313        Result += "\n};\n";
6314      else
6315        Result += ",\n";
6316    }
6317  }
6318}
6319
6320static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6321                                            ASTContext *Context, std::string &Result,
6322                                            ArrayRef<ObjCMethodDecl *> Methods,
6323                                            StringRef VarName,
6324                                            StringRef TopLevelDeclName,
6325                                            bool MethodImpl) {
6326  if (Methods.size() > 0) {
6327    Result += "\nstatic ";
6328    Write_method_list_t_TypeDecl(Result, Methods.size());
6329    Result += " "; Result += VarName;
6330    Result += TopLevelDeclName;
6331    Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6332    Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6333    Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6334    for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6335      ObjCMethodDecl *MD = Methods[i];
6336      if (i == 0)
6337        Result += "\t{{(struct objc_selector *)\"";
6338      else
6339        Result += "\t{(struct objc_selector *)\"";
6340      Result += (MD)->getSelector().getAsString(); Result += "\"";
6341      Result += ", ";
6342      std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6343      Result += "\""; Result += MethodTypeString; Result += "\"";
6344      Result += ", ";
6345      if (!MethodImpl)
6346        Result += "0";
6347      else {
6348        Result += "(void *)";
6349        Result += RewriteObj.MethodInternalNames[MD];
6350      }
6351      if (i  == e-1)
6352        Result += "}}\n";
6353      else
6354        Result += "},\n";
6355    }
6356    Result += "};\n";
6357  }
6358}
6359
6360static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6361                                           ASTContext *Context, std::string &Result,
6362                                           ArrayRef<ObjCPropertyDecl *> Properties,
6363                                           const Decl *Container,
6364                                           StringRef VarName,
6365                                           StringRef ProtocolName) {
6366  if (Properties.size() > 0) {
6367    Result += "\nstatic ";
6368    Write__prop_list_t_TypeDecl(Result, Properties.size());
6369    Result += " "; Result += VarName;
6370    Result += ProtocolName;
6371    Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6372    Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6373    Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6374    for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6375      ObjCPropertyDecl *PropDecl = Properties[i];
6376      if (i == 0)
6377        Result += "\t{{\"";
6378      else
6379        Result += "\t{\"";
6380      Result += PropDecl->getName(); Result += "\",";
6381      std::string PropertyTypeString =
6382        Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6383      std::string QuotePropertyTypeString;
6384      RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6385      Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6386      if (i  == e-1)
6387        Result += "}}\n";
6388      else
6389        Result += "},\n";
6390    }
6391    Result += "};\n";
6392  }
6393}
6394
6395// Metadata flags
6396enum MetaDataDlags {
6397  CLS = 0x0,
6398  CLS_META = 0x1,
6399  CLS_ROOT = 0x2,
6400  OBJC2_CLS_HIDDEN = 0x10,
6401  CLS_EXCEPTION = 0x20,
6402
6403  /// (Obsolete) ARC-specific: this class has a .release_ivars method
6404  CLS_HAS_IVAR_RELEASER = 0x40,
6405  /// class was compiled with -fobjc-arr
6406  CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6407};
6408
6409static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6410                                          unsigned int flags,
6411                                          const std::string &InstanceStart,
6412                                          const std::string &InstanceSize,
6413                                          ArrayRef<ObjCMethodDecl *>baseMethods,
6414                                          ArrayRef<ObjCProtocolDecl *>baseProtocols,
6415                                          ArrayRef<ObjCIvarDecl *>ivars,
6416                                          ArrayRef<ObjCPropertyDecl *>Properties,
6417                                          StringRef VarName,
6418                                          StringRef ClassName) {
6419  Result += "\nstatic struct _class_ro_t ";
6420  Result += VarName; Result += ClassName;
6421  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6422  Result += "\t";
6423  Result += llvm::utostr(flags); Result += ", ";
6424  Result += InstanceStart; Result += ", ";
6425  Result += InstanceSize; Result += ", \n";
6426  Result += "\t";
6427  const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6428  if (Triple.getArch() == llvm::Triple::x86_64)
6429    // uint32_t const reserved; // only when building for 64bit targets
6430    Result += "(unsigned int)0, \n\t";
6431  // const uint8_t * const ivarLayout;
6432  Result += "0, \n\t";
6433  Result += "\""; Result += ClassName; Result += "\",\n\t";
6434  bool metaclass = ((flags & CLS_META) != 0);
6435  if (baseMethods.size() > 0) {
6436    Result += "(const struct _method_list_t *)&";
6437    if (metaclass)
6438      Result += "_OBJC_$_CLASS_METHODS_";
6439    else
6440      Result += "_OBJC_$_INSTANCE_METHODS_";
6441    Result += ClassName;
6442    Result += ",\n\t";
6443  }
6444  else
6445    Result += "0, \n\t";
6446
6447  if (!metaclass && baseProtocols.size() > 0) {
6448    Result += "(const struct _objc_protocol_list *)&";
6449    Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6450    Result += ",\n\t";
6451  }
6452  else
6453    Result += "0, \n\t";
6454
6455  if (!metaclass && ivars.size() > 0) {
6456    Result += "(const struct _ivar_list_t *)&";
6457    Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6458    Result += ",\n\t";
6459  }
6460  else
6461    Result += "0, \n\t";
6462
6463  // weakIvarLayout
6464  Result += "0, \n\t";
6465  if (!metaclass && Properties.size() > 0) {
6466    Result += "(const struct _prop_list_t *)&";
6467    Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6468    Result += ",\n";
6469  }
6470  else
6471    Result += "0, \n";
6472
6473  Result += "};\n";
6474}
6475
6476static void Write_class_t(ASTContext *Context, std::string &Result,
6477                          StringRef VarName,
6478                          const ObjCInterfaceDecl *CDecl, bool metaclass) {
6479  bool rootClass = (!CDecl->getSuperClass());
6480  const ObjCInterfaceDecl *RootClass = CDecl;
6481
6482  if (!rootClass) {
6483    // Find the Root class
6484    RootClass = CDecl->getSuperClass();
6485    while (RootClass->getSuperClass()) {
6486      RootClass = RootClass->getSuperClass();
6487    }
6488  }
6489
6490  if (metaclass && rootClass) {
6491    // Need to handle a case of use of forward declaration.
6492    Result += "\n";
6493    Result += "extern \"C\" ";
6494    if (CDecl->getImplementation())
6495      Result += "__declspec(dllexport) ";
6496    else
6497      Result += "__declspec(dllimport) ";
6498
6499    Result += "struct _class_t OBJC_CLASS_$_";
6500    Result += CDecl->getNameAsString();
6501    Result += ";\n";
6502  }
6503  // Also, for possibility of 'super' metadata class not having been defined yet.
6504  if (!rootClass) {
6505    ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6506    Result += "\n";
6507    Result += "extern \"C\" ";
6508    if (SuperClass->getImplementation())
6509      Result += "__declspec(dllexport) ";
6510    else
6511      Result += "__declspec(dllimport) ";
6512
6513    Result += "struct _class_t ";
6514    Result += VarName;
6515    Result += SuperClass->getNameAsString();
6516    Result += ";\n";
6517
6518    if (metaclass && RootClass != SuperClass) {
6519      Result += "extern \"C\" ";
6520      if (RootClass->getImplementation())
6521        Result += "__declspec(dllexport) ";
6522      else
6523        Result += "__declspec(dllimport) ";
6524
6525      Result += "struct _class_t ";
6526      Result += VarName;
6527      Result += RootClass->getNameAsString();
6528      Result += ";\n";
6529    }
6530  }
6531
6532  Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6533  Result += VarName; Result += CDecl->getNameAsString();
6534  Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6535  Result += "\t";
6536  if (metaclass) {
6537    if (!rootClass) {
6538      Result += "0, // &"; Result += VarName;
6539      Result += RootClass->getNameAsString();
6540      Result += ",\n\t";
6541      Result += "0, // &"; Result += VarName;
6542      Result += CDecl->getSuperClass()->getNameAsString();
6543      Result += ",\n\t";
6544    }
6545    else {
6546      Result += "0, // &"; Result += VarName;
6547      Result += CDecl->getNameAsString();
6548      Result += ",\n\t";
6549      Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6550      Result += ",\n\t";
6551    }
6552  }
6553  else {
6554    Result += "0, // &OBJC_METACLASS_$_";
6555    Result += CDecl->getNameAsString();
6556    Result += ",\n\t";
6557    if (!rootClass) {
6558      Result += "0, // &"; Result += VarName;
6559      Result += CDecl->getSuperClass()->getNameAsString();
6560      Result += ",\n\t";
6561    }
6562    else
6563      Result += "0,\n\t";
6564  }
6565  Result += "0, // (void *)&_objc_empty_cache,\n\t";
6566  Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6567  if (metaclass)
6568    Result += "&_OBJC_METACLASS_RO_$_";
6569  else
6570    Result += "&_OBJC_CLASS_RO_$_";
6571  Result += CDecl->getNameAsString();
6572  Result += ",\n};\n";
6573
6574  // Add static function to initialize some of the meta-data fields.
6575  // avoid doing it twice.
6576  if (metaclass)
6577    return;
6578
6579  const ObjCInterfaceDecl *SuperClass =
6580    rootClass ? CDecl : CDecl->getSuperClass();
6581
6582  Result += "static void OBJC_CLASS_SETUP_$_";
6583  Result += CDecl->getNameAsString();
6584  Result += "(void ) {\n";
6585  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6586  Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6587  Result += RootClass->getNameAsString(); Result += ";\n";
6588
6589  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6590  Result += ".superclass = ";
6591  if (rootClass)
6592    Result += "&OBJC_CLASS_$_";
6593  else
6594     Result += "&OBJC_METACLASS_$_";
6595
6596  Result += SuperClass->getNameAsString(); Result += ";\n";
6597
6598  Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6599  Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6600
6601  Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6602  Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6603  Result += CDecl->getNameAsString(); Result += ";\n";
6604
6605  if (!rootClass) {
6606    Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6607    Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6608    Result += SuperClass->getNameAsString(); Result += ";\n";
6609  }
6610
6611  Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6612  Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6613  Result += "}\n";
6614}
6615
6616static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6617                             std::string &Result,
6618                             ObjCCategoryDecl *CatDecl,
6619                             ObjCInterfaceDecl *ClassDecl,
6620                             ArrayRef<ObjCMethodDecl *> InstanceMethods,
6621                             ArrayRef<ObjCMethodDecl *> ClassMethods,
6622                             ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6623                             ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6624  StringRef CatName = CatDecl->getName();
6625  StringRef ClassName = ClassDecl->getName();
6626  // must declare an extern class object in case this class is not implemented
6627  // in this TU.
6628  Result += "\n";
6629  Result += "extern \"C\" ";
6630  if (ClassDecl->getImplementation())
6631    Result += "__declspec(dllexport) ";
6632  else
6633    Result += "__declspec(dllimport) ";
6634
6635  Result += "struct _class_t ";
6636  Result += "OBJC_CLASS_$_"; Result += ClassName;
6637  Result += ";\n";
6638
6639  Result += "\nstatic struct _category_t ";
6640  Result += "_OBJC_$_CATEGORY_";
6641  Result += ClassName; Result += "_$_"; Result += CatName;
6642  Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6643  Result += "{\n";
6644  Result += "\t\""; Result += ClassName; Result += "\",\n";
6645  Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6646  Result += ",\n";
6647  if (InstanceMethods.size() > 0) {
6648    Result += "\t(const struct _method_list_t *)&";
6649    Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6650    Result += ClassName; Result += "_$_"; Result += CatName;
6651    Result += ",\n";
6652  }
6653  else
6654    Result += "\t0,\n";
6655
6656  if (ClassMethods.size() > 0) {
6657    Result += "\t(const struct _method_list_t *)&";
6658    Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6659    Result += ClassName; Result += "_$_"; Result += CatName;
6660    Result += ",\n";
6661  }
6662  else
6663    Result += "\t0,\n";
6664
6665  if (RefedProtocols.size() > 0) {
6666    Result += "\t(const struct _protocol_list_t *)&";
6667    Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6668    Result += ClassName; Result += "_$_"; Result += CatName;
6669    Result += ",\n";
6670  }
6671  else
6672    Result += "\t0,\n";
6673
6674  if (ClassProperties.size() > 0) {
6675    Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6676    Result += ClassName; Result += "_$_"; Result += CatName;
6677    Result += ",\n";
6678  }
6679  else
6680    Result += "\t0,\n";
6681
6682  Result += "};\n";
6683
6684  // Add static function to initialize the class pointer in the category structure.
6685  Result += "static void OBJC_CATEGORY_SETUP_$_";
6686  Result += ClassDecl->getNameAsString();
6687  Result += "_$_";
6688  Result += CatName;
6689  Result += "(void ) {\n";
6690  Result += "\t_OBJC_$_CATEGORY_";
6691  Result += ClassDecl->getNameAsString();
6692  Result += "_$_";
6693  Result += CatName;
6694  Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6695  Result += ";\n}\n";
6696}
6697
6698static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6699                                           ASTContext *Context, std::string &Result,
6700                                           ArrayRef<ObjCMethodDecl *> Methods,
6701                                           StringRef VarName,
6702                                           StringRef ProtocolName) {
6703  if (Methods.size() == 0)
6704    return;
6705
6706  Result += "\nstatic const char *";
6707  Result += VarName; Result += ProtocolName;
6708  Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6709  Result += "{\n";
6710  for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6711    ObjCMethodDecl *MD = Methods[i];
6712    std::string MethodTypeString =
6713      Context->getObjCEncodingForMethodDecl(MD, true);
6714    std::string QuoteMethodTypeString;
6715    RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6716    Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6717    if (i == e-1)
6718      Result += "\n};\n";
6719    else {
6720      Result += ",\n";
6721    }
6722  }
6723}
6724
6725static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6726                                ASTContext *Context,
6727                                std::string &Result,
6728                                ArrayRef<ObjCIvarDecl *> Ivars,
6729                                ObjCInterfaceDecl *CDecl) {
6730  // FIXME. visibilty of offset symbols may have to be set; for Darwin
6731  // this is what happens:
6732  /**
6733   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6734       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6735       Class->getVisibility() == HiddenVisibility)
6736     Visibility should be: HiddenVisibility;
6737   else
6738     Visibility should be: DefaultVisibility;
6739  */
6740
6741  Result += "\n";
6742  for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6743    ObjCIvarDecl *IvarDecl = Ivars[i];
6744    if (Context->getLangOpts().MicrosoftExt)
6745      Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6746
6747    if (!Context->getLangOpts().MicrosoftExt ||
6748        IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6749        IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6750      Result += "extern \"C\" unsigned long int ";
6751    else
6752      Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6753    if (Ivars[i]->isBitField())
6754      RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6755    else
6756      WriteInternalIvarName(CDecl, IvarDecl, Result);
6757    Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6758    Result += " = ";
6759    RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6760    Result += ";\n";
6761    if (Ivars[i]->isBitField()) {
6762      // skip over rest of the ivar bitfields.
6763      SKIP_BITFIELDS(i , e, Ivars);
6764    }
6765  }
6766}
6767
6768static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6769                                           ASTContext *Context, std::string &Result,
6770                                           ArrayRef<ObjCIvarDecl *> OriginalIvars,
6771                                           StringRef VarName,
6772                                           ObjCInterfaceDecl *CDecl) {
6773  if (OriginalIvars.size() > 0) {
6774    Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6775    SmallVector<ObjCIvarDecl *, 8> Ivars;
6776    // strip off all but the first ivar bitfield from each group of ivars.
6777    // Such ivars in the ivar list table will be replaced by their grouping struct
6778    // 'ivar'.
6779    for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6780      if (OriginalIvars[i]->isBitField()) {
6781        Ivars.push_back(OriginalIvars[i]);
6782        // skip over rest of the ivar bitfields.
6783        SKIP_BITFIELDS(i , e, OriginalIvars);
6784      }
6785      else
6786        Ivars.push_back(OriginalIvars[i]);
6787    }
6788
6789    Result += "\nstatic ";
6790    Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6791    Result += " "; Result += VarName;
6792    Result += CDecl->getNameAsString();
6793    Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6794    Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6795    Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6796    for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6797      ObjCIvarDecl *IvarDecl = Ivars[i];
6798      if (i == 0)
6799        Result += "\t{{";
6800      else
6801        Result += "\t {";
6802      Result += "(unsigned long int *)&";
6803      if (Ivars[i]->isBitField())
6804        RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6805      else
6806        WriteInternalIvarName(CDecl, IvarDecl, Result);
6807      Result += ", ";
6808
6809      Result += "\"";
6810      if (Ivars[i]->isBitField())
6811        RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6812      else
6813        Result += IvarDecl->getName();
6814      Result += "\", ";
6815
6816      QualType IVQT = IvarDecl->getType();
6817      if (IvarDecl->isBitField())
6818        IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6819
6820      std::string IvarTypeString, QuoteIvarTypeString;
6821      Context->getObjCEncodingForType(IVQT, IvarTypeString,
6822                                      IvarDecl);
6823      RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6824      Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6825
6826      // FIXME. this alignment represents the host alignment and need be changed to
6827      // represent the target alignment.
6828      unsigned Align = Context->getTypeAlign(IVQT)/8;
6829      Align = llvm::Log2_32(Align);
6830      Result += llvm::utostr(Align); Result += ", ";
6831      CharUnits Size = Context->getTypeSizeInChars(IVQT);
6832      Result += llvm::utostr(Size.getQuantity());
6833      if (i  == e-1)
6834        Result += "}}\n";
6835      else
6836        Result += "},\n";
6837    }
6838    Result += "};\n";
6839  }
6840}
6841
6842/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6843void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6844                                                    std::string &Result) {
6845
6846  // Do not synthesize the protocol more than once.
6847  if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6848    return;
6849  WriteModernMetadataDeclarations(Context, Result);
6850
6851  if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6852    PDecl = Def;
6853  // Must write out all protocol definitions in current qualifier list,
6854  // and in their nested qualifiers before writing out current definition.
6855  for (auto *I : PDecl->protocols())
6856    RewriteObjCProtocolMetaData(I, Result);
6857
6858  // Construct method lists.
6859  std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6860  std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6861  for (auto *MD : PDecl->instance_methods()) {
6862    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6863      OptInstanceMethods.push_back(MD);
6864    } else {
6865      InstanceMethods.push_back(MD);
6866    }
6867  }
6868
6869  for (auto *MD : PDecl->class_methods()) {
6870    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6871      OptClassMethods.push_back(MD);
6872    } else {
6873      ClassMethods.push_back(MD);
6874    }
6875  }
6876  std::vector<ObjCMethodDecl *> AllMethods;
6877  for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6878    AllMethods.push_back(InstanceMethods[i]);
6879  for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6880    AllMethods.push_back(ClassMethods[i]);
6881  for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6882    AllMethods.push_back(OptInstanceMethods[i]);
6883  for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6884    AllMethods.push_back(OptClassMethods[i]);
6885
6886  Write__extendedMethodTypes_initializer(*this, Context, Result,
6887                                         AllMethods,
6888                                         "_OBJC_PROTOCOL_METHOD_TYPES_",
6889                                         PDecl->getNameAsString());
6890  // Protocol's super protocol list
6891  SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6892  Write_protocol_list_initializer(Context, Result, SuperProtocols,
6893                                  "_OBJC_PROTOCOL_REFS_",
6894                                  PDecl->getNameAsString());
6895
6896  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6897                                  "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6898                                  PDecl->getNameAsString(), false);
6899
6900  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6901                                  "_OBJC_PROTOCOL_CLASS_METHODS_",
6902                                  PDecl->getNameAsString(), false);
6903
6904  Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6905                                  "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6906                                  PDecl->getNameAsString(), false);
6907
6908  Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6909                                  "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6910                                  PDecl->getNameAsString(), false);
6911
6912  // Protocol's property metadata.
6913  SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6914      PDecl->instance_properties());
6915  Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6916                                 /* Container */nullptr,
6917                                 "_OBJC_PROTOCOL_PROPERTIES_",
6918                                 PDecl->getNameAsString());
6919
6920  // Writer out root metadata for current protocol: struct _protocol_t
6921  Result += "\n";
6922  if (LangOpts.MicrosoftExt)
6923    Result += "static ";
6924  Result += "struct _protocol_t _OBJC_PROTOCOL_";
6925  Result += PDecl->getNameAsString();
6926  Result += " __attribute__ ((used)) = {\n";
6927  Result += "\t0,\n"; // id is; is null
6928  Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6929  if (SuperProtocols.size() > 0) {
6930    Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6931    Result += PDecl->getNameAsString(); Result += ",\n";
6932  }
6933  else
6934    Result += "\t0,\n";
6935  if (InstanceMethods.size() > 0) {
6936    Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6937    Result += PDecl->getNameAsString(); Result += ",\n";
6938  }
6939  else
6940    Result += "\t0,\n";
6941
6942  if (ClassMethods.size() > 0) {
6943    Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6944    Result += PDecl->getNameAsString(); Result += ",\n";
6945  }
6946  else
6947    Result += "\t0,\n";
6948
6949  if (OptInstanceMethods.size() > 0) {
6950    Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6951    Result += PDecl->getNameAsString(); Result += ",\n";
6952  }
6953  else
6954    Result += "\t0,\n";
6955
6956  if (OptClassMethods.size() > 0) {
6957    Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6958    Result += PDecl->getNameAsString(); Result += ",\n";
6959  }
6960  else
6961    Result += "\t0,\n";
6962
6963  if (ProtocolProperties.size() > 0) {
6964    Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6965    Result += PDecl->getNameAsString(); Result += ",\n";
6966  }
6967  else
6968    Result += "\t0,\n";
6969
6970  Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6971  Result += "\t0,\n";
6972
6973  if (AllMethods.size() > 0) {
6974    Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6975    Result += PDecl->getNameAsString();
6976    Result += "\n};\n";
6977  }
6978  else
6979    Result += "\t0\n};\n";
6980
6981  if (LangOpts.MicrosoftExt)
6982    Result += "static ";
6983  Result += "struct _protocol_t *";
6984  Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6985  Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6986  Result += ";\n";
6987
6988  // Mark this protocol as having been generated.
6989  if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6990    llvm_unreachable("protocol already synthesized");
6991}
6992
6993/// hasObjCExceptionAttribute - Return true if this class or any super
6994/// class has the __objc_exception__ attribute.
6995/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6996static bool hasObjCExceptionAttribute(ASTContext &Context,
6997                                      const ObjCInterfaceDecl *OID) {
6998  if (OID->hasAttr<ObjCExceptionAttr>())
6999    return true;
7000  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7001    return hasObjCExceptionAttribute(Context, Super);
7002  return false;
7003}
7004
7005void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7006                                           std::string &Result) {
7007  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7008
7009  // Explicitly declared @interface's are already synthesized.
7010  if (CDecl->isImplicitInterfaceDecl())
7011    assert(false &&
7012           "Legacy implicit interface rewriting not supported in moder abi");
7013
7014  WriteModernMetadataDeclarations(Context, Result);
7015  SmallVector<ObjCIvarDecl *, 8> IVars;
7016
7017  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7018      IVD; IVD = IVD->getNextIvar()) {
7019    // Ignore unnamed bit-fields.
7020    if (!IVD->getDeclName())
7021      continue;
7022    IVars.push_back(IVD);
7023  }
7024
7025  Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7026                                 "_OBJC_$_INSTANCE_VARIABLES_",
7027                                 CDecl);
7028
7029  // Build _objc_method_list for class's instance methods if needed
7030  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7031
7032  // If any of our property implementations have associated getters or
7033  // setters, produce metadata for them as well.
7034  for (const auto *Prop : IDecl->property_impls()) {
7035    if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7036      continue;
7037    if (!Prop->getPropertyIvarDecl())
7038      continue;
7039    ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7040    if (!PD)
7041      continue;
7042    if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7043      if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7044        InstanceMethods.push_back(Getter);
7045    if (PD->isReadOnly())
7046      continue;
7047    if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7048      if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7049        InstanceMethods.push_back(Setter);
7050  }
7051
7052  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7053                                  "_OBJC_$_INSTANCE_METHODS_",
7054                                  IDecl->getNameAsString(), true);
7055
7056  SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7057
7058  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7059                                  "_OBJC_$_CLASS_METHODS_",
7060                                  IDecl->getNameAsString(), true);
7061
7062  // Protocols referenced in class declaration?
7063  // Protocol's super protocol list
7064  std::vector<ObjCProtocolDecl *> RefedProtocols;
7065  const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7066  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7067       E = Protocols.end();
7068       I != E; ++I) {
7069    RefedProtocols.push_back(*I);
7070    // Must write out all protocol definitions in current qualifier list,
7071    // and in their nested qualifiers before writing out current definition.
7072    RewriteObjCProtocolMetaData(*I, Result);
7073  }
7074
7075  Write_protocol_list_initializer(Context, Result,
7076                                  RefedProtocols,
7077                                  "_OBJC_CLASS_PROTOCOLS_$_",
7078                                  IDecl->getNameAsString());
7079
7080  // Protocol's property metadata.
7081  SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7082      CDecl->instance_properties());
7083  Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7084                                 /* Container */IDecl,
7085                                 "_OBJC_$_PROP_LIST_",
7086                                 CDecl->getNameAsString());
7087
7088  // Data for initializing _class_ro_t  metaclass meta-data
7089  uint32_t flags = CLS_META;
7090  std::string InstanceSize;
7091  std::string InstanceStart;
7092
7093  bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7094  if (classIsHidden)
7095    flags |= OBJC2_CLS_HIDDEN;
7096
7097  if (!CDecl->getSuperClass())
7098    // class is root
7099    flags |= CLS_ROOT;
7100  InstanceSize = "sizeof(struct _class_t)";
7101  InstanceStart = InstanceSize;
7102  Write__class_ro_t_initializer(Context, Result, flags,
7103                                InstanceStart, InstanceSize,
7104                                ClassMethods,
7105                                nullptr,
7106                                nullptr,
7107                                nullptr,
7108                                "_OBJC_METACLASS_RO_$_",
7109                                CDecl->getNameAsString());
7110
7111  // Data for initializing _class_ro_t meta-data
7112  flags = CLS;
7113  if (classIsHidden)
7114    flags |= OBJC2_CLS_HIDDEN;
7115
7116  if (hasObjCExceptionAttribute(*Context, CDecl))
7117    flags |= CLS_EXCEPTION;
7118
7119  if (!CDecl->getSuperClass())
7120    // class is root
7121    flags |= CLS_ROOT;
7122
7123  InstanceSize.clear();
7124  InstanceStart.clear();
7125  if (!ObjCSynthesizedStructs.count(CDecl)) {
7126    InstanceSize = "0";
7127    InstanceStart = "0";
7128  }
7129  else {
7130    InstanceSize = "sizeof(struct ";
7131    InstanceSize += CDecl->getNameAsString();
7132    InstanceSize += "_IMPL)";
7133
7134    ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7135    if (IVD) {
7136      RewriteIvarOffsetComputation(IVD, InstanceStart);
7137    }
7138    else
7139      InstanceStart = InstanceSize;
7140  }
7141  Write__class_ro_t_initializer(Context, Result, flags,
7142                                InstanceStart, InstanceSize,
7143                                InstanceMethods,
7144                                RefedProtocols,
7145                                IVars,
7146                                ClassProperties,
7147                                "_OBJC_CLASS_RO_$_",
7148                                CDecl->getNameAsString());
7149
7150  Write_class_t(Context, Result,
7151                "OBJC_METACLASS_$_",
7152                CDecl, /*metaclass*/true);
7153
7154  Write_class_t(Context, Result,
7155                "OBJC_CLASS_$_",
7156                CDecl, /*metaclass*/false);
7157
7158  if (ImplementationIsNonLazy(IDecl))
7159    DefinedNonLazyClasses.push_back(CDecl);
7160}
7161
7162void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7163  int ClsDefCount = ClassImplementation.size();
7164  if (!ClsDefCount)
7165    return;
7166  Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7167  Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7168  Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7169  for (int i = 0; i < ClsDefCount; i++) {
7170    ObjCImplementationDecl *IDecl = ClassImplementation[i];
7171    ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7172    Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7173    Result  += CDecl->getName(); Result += ",\n";
7174  }
7175  Result += "};\n";
7176}
7177
7178void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7179  int ClsDefCount = ClassImplementation.size();
7180  int CatDefCount = CategoryImplementation.size();
7181
7182  // For each implemented class, write out all its meta data.
7183  for (int i = 0; i < ClsDefCount; i++)
7184    RewriteObjCClassMetaData(ClassImplementation[i], Result);
7185
7186  RewriteClassSetupInitHook(Result);
7187
7188  // For each implemented category, write out all its meta data.
7189  for (int i = 0; i < CatDefCount; i++)
7190    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7191
7192  RewriteCategorySetupInitHook(Result);
7193
7194  if (ClsDefCount > 0) {
7195    if (LangOpts.MicrosoftExt)
7196      Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7197    Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7198    Result += llvm::utostr(ClsDefCount); Result += "]";
7199    Result +=
7200      " __attribute__((used, section (\"__DATA, __objc_classlist,"
7201      "regular,no_dead_strip\")))= {\n";
7202    for (int i = 0; i < ClsDefCount; i++) {
7203      Result += "\t&OBJC_CLASS_$_";
7204      Result += ClassImplementation[i]->getNameAsString();
7205      Result += ",\n";
7206    }
7207    Result += "};\n";
7208
7209    if (!DefinedNonLazyClasses.empty()) {
7210      if (LangOpts.MicrosoftExt)
7211        Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7212      Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7213      for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7214        Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7215        Result += ",\n";
7216      }
7217      Result += "};\n";
7218    }
7219  }
7220
7221  if (CatDefCount > 0) {
7222    if (LangOpts.MicrosoftExt)
7223      Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7224    Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7225    Result += llvm::utostr(CatDefCount); Result += "]";
7226    Result +=
7227    " __attribute__((used, section (\"__DATA, __objc_catlist,"
7228    "regular,no_dead_strip\")))= {\n";
7229    for (int i = 0; i < CatDefCount; i++) {
7230      Result += "\t&_OBJC_$_CATEGORY_";
7231      Result +=
7232        CategoryImplementation[i]->getClassInterface()->getNameAsString();
7233      Result += "_$_";
7234      Result += CategoryImplementation[i]->getNameAsString();
7235      Result += ",\n";
7236    }
7237    Result += "};\n";
7238  }
7239
7240  if (!DefinedNonLazyCategories.empty()) {
7241    if (LangOpts.MicrosoftExt)
7242      Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7243    Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7244    for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7245      Result += "\t&_OBJC_$_CATEGORY_";
7246      Result +=
7247        DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7248      Result += "_$_";
7249      Result += DefinedNonLazyCategories[i]->getNameAsString();
7250      Result += ",\n";
7251    }
7252    Result += "};\n";
7253  }
7254}
7255
7256void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7257  if (LangOpts.MicrosoftExt)
7258    Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7259
7260  Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7261  // version 0, ObjCABI is 2
7262  Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7263}
7264
7265/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7266/// implementation.
7267void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7268                                              std::string &Result) {
7269  WriteModernMetadataDeclarations(Context, Result);
7270  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7271  // Find category declaration for this implementation.
7272  ObjCCategoryDecl *CDecl
7273    = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7274
7275  std::string FullCategoryName = ClassDecl->getNameAsString();
7276  FullCategoryName += "_$_";
7277  FullCategoryName += CDecl->getNameAsString();
7278
7279  // Build _objc_method_list for class's instance methods if needed
7280  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7281
7282  // If any of our property implementations have associated getters or
7283  // setters, produce metadata for them as well.
7284  for (const auto *Prop : IDecl->property_impls()) {
7285    if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7286      continue;
7287    if (!Prop->getPropertyIvarDecl())
7288      continue;
7289    ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7290    if (!PD)
7291      continue;
7292    if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7293      InstanceMethods.push_back(Getter);
7294    if (PD->isReadOnly())
7295      continue;
7296    if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7297      InstanceMethods.push_back(Setter);
7298  }
7299
7300  Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7301                                  "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7302                                  FullCategoryName, true);
7303
7304  SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7305
7306  Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7307                                  "_OBJC_$_CATEGORY_CLASS_METHODS_",
7308                                  FullCategoryName, true);
7309
7310  // Protocols referenced in class declaration?
7311  // Protocol's super protocol list
7312  SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7313  for (auto *I : CDecl->protocols())
7314    // Must write out all protocol definitions in current qualifier list,
7315    // and in their nested qualifiers before writing out current definition.
7316    RewriteObjCProtocolMetaData(I, Result);
7317
7318  Write_protocol_list_initializer(Context, Result,
7319                                  RefedProtocols,
7320                                  "_OBJC_CATEGORY_PROTOCOLS_$_",
7321                                  FullCategoryName);
7322
7323  // Protocol's property metadata.
7324  SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7325      CDecl->instance_properties());
7326  Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7327                                /* Container */IDecl,
7328                                "_OBJC_$_PROP_LIST_",
7329                                FullCategoryName);
7330
7331  Write_category_t(*this, Context, Result,
7332                   CDecl,
7333                   ClassDecl,
7334                   InstanceMethods,
7335                   ClassMethods,
7336                   RefedProtocols,
7337                   ClassProperties);
7338
7339  // Determine if this category is also "non-lazy".
7340  if (ImplementationIsNonLazy(IDecl))
7341    DefinedNonLazyCategories.push_back(CDecl);
7342}
7343
7344void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7345  int CatDefCount = CategoryImplementation.size();
7346  if (!CatDefCount)
7347    return;
7348  Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7349  Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7350  Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7351  for (int i = 0; i < CatDefCount; i++) {
7352    ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7353    ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7354    ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7355    Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7356    Result += ClassDecl->getName();
7357    Result += "_$_";
7358    Result += CatDecl->getName();
7359    Result += ",\n";
7360  }
7361  Result += "};\n";
7362}
7363
7364// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7365/// class methods.
7366template<typename MethodIterator>
7367void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7368                                             MethodIterator MethodEnd,
7369                                             bool IsInstanceMethod,
7370                                             StringRef prefix,
7371                                             StringRef ClassName,
7372                                             std::string &Result) {
7373  if (MethodBegin == MethodEnd) return;
7374
7375  if (!objc_impl_method) {
7376    /* struct _objc_method {
7377     SEL _cmd;
7378     char *method_types;
7379     void *_imp;
7380     }
7381     */
7382    Result += "\nstruct _objc_method {\n";
7383    Result += "\tSEL _cmd;\n";
7384    Result += "\tchar *method_types;\n";
7385    Result += "\tvoid *_imp;\n";
7386    Result += "};\n";
7387
7388    objc_impl_method = true;
7389  }
7390
7391  // Build _objc_method_list for class's methods if needed
7392
7393  /* struct  {
7394   struct _objc_method_list *next_method;
7395   int method_count;
7396   struct _objc_method method_list[];
7397   }
7398   */
7399  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7400  Result += "\n";
7401  if (LangOpts.MicrosoftExt) {
7402    if (IsInstanceMethod)
7403      Result += "__declspec(allocate(\".inst_meth$B\")) ";
7404    else
7405      Result += "__declspec(allocate(\".cls_meth$B\")) ";
7406  }
7407  Result += "static struct {\n";
7408  Result += "\tstruct _objc_method_list *next_method;\n";
7409  Result += "\tint method_count;\n";
7410  Result += "\tstruct _objc_method method_list[";
7411  Result += utostr(NumMethods);
7412  Result += "];\n} _OBJC_";
7413  Result += prefix;
7414  Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7415  Result += "_METHODS_";
7416  Result += ClassName;
7417  Result += " __attribute__ ((used, section (\"__OBJC, __";
7418  Result += IsInstanceMethod ? "inst" : "cls";
7419  Result += "_meth\")))= ";
7420  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7421
7422  Result += "\t,{{(SEL)\"";
7423  Result += (*MethodBegin)->getSelector().getAsString().c_str();
7424  std::string MethodTypeString;
7425  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7426  Result += "\", \"";
7427  Result += MethodTypeString;
7428  Result += "\", (void *)";
7429  Result += MethodInternalNames[*MethodBegin];
7430  Result += "}\n";
7431  for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7432    Result += "\t  ,{(SEL)\"";
7433    Result += (*MethodBegin)->getSelector().getAsString().c_str();
7434    std::string MethodTypeString;
7435    Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7436    Result += "\", \"";
7437    Result += MethodTypeString;
7438    Result += "\", (void *)";
7439    Result += MethodInternalNames[*MethodBegin];
7440    Result += "}\n";
7441  }
7442  Result += "\t }\n};\n";
7443}
7444
7445Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7446  SourceRange OldRange = IV->getSourceRange();
7447  Expr *BaseExpr = IV->getBase();
7448
7449  // Rewrite the base, but without actually doing replaces.
7450  {
7451    DisableReplaceStmtScope S(*this);
7452    BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7453    IV->setBase(BaseExpr);
7454  }
7455
7456  ObjCIvarDecl *D = IV->getDecl();
7457
7458  Expr *Replacement = IV;
7459
7460    if (BaseExpr->getType()->isObjCObjectPointerType()) {
7461      const ObjCInterfaceType *iFaceDecl =
7462        dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7463      assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7464      // lookup which class implements the instance variable.
7465      ObjCInterfaceDecl *clsDeclared = nullptr;
7466      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7467                                                   clsDeclared);
7468      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7469
7470      // Build name of symbol holding ivar offset.
7471      std::string IvarOffsetName;
7472      if (D->isBitField())
7473        ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7474      else
7475        WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7476
7477      ReferencedIvars[clsDeclared].insert(D);
7478
7479      // cast offset to "char *".
7480      CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7481                                                    Context->getPointerType(Context->CharTy),
7482                                                    CK_BitCast,
7483                                                    BaseExpr);
7484      VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7485                                       SourceLocation(), &Context->Idents.get(IvarOffsetName),
7486                                       Context->UnsignedLongTy, nullptr,
7487                                       SC_Extern);
7488      DeclRefExpr *DRE = new (Context)
7489          DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7490                      VK_LValue, SourceLocation());
7491      BinaryOperator *addExpr = BinaryOperator::Create(
7492          *Context, castExpr, DRE, BO_Add,
7493          Context->getPointerType(Context->CharTy), VK_RValue, OK_Ordinary,
7494          SourceLocation(), FPOptionsOverride());
7495      // Don't forget the parens to enforce the proper binding.
7496      ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7497                                              SourceLocation(),
7498                                              addExpr);
7499      QualType IvarT = D->getType();
7500      if (D->isBitField())
7501        IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7502
7503      if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7504        RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
7505        RD = RD->getDefinition();
7506        if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7507          // decltype(((Foo_IMPL*)0)->bar) *
7508          auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
7509          // ivar in class extensions requires special treatment.
7510          if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7511            CDecl = CatDecl->getClassInterface();
7512          std::string RecName = std::string(CDecl->getName());
7513          RecName += "_IMPL";
7514          RecordDecl *RD = RecordDecl::Create(
7515              *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7516              &Context->Idents.get(RecName));
7517          QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7518          unsigned UnsignedIntSize =
7519            static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7520          Expr *Zero = IntegerLiteral::Create(*Context,
7521                                              llvm::APInt(UnsignedIntSize, 0),
7522                                              Context->UnsignedIntTy, SourceLocation());
7523          Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7524          ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7525                                                  Zero);
7526          FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7527                                            SourceLocation(),
7528                                            &Context->Idents.get(D->getNameAsString()),
7529                                            IvarT, nullptr,
7530                                            /*BitWidth=*/nullptr,
7531                                            /*Mutable=*/true, ICIS_NoInit);
7532          MemberExpr *ME = MemberExpr::CreateImplicit(
7533              *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
7534          IvarT = Context->getDecltypeType(ME, ME->getType());
7535        }
7536      }
7537      convertObjCTypeToCStyleType(IvarT);
7538      QualType castT = Context->getPointerType(IvarT);
7539
7540      castExpr = NoTypeInfoCStyleCastExpr(Context,
7541                                          castT,
7542                                          CK_BitCast,
7543                                          PE);
7544
7545      Expr *Exp = UnaryOperator::Create(
7546          const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
7547          VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
7548      PE = new (Context) ParenExpr(OldRange.getBegin(),
7549                                   OldRange.getEnd(),
7550                                   Exp);
7551
7552      if (D->isBitField()) {
7553        FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7554                                          SourceLocation(),
7555                                          &Context->Idents.get(D->getNameAsString()),
7556                                          D->getType(), nullptr,
7557                                          /*BitWidth=*/D->getBitWidth(),
7558                                          /*Mutable=*/true, ICIS_NoInit);
7559        MemberExpr *ME =
7560            MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7561                                       FD->getType(), VK_LValue, OK_Ordinary);
7562        Replacement = ME;
7563
7564      }
7565      else
7566        Replacement = PE;
7567    }
7568
7569    ReplaceStmtWithRange(IV, Replacement, OldRange);
7570    return Replacement;
7571}
7572
7573#endif // CLANG_ENABLE_OBJC_REWRITER
7574