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