clang API Documentation

RewriteModernObjC.cpp
Go to the documentation of this file.
00001 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Hacks and fun related to the code rewriter.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Rewrite/Frontend/ASTConsumers.h"
00015 #include "clang/AST/AST.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/ParentMap.h"
00019 #include "clang/Basic/CharInfo.h"
00020 #include "clang/Basic/Diagnostic.h"
00021 #include "clang/Basic/IdentifierTable.h"
00022 #include "clang/Basic/SourceManager.h"
00023 #include "clang/Basic/TargetInfo.h"
00024 #include "clang/Lex/Lexer.h"
00025 #include "clang/Rewrite/Core/Rewriter.h"
00026 #include "llvm/ADT/DenseSet.h"
00027 #include "llvm/ADT/SmallPtrSet.h"
00028 #include "llvm/ADT/StringExtras.h"
00029 #include "llvm/Support/MemoryBuffer.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include <memory>
00032 
00033 #ifdef CLANG_ENABLE_OBJC_REWRITER
00034 
00035 using namespace clang;
00036 using llvm::utostr;
00037 
00038 namespace {
00039   class RewriteModernObjC : public ASTConsumer {
00040   protected:
00041     
00042     enum {
00043       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
00044                                         block, ... */
00045       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
00046       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the 
00047                                         __block variable */
00048       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
00049                                         helpers */
00050       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
00051                                         support routines */
00052       BLOCK_BYREF_CURRENT_MAX = 256
00053     };
00054     
00055     enum {
00056       BLOCK_NEEDS_FREE =        (1 << 24),
00057       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
00058       BLOCK_HAS_CXX_OBJ =       (1 << 26),
00059       BLOCK_IS_GC =             (1 << 27),
00060       BLOCK_IS_GLOBAL =         (1 << 28),
00061       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
00062     };
00063     
00064     Rewriter Rewrite;
00065     DiagnosticsEngine &Diags;
00066     const LangOptions &LangOpts;
00067     ASTContext *Context;
00068     SourceManager *SM;
00069     TranslationUnitDecl *TUDecl;
00070     FileID MainFileID;
00071     const char *MainFileStart, *MainFileEnd;
00072     Stmt *CurrentBody;
00073     ParentMap *PropParentMap; // created lazily.
00074     std::string InFileName;
00075     raw_ostream* OutFile;
00076     std::string Preamble;
00077     
00078     TypeDecl *ProtocolTypeDecl;
00079     VarDecl *GlobalVarDecl;
00080     Expr *GlobalConstructionExp;
00081     unsigned RewriteFailedDiag;
00082     unsigned GlobalBlockRewriteFailedDiag;
00083     // ObjC string constant support.
00084     unsigned NumObjCStringLiterals;
00085     VarDecl *ConstantStringClassReference;
00086     RecordDecl *NSStringRecord;
00087 
00088     // ObjC foreach break/continue generation support.
00089     int BcLabelCount;
00090     
00091     unsigned TryFinallyContainsReturnDiag;
00092     // Needed for super.
00093     ObjCMethodDecl *CurMethodDef;
00094     RecordDecl *SuperStructDecl;
00095     RecordDecl *ConstantStringDecl;
00096     
00097     FunctionDecl *MsgSendFunctionDecl;
00098     FunctionDecl *MsgSendSuperFunctionDecl;
00099     FunctionDecl *MsgSendStretFunctionDecl;
00100     FunctionDecl *MsgSendSuperStretFunctionDecl;
00101     FunctionDecl *MsgSendFpretFunctionDecl;
00102     FunctionDecl *GetClassFunctionDecl;
00103     FunctionDecl *GetMetaClassFunctionDecl;
00104     FunctionDecl *GetSuperClassFunctionDecl;
00105     FunctionDecl *SelGetUidFunctionDecl;
00106     FunctionDecl *CFStringFunctionDecl;
00107     FunctionDecl *SuperConstructorFunctionDecl;
00108     FunctionDecl *CurFunctionDef;
00109 
00110     /* Misc. containers needed for meta-data rewrite. */
00111     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
00112     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
00113     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
00114     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
00115     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
00116     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
00117     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
00118     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
00119     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
00120     
00121     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
00122     SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
00123     
00124     SmallVector<Stmt *, 32> Stmts;
00125     SmallVector<int, 8> ObjCBcLabelNo;
00126     // Remember all the @protocol(<expr>) expressions.
00127     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
00128     
00129     llvm::DenseSet<uint64_t> CopyDestroyCache;
00130 
00131     // Block expressions.
00132     SmallVector<BlockExpr *, 32> Blocks;
00133     SmallVector<int, 32> InnerDeclRefsCount;
00134     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
00135     
00136     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
00137 
00138     
00139     // Block related declarations.
00140     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
00141     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
00142     SmallVector<ValueDecl *, 8> BlockByRefDecls;
00143     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
00144     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
00145     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
00146     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
00147     
00148     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
00149     llvm::DenseMap<ObjCInterfaceDecl *, 
00150                     llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
00151     
00152     // ivar bitfield grouping containers
00153     llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
00154     llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
00155     // This container maps an <class, group number for ivar> tuple to the type
00156     // of the struct where the bitfield belongs.
00157     llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
00158     SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
00159     
00160     // This maps an original source AST to it's rewritten form. This allows
00161     // us to avoid rewriting the same node twice (which is very uncommon).
00162     // This is needed to support some of the exotic property rewriting.
00163     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
00164 
00165     // Needed for header files being rewritten
00166     bool IsHeader;
00167     bool SilenceRewriteMacroWarning;
00168     bool GenerateLineInfo;
00169     bool objc_impl_method;
00170     
00171     bool DisableReplaceStmt;
00172     class DisableReplaceStmtScope {
00173       RewriteModernObjC &R;
00174       bool SavedValue;
00175     
00176     public:
00177       DisableReplaceStmtScope(RewriteModernObjC &R)
00178         : R(R), SavedValue(R.DisableReplaceStmt) {
00179         R.DisableReplaceStmt = true;
00180       }
00181       ~DisableReplaceStmtScope() {
00182         R.DisableReplaceStmt = SavedValue;
00183       }
00184     };
00185     void InitializeCommon(ASTContext &context);
00186 
00187   public:
00188     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
00189     // Top Level Driver code.
00190     bool HandleTopLevelDecl(DeclGroupRef D) override {
00191       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
00192         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
00193           if (!Class->isThisDeclarationADefinition()) {
00194             RewriteForwardClassDecl(D);
00195             break;
00196           } else {
00197             // Keep track of all interface declarations seen.
00198             ObjCInterfacesSeen.push_back(Class);
00199             break;
00200           }
00201         }
00202 
00203         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
00204           if (!Proto->isThisDeclarationADefinition()) {
00205             RewriteForwardProtocolDecl(D);
00206             break;
00207           }
00208         }
00209 
00210         if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
00211           // Under modern abi, we cannot translate body of the function
00212           // yet until all class extensions and its implementation is seen.
00213           // This is because they may introduce new bitfields which must go
00214           // into their grouping struct.
00215           if (FDecl->isThisDeclarationADefinition() &&
00216               // Not c functions defined inside an objc container.
00217               !FDecl->isTopLevelDeclInObjCContainer()) {
00218             FunctionDefinitionsSeen.push_back(FDecl);
00219             break;
00220           }
00221         }
00222         HandleTopLevelSingleDecl(*I);
00223       }
00224       return true;
00225     }
00226 
00227     void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
00228       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
00229         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
00230           if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
00231             RewriteBlockPointerDecl(TD);
00232           else if (TD->getUnderlyingType()->isFunctionPointerType())
00233             CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
00234           else
00235             RewriteObjCQualifiedInterfaceTypes(TD);
00236         }
00237       }
00238       return;
00239     }
00240     
00241     void HandleTopLevelSingleDecl(Decl *D);
00242     void HandleDeclInMainFile(Decl *D);
00243     RewriteModernObjC(std::string inFile, raw_ostream *OS,
00244                 DiagnosticsEngine &D, const LangOptions &LOpts,
00245                 bool silenceMacroWarn, bool LineInfo);
00246     
00247     ~RewriteModernObjC() {}
00248 
00249     void HandleTranslationUnit(ASTContext &C) override;
00250 
00251     void ReplaceStmt(Stmt *Old, Stmt *New) {
00252       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
00253     }
00254 
00255     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
00256       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
00257 
00258       Stmt *ReplacingStmt = ReplacedNodes[Old];
00259       if (ReplacingStmt)
00260         return; // We can't rewrite the same node twice.
00261 
00262       if (DisableReplaceStmt)
00263         return;
00264 
00265       // Measure the old text.
00266       int Size = Rewrite.getRangeSize(SrcRange);
00267       if (Size == -1) {
00268         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
00269                      << Old->getSourceRange();
00270         return;
00271       }
00272       // Get the new text.
00273       std::string SStr;
00274       llvm::raw_string_ostream S(SStr);
00275       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
00276       const std::string &Str = S.str();
00277 
00278       // If replacement succeeded or warning disabled return with no warning.
00279       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
00280         ReplacedNodes[Old] = New;
00281         return;
00282       }
00283       if (SilenceRewriteMacroWarning)
00284         return;
00285       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
00286                    << Old->getSourceRange();
00287     }
00288 
00289     void InsertText(SourceLocation Loc, StringRef Str,
00290                     bool InsertAfter = true) {
00291       // If insertion succeeded or warning disabled return with no warning.
00292       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
00293           SilenceRewriteMacroWarning)
00294         return;
00295 
00296       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
00297     }
00298 
00299     void ReplaceText(SourceLocation Start, unsigned OrigLength,
00300                      StringRef Str) {
00301       // If removal succeeded or warning disabled return with no warning.
00302       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
00303           SilenceRewriteMacroWarning)
00304         return;
00305 
00306       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
00307     }
00308 
00309     // Syntactic Rewriting.
00310     void RewriteRecordBody(RecordDecl *RD);
00311     void RewriteInclude();
00312     void RewriteLineDirective(const Decl *D);
00313     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
00314                                               std::string &LineString);
00315     void RewriteForwardClassDecl(DeclGroupRef D);
00316     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
00317     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 
00318                                      const std::string &typedefString);
00319     void RewriteImplementations();
00320     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
00321                                  ObjCImplementationDecl *IMD,
00322                                  ObjCCategoryImplDecl *CID);
00323     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
00324     void RewriteImplementationDecl(Decl *Dcl);
00325     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
00326                                ObjCMethodDecl *MDecl, std::string &ResultStr);
00327     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
00328                                const FunctionType *&FPRetType);
00329     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
00330                             ValueDecl *VD, bool def=false);
00331     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
00332     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
00333     void RewriteForwardProtocolDecl(DeclGroupRef D);
00334     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
00335     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
00336     void RewriteProperty(ObjCPropertyDecl *prop);
00337     void RewriteFunctionDecl(FunctionDecl *FD);
00338     void RewriteBlockPointerType(std::string& Str, QualType Type);
00339     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
00340     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
00341     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
00342     void RewriteTypeOfDecl(VarDecl *VD);
00343     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
00344     
00345     std::string getIvarAccessString(ObjCIvarDecl *D);
00346   
00347     // Expression Rewriting.
00348     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
00349     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
00350     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
00351     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
00352     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
00353     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
00354     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
00355     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
00356     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
00357     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
00358     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
00359     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
00360     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
00361     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
00362     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
00363     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
00364     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
00365                                        SourceLocation OrigEnd);
00366     Stmt *RewriteBreakStmt(BreakStmt *S);
00367     Stmt *RewriteContinueStmt(ContinueStmt *S);
00368     void RewriteCastExpr(CStyleCastExpr *CE);
00369     void RewriteImplicitCastObjCExpr(CastExpr *IE);
00370     void RewriteLinkageSpec(LinkageSpecDecl *LSD);
00371     
00372     // Computes ivar bitfield group no.
00373     unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
00374     // Names field decl. for ivar bitfield group.
00375     void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
00376     // Names struct type for ivar bitfield group.
00377     void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
00378     // Names symbol for ivar bitfield group field offset.
00379     void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
00380     // Given an ivar bitfield, it builds (or finds) its group record type.
00381     QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
00382     QualType SynthesizeBitfieldGroupStructType(
00383                                     ObjCIvarDecl *IV,
00384                                     SmallVectorImpl<ObjCIvarDecl *> &IVars);
00385     
00386     // Block rewriting.
00387     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
00388     
00389     // Block specific rewrite rules.
00390     void RewriteBlockPointerDecl(NamedDecl *VD);
00391     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
00392     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
00393     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
00394     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
00395     
00396     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
00397                                       std::string &Result);
00398     
00399     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
00400     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
00401                                  bool &IsNamedDefinition);
00402     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 
00403                                               std::string &Result);
00404     
00405     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
00406     
00407     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
00408                                   std::string &Result);
00409 
00410     void Initialize(ASTContext &context) override;
00411 
00412     // Misc. AST transformation routines. Sometimes they end up calling
00413     // rewriting routines on the new ASTs.
00414     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
00415                                            Expr **args, unsigned nargs,
00416                                            SourceLocation StartLoc=SourceLocation(),
00417                                            SourceLocation EndLoc=SourceLocation());
00418     
00419     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
00420                                         QualType returnType, 
00421                                         SmallVectorImpl<QualType> &ArgTypes,
00422                                         SmallVectorImpl<Expr*> &MsgExprs,
00423                                         ObjCMethodDecl *Method);
00424 
00425     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
00426                            SourceLocation StartLoc=SourceLocation(),
00427                            SourceLocation EndLoc=SourceLocation());
00428     
00429     void SynthCountByEnumWithState(std::string &buf);
00430     void SynthMsgSendFunctionDecl();
00431     void SynthMsgSendSuperFunctionDecl();
00432     void SynthMsgSendStretFunctionDecl();
00433     void SynthMsgSendFpretFunctionDecl();
00434     void SynthMsgSendSuperStretFunctionDecl();
00435     void SynthGetClassFunctionDecl();
00436     void SynthGetMetaClassFunctionDecl();
00437     void SynthGetSuperClassFunctionDecl();
00438     void SynthSelGetUidFunctionDecl();
00439     void SynthSuperConstructorFunctionDecl();
00440     
00441     // Rewriting metadata
00442     template<typename MethodIterator>
00443     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
00444                                     MethodIterator MethodEnd,
00445                                     bool IsInstanceMethod,
00446                                     StringRef prefix,
00447                                     StringRef ClassName,
00448                                     std::string &Result);
00449     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
00450                                      std::string &Result);
00451     void RewriteObjCProtocolListMetaData(
00452                    const ObjCList<ObjCProtocolDecl> &Prots,
00453                    StringRef prefix, StringRef ClassName, std::string &Result);
00454     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
00455                                           std::string &Result);
00456     void RewriteClassSetupInitHook(std::string &Result);
00457     
00458     void RewriteMetaDataIntoBuffer(std::string &Result);
00459     void WriteImageInfo(std::string &Result);
00460     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
00461                                              std::string &Result);
00462     void RewriteCategorySetupInitHook(std::string &Result);
00463     
00464     // Rewriting ivar
00465     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
00466                                               std::string &Result);
00467     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
00468 
00469     
00470     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
00471     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
00472                                       StringRef funcName, std::string Tag);
00473     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
00474                                       StringRef funcName, std::string Tag);
00475     std::string SynthesizeBlockImpl(BlockExpr *CE, 
00476                                     std::string Tag, std::string Desc);
00477     std::string SynthesizeBlockDescriptor(std::string DescTag, 
00478                                           std::string ImplTag,
00479                                           int i, StringRef funcName,
00480                                           unsigned hasCopy);
00481     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
00482     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
00483                                  StringRef FunName);
00484     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
00485     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
00486                       const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
00487 
00488     // Misc. helper routines.
00489     QualType getProtocolType();
00490     void WarnAboutReturnGotoStmts(Stmt *S);
00491     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
00492     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
00493     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
00494 
00495     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
00496     void CollectBlockDeclRefInfo(BlockExpr *Exp);
00497     void GetBlockDeclRefExprs(Stmt *S);
00498     void GetInnerBlockDeclRefExprs(Stmt *S,
00499                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
00500                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
00501 
00502     // We avoid calling Type::isBlockPointerType(), since it operates on the
00503     // canonical type. We only care if the top-level type is a closure pointer.
00504     bool isTopLevelBlockPointerType(QualType T) {
00505       return isa<BlockPointerType>(T);
00506     }
00507 
00508     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
00509     /// to a function pointer type and upon success, returns true; false
00510     /// otherwise.
00511     bool convertBlockPointerToFunctionPointer(QualType &T) {
00512       if (isTopLevelBlockPointerType(T)) {
00513         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
00514         T = Context->getPointerType(BPT->getPointeeType());
00515         return true;
00516       }
00517       return false;
00518     }
00519     
00520     bool convertObjCTypeToCStyleType(QualType &T);
00521     
00522     bool needToScanForQualifiers(QualType T);
00523     QualType getSuperStructType();
00524     QualType getConstantStringStructType();
00525     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
00526     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
00527     
00528     void convertToUnqualifiedObjCType(QualType &T) {
00529       if (T->isObjCQualifiedIdType()) {
00530         bool isConst = T.isConstQualified();
00531         T = isConst ? Context->getObjCIdType().withConst() 
00532                     : Context->getObjCIdType();
00533       }
00534       else if (T->isObjCQualifiedClassType())
00535         T = Context->getObjCClassType();
00536       else if (T->isObjCObjectPointerType() &&
00537                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
00538         if (const ObjCObjectPointerType * OBJPT =
00539               T->getAsObjCInterfacePointerType()) {
00540           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
00541           T = QualType(IFaceT, 0);
00542           T = Context->getPointerType(T);
00543         }
00544      }
00545     }
00546     
00547     // FIXME: This predicate seems like it would be useful to add to ASTContext.
00548     bool isObjCType(QualType T) {
00549       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
00550         return false;
00551 
00552       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
00553 
00554       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
00555           OCT == Context->getCanonicalType(Context->getObjCClassType()))
00556         return true;
00557 
00558       if (const PointerType *PT = OCT->getAs<PointerType>()) {
00559         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
00560             PT->getPointeeType()->isObjCQualifiedIdType())
00561           return true;
00562       }
00563       return false;
00564     }
00565     bool PointerTypeTakesAnyBlockArguments(QualType QT);
00566     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
00567     void GetExtentOfArgList(const char *Name, const char *&LParen,
00568                             const char *&RParen);
00569     
00570     void QuoteDoublequotes(std::string &From, std::string &To) {
00571       for (unsigned i = 0; i < From.length(); i++) {
00572         if (From[i] == '"')
00573           To += "\\\"";
00574         else
00575           To += From[i];
00576       }
00577     }
00578 
00579     QualType getSimpleFunctionType(QualType result,
00580                                    ArrayRef<QualType> args,
00581                                    bool variadic = false) {
00582       if (result == Context->getObjCInstanceType())
00583         result =  Context->getObjCIdType();
00584       FunctionProtoType::ExtProtoInfo fpi;
00585       fpi.Variadic = variadic;
00586       return Context->getFunctionType(result, args, fpi);
00587     }
00588 
00589     // Helper function: create a CStyleCastExpr with trivial type source info.
00590     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
00591                                              CastKind Kind, Expr *E) {
00592       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
00593       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
00594                                     TInfo, SourceLocation(), SourceLocation());
00595     }
00596     
00597     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
00598       IdentifierInfo* II = &Context->Idents.get("load");
00599       Selector LoadSel = Context->Selectors.getSelector(0, &II);
00600       return OD->getClassMethod(LoadSel) != nullptr;
00601     }
00602 
00603     StringLiteral *getStringLiteral(StringRef Str) {
00604       QualType StrType = Context->getConstantArrayType(
00605           Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
00606           0);
00607       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
00608                                    /*Pascal=*/false, StrType, SourceLocation());
00609     }
00610   };
00611   
00612 }
00613 
00614 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
00615                                                    NamedDecl *D) {
00616   if (const FunctionProtoType *fproto
00617       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
00618     for (const auto &I : fproto->param_types())
00619       if (isTopLevelBlockPointerType(I)) {
00620         // All the args are checked/rewritten. Don't call twice!
00621         RewriteBlockPointerDecl(D);
00622         break;
00623       }
00624   }
00625 }
00626 
00627 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
00628   const PointerType *PT = funcType->getAs<PointerType>();
00629   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
00630     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
00631 }
00632 
00633 static bool IsHeaderFile(const std::string &Filename) {
00634   std::string::size_type DotPos = Filename.rfind('.');
00635 
00636   if (DotPos == std::string::npos) {
00637     // no file extension
00638     return false;
00639   }
00640 
00641   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
00642   // C header: .h
00643   // C++ header: .hh or .H;
00644   return Ext == "h" || Ext == "hh" || Ext == "H";
00645 }
00646 
00647 RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
00648                          DiagnosticsEngine &D, const LangOptions &LOpts,
00649                          bool silenceMacroWarn,
00650                          bool LineInfo)
00651       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
00652         SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
00653   IsHeader = IsHeaderFile(inFile);
00654   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
00655                "rewriting sub-expression within a macro (may not be correct)");
00656   // FIXME. This should be an error. But if block is not called, it is OK. And it
00657   // may break including some headers.
00658   GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
00659     "rewriting block literal declared in global scope is not implemented");
00660           
00661   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
00662                DiagnosticsEngine::Warning,
00663                "rewriter doesn't support user-specified control flow semantics "
00664                "for @try/@finally (code may not execute properly)");
00665 }
00666 
00667 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
00668     const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
00669     const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
00670   return llvm::make_unique<RewriteModernObjC>(
00671       InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
00672 }
00673 
00674 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
00675   Context = &context;
00676   SM = &Context->getSourceManager();
00677   TUDecl = Context->getTranslationUnitDecl();
00678   MsgSendFunctionDecl = nullptr;
00679   MsgSendSuperFunctionDecl = nullptr;
00680   MsgSendStretFunctionDecl = nullptr;
00681   MsgSendSuperStretFunctionDecl = nullptr;
00682   MsgSendFpretFunctionDecl = nullptr;
00683   GetClassFunctionDecl = nullptr;
00684   GetMetaClassFunctionDecl = nullptr;
00685   GetSuperClassFunctionDecl = nullptr;
00686   SelGetUidFunctionDecl = nullptr;
00687   CFStringFunctionDecl = nullptr;
00688   ConstantStringClassReference = nullptr;
00689   NSStringRecord = nullptr;
00690   CurMethodDef = nullptr;
00691   CurFunctionDef = nullptr;
00692   GlobalVarDecl = nullptr;
00693   GlobalConstructionExp = nullptr;
00694   SuperStructDecl = nullptr;
00695   ProtocolTypeDecl = nullptr;
00696   ConstantStringDecl = nullptr;
00697   BcLabelCount = 0;
00698   SuperConstructorFunctionDecl = nullptr;
00699   NumObjCStringLiterals = 0;
00700   PropParentMap = nullptr;
00701   CurrentBody = nullptr;
00702   DisableReplaceStmt = false;
00703   objc_impl_method = false;
00704 
00705   // Get the ID and start/end of the main file.
00706   MainFileID = SM->getMainFileID();
00707   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
00708   MainFileStart = MainBuf->getBufferStart();
00709   MainFileEnd = MainBuf->getBufferEnd();
00710 
00711   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
00712 }
00713 
00714 //===----------------------------------------------------------------------===//
00715 // Top Level Driver Code
00716 //===----------------------------------------------------------------------===//
00717 
00718 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
00719   if (Diags.hasErrorOccurred())
00720     return;
00721 
00722   // Two cases: either the decl could be in the main file, or it could be in a
00723   // #included file.  If the former, rewrite it now.  If the later, check to see
00724   // if we rewrote the #include/#import.
00725   SourceLocation Loc = D->getLocation();
00726   Loc = SM->getExpansionLoc(Loc);
00727 
00728   // If this is for a builtin, ignore it.
00729   if (Loc.isInvalid()) return;
00730 
00731   // Look for built-in declarations that we need to refer during the rewrite.
00732   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00733     RewriteFunctionDecl(FD);
00734   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
00735     // declared in <Foundation/NSString.h>
00736     if (FVD->getName() == "_NSConstantStringClassReference") {
00737       ConstantStringClassReference = FVD;
00738       return;
00739     }
00740   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
00741     RewriteCategoryDecl(CD);
00742   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
00743     if (PD->isThisDeclarationADefinition())
00744       RewriteProtocolDecl(PD);
00745   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
00746     // FIXME. This will not work in all situations and leaving it out
00747     // is harmless.
00748     // RewriteLinkageSpec(LSD);
00749     
00750     // Recurse into linkage specifications
00751     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
00752                                  DIEnd = LSD->decls_end();
00753          DI != DIEnd; ) {
00754       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
00755         if (!IFace->isThisDeclarationADefinition()) {
00756           SmallVector<Decl *, 8> DG;
00757           SourceLocation StartLoc = IFace->getLocStart();
00758           do {
00759             if (isa<ObjCInterfaceDecl>(*DI) &&
00760                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
00761                 StartLoc == (*DI)->getLocStart())
00762               DG.push_back(*DI);
00763             else
00764               break;
00765             
00766             ++DI;
00767           } while (DI != DIEnd);
00768           RewriteForwardClassDecl(DG);
00769           continue;
00770         }
00771         else {
00772           // Keep track of all interface declarations seen.
00773           ObjCInterfacesSeen.push_back(IFace);
00774           ++DI;
00775           continue;
00776         }
00777       }
00778 
00779       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
00780         if (!Proto->isThisDeclarationADefinition()) {
00781           SmallVector<Decl *, 8> DG;
00782           SourceLocation StartLoc = Proto->getLocStart();
00783           do {
00784             if (isa<ObjCProtocolDecl>(*DI) &&
00785                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
00786                 StartLoc == (*DI)->getLocStart())
00787               DG.push_back(*DI);
00788             else
00789               break;
00790             
00791             ++DI;
00792           } while (DI != DIEnd);
00793           RewriteForwardProtocolDecl(DG);
00794           continue;
00795         }
00796       }
00797       
00798       HandleTopLevelSingleDecl(*DI);
00799       ++DI;
00800     }
00801   }
00802   // If we have a decl in the main file, see if we should rewrite it.
00803   if (SM->isWrittenInMainFile(Loc))
00804     return HandleDeclInMainFile(D);
00805 }
00806 
00807 //===----------------------------------------------------------------------===//
00808 // Syntactic (non-AST) Rewriting Code
00809 //===----------------------------------------------------------------------===//
00810 
00811 void RewriteModernObjC::RewriteInclude() {
00812   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
00813   StringRef MainBuf = SM->getBufferData(MainFileID);
00814   const char *MainBufStart = MainBuf.begin();
00815   const char *MainBufEnd = MainBuf.end();
00816   size_t ImportLen = strlen("import");
00817 
00818   // Loop over the whole file, looking for includes.
00819   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
00820     if (*BufPtr == '#') {
00821       if (++BufPtr == MainBufEnd)
00822         return;
00823       while (*BufPtr == ' ' || *BufPtr == '\t')
00824         if (++BufPtr == MainBufEnd)
00825           return;
00826       if (!strncmp(BufPtr, "import", ImportLen)) {
00827         // replace import with include
00828         SourceLocation ImportLoc =
00829           LocStart.getLocWithOffset(BufPtr-MainBufStart);
00830         ReplaceText(ImportLoc, ImportLen, "include");
00831         BufPtr += ImportLen;
00832       }
00833     }
00834   }
00835 }
00836 
00837 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
00838                                   ObjCIvarDecl *IvarDecl, std::string &Result) {
00839   Result += "OBJC_IVAR_$_";
00840   Result += IDecl->getName();
00841   Result += "$";
00842   Result += IvarDecl->getName();
00843 }
00844 
00845 std::string 
00846 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
00847   const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
00848   
00849   // Build name of symbol holding ivar offset.
00850   std::string IvarOffsetName;
00851   if (D->isBitField())
00852     ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
00853   else
00854     WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
00855   
00856   
00857   std::string S = "(*(";
00858   QualType IvarT = D->getType();
00859   if (D->isBitField())
00860     IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
00861   
00862   if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
00863     RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
00864     RD = RD->getDefinition();
00865     if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
00866       // decltype(((Foo_IMPL*)0)->bar) *
00867       ObjCContainerDecl *CDecl = 
00868       dyn_cast<ObjCContainerDecl>(D->getDeclContext());
00869       // ivar in class extensions requires special treatment.
00870       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
00871         CDecl = CatDecl->getClassInterface();
00872       std::string RecName = CDecl->getName();
00873       RecName += "_IMPL";
00874       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
00875                                           SourceLocation(), SourceLocation(),
00876                                           &Context->Idents.get(RecName.c_str()));
00877       QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
00878       unsigned UnsignedIntSize = 
00879       static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
00880       Expr *Zero = IntegerLiteral::Create(*Context,
00881                                           llvm::APInt(UnsignedIntSize, 0),
00882                                           Context->UnsignedIntTy, SourceLocation());
00883       Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
00884       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
00885                                               Zero);
00886       FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
00887                                         SourceLocation(),
00888                                         &Context->Idents.get(D->getNameAsString()),
00889                                         IvarT, nullptr,
00890                                         /*BitWidth=*/nullptr, /*Mutable=*/true,
00891                                         ICIS_NoInit);
00892       MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
00893                                                 FD->getType(), VK_LValue,
00894                                                 OK_Ordinary);
00895       IvarT = Context->getDecltypeType(ME, ME->getType());
00896     }
00897   }
00898   convertObjCTypeToCStyleType(IvarT);
00899   QualType castT = Context->getPointerType(IvarT);
00900   std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
00901   S += TypeString;
00902   S += ")";
00903   
00904   // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
00905   S += "((char *)self + ";
00906   S += IvarOffsetName;
00907   S += "))";
00908   if (D->isBitField()) {
00909     S += ".";
00910     S += D->getNameAsString();
00911   }
00912   ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
00913   return S;
00914 }
00915 
00916 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
00917 /// been found in the class implementation. In this case, it must be synthesized.
00918 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
00919                                              ObjCPropertyDecl *PD,
00920                                              bool getter) {
00921   return getter ? !IMP->getInstanceMethod(PD->getGetterName())
00922                 : !IMP->getInstanceMethod(PD->getSetterName());
00923   
00924 }
00925 
00926 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
00927                                           ObjCImplementationDecl *IMD,
00928                                           ObjCCategoryImplDecl *CID) {
00929   static bool objcGetPropertyDefined = false;
00930   static bool objcSetPropertyDefined = false;
00931   SourceLocation startGetterSetterLoc;
00932   
00933   if (PID->getLocStart().isValid()) {
00934     SourceLocation startLoc = PID->getLocStart();
00935     InsertText(startLoc, "// ");
00936     const char *startBuf = SM->getCharacterData(startLoc);
00937     assert((*startBuf == '@') && "bogus @synthesize location");
00938     const char *semiBuf = strchr(startBuf, ';');
00939     assert((*semiBuf == ';') && "@synthesize: can't find ';'");
00940     startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
00941   }
00942   else
00943     startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
00944 
00945   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
00946     return; // FIXME: is this correct?
00947 
00948   // Generate the 'getter' function.
00949   ObjCPropertyDecl *PD = PID->getPropertyDecl();
00950   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
00951   assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
00952 
00953   unsigned Attributes = PD->getPropertyAttributes();
00954   if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
00955     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
00956                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
00957                                          ObjCPropertyDecl::OBJC_PR_copy));
00958     std::string Getr;
00959     if (GenGetProperty && !objcGetPropertyDefined) {
00960       objcGetPropertyDefined = true;
00961       // FIXME. Is this attribute correct in all cases?
00962       Getr = "\nextern \"C\" __declspec(dllimport) "
00963             "id objc_getProperty(id, SEL, long, bool);\n";
00964     }
00965     RewriteObjCMethodDecl(OID->getContainingInterface(),  
00966                           PD->getGetterMethodDecl(), Getr);
00967     Getr += "{ ";
00968     // Synthesize an explicit cast to gain access to the ivar.
00969     // See objc-act.c:objc_synthesize_new_getter() for details.
00970     if (GenGetProperty) {
00971       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
00972       Getr += "typedef ";
00973       const FunctionType *FPRetType = nullptr;
00974       RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
00975                             FPRetType);
00976       Getr += " _TYPE";
00977       if (FPRetType) {
00978         Getr += ")"; // close the precedence "scope" for "*".
00979       
00980         // Now, emit the argument types (if any).
00981         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
00982           Getr += "(";
00983           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00984             if (i) Getr += ", ";
00985             std::string ParamStr =
00986                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
00987             Getr += ParamStr;
00988           }
00989           if (FT->isVariadic()) {
00990             if (FT->getNumParams())
00991               Getr += ", ";
00992             Getr += "...";
00993           }
00994           Getr += ")";
00995         } else
00996           Getr += "()";
00997       }
00998       Getr += ";\n";
00999       Getr += "return (_TYPE)";
01000       Getr += "objc_getProperty(self, _cmd, ";
01001       RewriteIvarOffsetComputation(OID, Getr);
01002       Getr += ", 1)";
01003     }
01004     else
01005       Getr += "return " + getIvarAccessString(OID);
01006     Getr += "; }";
01007     InsertText(startGetterSetterLoc, Getr);
01008   }
01009   
01010   if (PD->isReadOnly() || 
01011       !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
01012     return;
01013 
01014   // Generate the 'setter' function.
01015   std::string Setr;
01016   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
01017                                       ObjCPropertyDecl::OBJC_PR_copy);
01018   if (GenSetProperty && !objcSetPropertyDefined) {
01019     objcSetPropertyDefined = true;
01020     // FIXME. Is this attribute correct in all cases?
01021     Setr = "\nextern \"C\" __declspec(dllimport) "
01022     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
01023   }
01024   
01025   RewriteObjCMethodDecl(OID->getContainingInterface(), 
01026                         PD->getSetterMethodDecl(), Setr);
01027   Setr += "{ ";
01028   // Synthesize an explicit cast to initialize the ivar.
01029   // See objc-act.c:objc_synthesize_new_setter() for details.
01030   if (GenSetProperty) {
01031     Setr += "objc_setProperty (self, _cmd, ";
01032     RewriteIvarOffsetComputation(OID, Setr);
01033     Setr += ", (id)";
01034     Setr += PD->getName();
01035     Setr += ", ";
01036     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
01037       Setr += "0, ";
01038     else
01039       Setr += "1, ";
01040     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
01041       Setr += "1)";
01042     else
01043       Setr += "0)";
01044   }
01045   else {
01046     Setr += getIvarAccessString(OID) + " = ";
01047     Setr += PD->getName();
01048   }
01049   Setr += "; }\n";
01050   InsertText(startGetterSetterLoc, Setr);
01051 }
01052 
01053 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
01054                                        std::string &typedefString) {
01055   typedefString += "\n#ifndef _REWRITER_typedef_";
01056   typedefString += ForwardDecl->getNameAsString();
01057   typedefString += "\n";
01058   typedefString += "#define _REWRITER_typedef_";
01059   typedefString += ForwardDecl->getNameAsString();
01060   typedefString += "\n";
01061   typedefString += "typedef struct objc_object ";
01062   typedefString += ForwardDecl->getNameAsString();
01063   // typedef struct { } _objc_exc_Classname;
01064   typedefString += ";\ntypedef struct {} _objc_exc_";
01065   typedefString += ForwardDecl->getNameAsString();
01066   typedefString += ";\n#endif\n";
01067 }
01068 
01069 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
01070                                               const std::string &typedefString) {
01071     SourceLocation startLoc = ClassDecl->getLocStart();
01072     const char *startBuf = SM->getCharacterData(startLoc);
01073     const char *semiPtr = strchr(startBuf, ';'); 
01074     // Replace the @class with typedefs corresponding to the classes.
01075     ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);  
01076 }
01077 
01078 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
01079   std::string typedefString;
01080   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
01081     if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
01082       if (I == D.begin()) {
01083         // Translate to typedef's that forward reference structs with the same name
01084         // as the class. As a convenience, we include the original declaration
01085         // as a comment.
01086         typedefString += "// @class ";
01087         typedefString += ForwardDecl->getNameAsString();
01088         typedefString += ";";
01089       }
01090       RewriteOneForwardClassDecl(ForwardDecl, typedefString);
01091     }
01092     else
01093       HandleTopLevelSingleDecl(*I);
01094   }
01095   DeclGroupRef::iterator I = D.begin();
01096   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
01097 }
01098 
01099 void RewriteModernObjC::RewriteForwardClassDecl(
01100                                 const SmallVectorImpl<Decl *> &D) {
01101   std::string typedefString;
01102   for (unsigned i = 0; i < D.size(); i++) {
01103     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
01104     if (i == 0) {
01105       typedefString += "// @class ";
01106       typedefString += ForwardDecl->getNameAsString();
01107       typedefString += ";";
01108     }
01109     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
01110   }
01111   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
01112 }
01113 
01114 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
01115   // When method is a synthesized one, such as a getter/setter there is
01116   // nothing to rewrite.
01117   if (Method->isImplicit())
01118     return;
01119   SourceLocation LocStart = Method->getLocStart();
01120   SourceLocation LocEnd = Method->getLocEnd();
01121 
01122   if (SM->getExpansionLineNumber(LocEnd) >
01123       SM->getExpansionLineNumber(LocStart)) {
01124     InsertText(LocStart, "#if 0\n");
01125     ReplaceText(LocEnd, 1, ";\n#endif\n");
01126   } else {
01127     InsertText(LocStart, "// ");
01128   }
01129 }
01130 
01131 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
01132   SourceLocation Loc = prop->getAtLoc();
01133 
01134   ReplaceText(Loc, 0, "// ");
01135   // FIXME: handle properties that are declared across multiple lines.
01136 }
01137 
01138 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
01139   SourceLocation LocStart = CatDecl->getLocStart();
01140 
01141   // FIXME: handle category headers that are declared across multiple lines.
01142   if (CatDecl->getIvarRBraceLoc().isValid()) {
01143     ReplaceText(LocStart, 1, "/** ");
01144     ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
01145   }
01146   else {
01147     ReplaceText(LocStart, 0, "// ");
01148   }
01149   
01150   for (auto *I : CatDecl->properties())
01151     RewriteProperty(I);
01152   
01153   for (auto *I : CatDecl->instance_methods())
01154     RewriteMethodDeclaration(I);
01155   for (auto *I : CatDecl->class_methods())
01156     RewriteMethodDeclaration(I);
01157 
01158   // Lastly, comment out the @end.
01159   ReplaceText(CatDecl->getAtEndRange().getBegin(), 
01160               strlen("@end"), "/* @end */\n");
01161 }
01162 
01163 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
01164   SourceLocation LocStart = PDecl->getLocStart();
01165   assert(PDecl->isThisDeclarationADefinition());
01166   
01167   // FIXME: handle protocol headers that are declared across multiple lines.
01168   ReplaceText(LocStart, 0, "// ");
01169 
01170   for (auto *I : PDecl->instance_methods())
01171     RewriteMethodDeclaration(I);
01172   for (auto *I : PDecl->class_methods())
01173     RewriteMethodDeclaration(I);
01174   for (auto *I : PDecl->properties())
01175     RewriteProperty(I);
01176   
01177   // Lastly, comment out the @end.
01178   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
01179   ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
01180 
01181   // Must comment out @optional/@required
01182   const char *startBuf = SM->getCharacterData(LocStart);
01183   const char *endBuf = SM->getCharacterData(LocEnd);
01184   for (const char *p = startBuf; p < endBuf; p++) {
01185     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
01186       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
01187       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
01188 
01189     }
01190     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
01191       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
01192       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
01193 
01194     }
01195   }
01196 }
01197 
01198 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
01199   SourceLocation LocStart = (*D.begin())->getLocStart();
01200   if (LocStart.isInvalid())
01201     llvm_unreachable("Invalid SourceLocation");
01202   // FIXME: handle forward protocol that are declared across multiple lines.
01203   ReplaceText(LocStart, 0, "// ");
01204 }
01205 
01206 void 
01207 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
01208   SourceLocation LocStart = DG[0]->getLocStart();
01209   if (LocStart.isInvalid())
01210     llvm_unreachable("Invalid SourceLocation");
01211   // FIXME: handle forward protocol that are declared across multiple lines.
01212   ReplaceText(LocStart, 0, "// ");
01213 }
01214 
01215 void 
01216 RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
01217   SourceLocation LocStart = LSD->getExternLoc();
01218   if (LocStart.isInvalid())
01219     llvm_unreachable("Invalid extern SourceLocation");
01220   
01221   ReplaceText(LocStart, 0, "// ");
01222   if (!LSD->hasBraces())
01223     return;
01224   // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
01225   SourceLocation LocRBrace = LSD->getRBraceLoc();
01226   if (LocRBrace.isInvalid())
01227     llvm_unreachable("Invalid rbrace SourceLocation");
01228   ReplaceText(LocRBrace, 0, "// ");
01229 }
01230 
01231 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
01232                                         const FunctionType *&FPRetType) {
01233   if (T->isObjCQualifiedIdType())
01234     ResultStr += "id";
01235   else if (T->isFunctionPointerType() ||
01236            T->isBlockPointerType()) {
01237     // needs special handling, since pointer-to-functions have special
01238     // syntax (where a decaration models use).
01239     QualType retType = T;
01240     QualType PointeeTy;
01241     if (const PointerType* PT = retType->getAs<PointerType>())
01242       PointeeTy = PT->getPointeeType();
01243     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
01244       PointeeTy = BPT->getPointeeType();
01245     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
01246       ResultStr +=
01247           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
01248       ResultStr += "(*";
01249     }
01250   } else
01251     ResultStr += T.getAsString(Context->getPrintingPolicy());
01252 }
01253 
01254 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
01255                                         ObjCMethodDecl *OMD,
01256                                         std::string &ResultStr) {
01257   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
01258   const FunctionType *FPRetType = nullptr;
01259   ResultStr += "\nstatic ";
01260   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
01261   ResultStr += " ";
01262 
01263   // Unique method name
01264   std::string NameStr;
01265 
01266   if (OMD->isInstanceMethod())
01267     NameStr += "_I_";
01268   else
01269     NameStr += "_C_";
01270 
01271   NameStr += IDecl->getNameAsString();
01272   NameStr += "_";
01273 
01274   if (ObjCCategoryImplDecl *CID =
01275       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
01276     NameStr += CID->getNameAsString();
01277     NameStr += "_";
01278   }
01279   // Append selector names, replacing ':' with '_'
01280   {
01281     std::string selString = OMD->getSelector().getAsString();
01282     int len = selString.size();
01283     for (int i = 0; i < len; i++)
01284       if (selString[i] == ':')
01285         selString[i] = '_';
01286     NameStr += selString;
01287   }
01288   // Remember this name for metadata emission
01289   MethodInternalNames[OMD] = NameStr;
01290   ResultStr += NameStr;
01291 
01292   // Rewrite arguments
01293   ResultStr += "(";
01294 
01295   // invisible arguments
01296   if (OMD->isInstanceMethod()) {
01297     QualType selfTy = Context->getObjCInterfaceType(IDecl);
01298     selfTy = Context->getPointerType(selfTy);
01299     if (!LangOpts.MicrosoftExt) {
01300       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
01301         ResultStr += "struct ";
01302     }
01303     // When rewriting for Microsoft, explicitly omit the structure name.
01304     ResultStr += IDecl->getNameAsString();
01305     ResultStr += " *";
01306   }
01307   else
01308     ResultStr += Context->getObjCClassType().getAsString(
01309       Context->getPrintingPolicy());
01310 
01311   ResultStr += " self, ";
01312   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
01313   ResultStr += " _cmd";
01314 
01315   // Method arguments.
01316   for (const auto *PDecl : OMD->params()) {
01317     ResultStr += ", ";
01318     if (PDecl->getType()->isObjCQualifiedIdType()) {
01319       ResultStr += "id ";
01320       ResultStr += PDecl->getNameAsString();
01321     } else {
01322       std::string Name = PDecl->getNameAsString();
01323       QualType QT = PDecl->getType();
01324       // Make sure we convert "t (^)(...)" to "t (*)(...)".
01325       (void)convertBlockPointerToFunctionPointer(QT);
01326       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
01327       ResultStr += Name;
01328     }
01329   }
01330   if (OMD->isVariadic())
01331     ResultStr += ", ...";
01332   ResultStr += ") ";
01333 
01334   if (FPRetType) {
01335     ResultStr += ")"; // close the precedence "scope" for "*".
01336 
01337     // Now, emit the argument types (if any).
01338     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
01339       ResultStr += "(";
01340       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
01341         if (i) ResultStr += ", ";
01342         std::string ParamStr =
01343             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
01344         ResultStr += ParamStr;
01345       }
01346       if (FT->isVariadic()) {
01347         if (FT->getNumParams())
01348           ResultStr += ", ";
01349         ResultStr += "...";
01350       }
01351       ResultStr += ")";
01352     } else {
01353       ResultStr += "()";
01354     }
01355   }
01356 }
01357 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
01358   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
01359   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
01360 
01361   if (IMD) {
01362     if (IMD->getIvarRBraceLoc().isValid()) {
01363       ReplaceText(IMD->getLocStart(), 1, "/** ");
01364       ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
01365     }
01366     else {
01367       InsertText(IMD->getLocStart(), "// ");
01368     }
01369   }
01370   else
01371     InsertText(CID->getLocStart(), "// ");
01372 
01373   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
01374     std::string ResultStr;
01375     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
01376     SourceLocation LocStart = OMD->getLocStart();
01377     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
01378 
01379     const char *startBuf = SM->getCharacterData(LocStart);
01380     const char *endBuf = SM->getCharacterData(LocEnd);
01381     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
01382   }
01383 
01384   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
01385     std::string ResultStr;
01386     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
01387     SourceLocation LocStart = OMD->getLocStart();
01388     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
01389 
01390     const char *startBuf = SM->getCharacterData(LocStart);
01391     const char *endBuf = SM->getCharacterData(LocEnd);
01392     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
01393   }
01394   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
01395     RewritePropertyImplDecl(I, IMD, CID);
01396 
01397   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
01398 }
01399 
01400 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
01401   // Do not synthesize more than once.
01402   if (ObjCSynthesizedStructs.count(ClassDecl))
01403     return;
01404   // Make sure super class's are written before current class is written.
01405   ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
01406   while (SuperClass) {
01407     RewriteInterfaceDecl(SuperClass);
01408     SuperClass = SuperClass->getSuperClass();
01409   }
01410   std::string ResultStr;
01411   if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
01412     // we haven't seen a forward decl - generate a typedef.
01413     RewriteOneForwardClassDecl(ClassDecl, ResultStr);
01414     RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
01415     
01416     RewriteObjCInternalStruct(ClassDecl, ResultStr);
01417     // Mark this typedef as having been written into its c++ equivalent.
01418     ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
01419   
01420     for (auto *I : ClassDecl->properties())
01421       RewriteProperty(I);
01422     for (auto *I : ClassDecl->instance_methods())
01423       RewriteMethodDeclaration(I);
01424     for (auto *I : ClassDecl->class_methods())
01425       RewriteMethodDeclaration(I);
01426 
01427     // Lastly, comment out the @end.
01428     ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), 
01429                 "/* @end */\n");
01430   }
01431 }
01432 
01433 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
01434   SourceRange OldRange = PseudoOp->getSourceRange();
01435 
01436   // We just magically know some things about the structure of this
01437   // expression.
01438   ObjCMessageExpr *OldMsg =
01439     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
01440                             PseudoOp->getNumSemanticExprs() - 1));
01441 
01442   // Because the rewriter doesn't allow us to rewrite rewritten code,
01443   // we need to suppress rewriting the sub-statements.
01444   Expr *Base;
01445   SmallVector<Expr*, 2> Args;
01446   {
01447     DisableReplaceStmtScope S(*this);
01448 
01449     // Rebuild the base expression if we have one.
01450     Base = nullptr;
01451     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
01452       Base = OldMsg->getInstanceReceiver();
01453       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
01454       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
01455     }
01456   
01457     unsigned numArgs = OldMsg->getNumArgs();
01458     for (unsigned i = 0; i < numArgs; i++) {
01459       Expr *Arg = OldMsg->getArg(i);
01460       if (isa<OpaqueValueExpr>(Arg))
01461         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
01462       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
01463       Args.push_back(Arg);
01464     }
01465   }
01466 
01467   // TODO: avoid this copy.
01468   SmallVector<SourceLocation, 1> SelLocs;
01469   OldMsg->getSelectorLocs(SelLocs);
01470 
01471   ObjCMessageExpr *NewMsg = nullptr;
01472   switch (OldMsg->getReceiverKind()) {
01473   case ObjCMessageExpr::Class:
01474     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01475                                      OldMsg->getValueKind(),
01476                                      OldMsg->getLeftLoc(),
01477                                      OldMsg->getClassReceiverTypeInfo(),
01478                                      OldMsg->getSelector(),
01479                                      SelLocs,
01480                                      OldMsg->getMethodDecl(),
01481                                      Args,
01482                                      OldMsg->getRightLoc(),
01483                                      OldMsg->isImplicit());
01484     break;
01485 
01486   case ObjCMessageExpr::Instance:
01487     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01488                                      OldMsg->getValueKind(),
01489                                      OldMsg->getLeftLoc(),
01490                                      Base,
01491                                      OldMsg->getSelector(),
01492                                      SelLocs,
01493                                      OldMsg->getMethodDecl(),
01494                                      Args,
01495                                      OldMsg->getRightLoc(),
01496                                      OldMsg->isImplicit());
01497     break;
01498 
01499   case ObjCMessageExpr::SuperClass:
01500   case ObjCMessageExpr::SuperInstance:
01501     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01502                                      OldMsg->getValueKind(),
01503                                      OldMsg->getLeftLoc(),
01504                                      OldMsg->getSuperLoc(),
01505                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
01506                                      OldMsg->getSuperType(),
01507                                      OldMsg->getSelector(),
01508                                      SelLocs,
01509                                      OldMsg->getMethodDecl(),
01510                                      Args,
01511                                      OldMsg->getRightLoc(),
01512                                      OldMsg->isImplicit());
01513     break;
01514   }
01515 
01516   Stmt *Replacement = SynthMessageExpr(NewMsg);
01517   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
01518   return Replacement;
01519 }
01520 
01521 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
01522   SourceRange OldRange = PseudoOp->getSourceRange();
01523 
01524   // We just magically know some things about the structure of this
01525   // expression.
01526   ObjCMessageExpr *OldMsg =
01527     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
01528 
01529   // Because the rewriter doesn't allow us to rewrite rewritten code,
01530   // we need to suppress rewriting the sub-statements.
01531   Expr *Base = nullptr;
01532   SmallVector<Expr*, 1> Args;
01533   {
01534     DisableReplaceStmtScope S(*this);
01535     // Rebuild the base expression if we have one.
01536     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
01537       Base = OldMsg->getInstanceReceiver();
01538       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
01539       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
01540     }
01541     unsigned numArgs = OldMsg->getNumArgs();
01542     for (unsigned i = 0; i < numArgs; i++) {
01543       Expr *Arg = OldMsg->getArg(i);
01544       if (isa<OpaqueValueExpr>(Arg))
01545         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
01546       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
01547       Args.push_back(Arg);
01548     }
01549   }
01550 
01551   // Intentionally empty.
01552   SmallVector<SourceLocation, 1> SelLocs;
01553 
01554   ObjCMessageExpr *NewMsg = nullptr;
01555   switch (OldMsg->getReceiverKind()) {
01556   case ObjCMessageExpr::Class:
01557     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01558                                      OldMsg->getValueKind(),
01559                                      OldMsg->getLeftLoc(),
01560                                      OldMsg->getClassReceiverTypeInfo(),
01561                                      OldMsg->getSelector(),
01562                                      SelLocs,
01563                                      OldMsg->getMethodDecl(),
01564                                      Args,
01565                                      OldMsg->getRightLoc(),
01566                                      OldMsg->isImplicit());
01567     break;
01568 
01569   case ObjCMessageExpr::Instance:
01570     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01571                                      OldMsg->getValueKind(),
01572                                      OldMsg->getLeftLoc(),
01573                                      Base,
01574                                      OldMsg->getSelector(),
01575                                      SelLocs,
01576                                      OldMsg->getMethodDecl(),
01577                                      Args,
01578                                      OldMsg->getRightLoc(),
01579                                      OldMsg->isImplicit());
01580     break;
01581 
01582   case ObjCMessageExpr::SuperClass:
01583   case ObjCMessageExpr::SuperInstance:
01584     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01585                                      OldMsg->getValueKind(),
01586                                      OldMsg->getLeftLoc(),
01587                                      OldMsg->getSuperLoc(),
01588                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
01589                                      OldMsg->getSuperType(),
01590                                      OldMsg->getSelector(),
01591                                      SelLocs,
01592                                      OldMsg->getMethodDecl(),
01593                                      Args,
01594                                      OldMsg->getRightLoc(),
01595                                      OldMsg->isImplicit());
01596     break;
01597   }
01598 
01599   Stmt *Replacement = SynthMessageExpr(NewMsg);
01600   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
01601   return Replacement;
01602 }
01603 
01604 /// SynthCountByEnumWithState - To print:
01605 /// ((NSUInteger (*)
01606 ///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
01607 ///  (void *)objc_msgSend)((id)l_collection,
01608 ///                        sel_registerName(
01609 ///                          "countByEnumeratingWithState:objects:count:"),
01610 ///                        &enumState,
01611 ///                        (id *)__rw_items, (NSUInteger)16)
01612 ///
01613 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
01614   buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
01615   "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
01616   buf += "\n\t\t";
01617   buf += "((id)l_collection,\n\t\t";
01618   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
01619   buf += "\n\t\t";
01620   buf += "&enumState, "
01621          "(id *)__rw_items, (_WIN_NSUInteger)16)";
01622 }
01623 
01624 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
01625 /// statement to exit to its outer synthesized loop.
01626 ///
01627 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
01628   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
01629     return S;
01630   // replace break with goto __break_label
01631   std::string buf;
01632 
01633   SourceLocation startLoc = S->getLocStart();
01634   buf = "goto __break_label_";
01635   buf += utostr(ObjCBcLabelNo.back());
01636   ReplaceText(startLoc, strlen("break"), buf);
01637 
01638   return nullptr;
01639 }
01640 
01641 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
01642                                           SourceLocation Loc,
01643                                           std::string &LineString) {
01644   if (Loc.isFileID() && GenerateLineInfo) {
01645     LineString += "\n#line ";
01646     PresumedLoc PLoc = SM->getPresumedLoc(Loc);
01647     LineString += utostr(PLoc.getLine());
01648     LineString += " \"";
01649     LineString += Lexer::Stringify(PLoc.getFilename());
01650     LineString += "\"\n";
01651   }
01652 }
01653 
01654 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
01655 /// statement to continue with its inner synthesized loop.
01656 ///
01657 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
01658   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
01659     return S;
01660   // replace continue with goto __continue_label
01661   std::string buf;
01662 
01663   SourceLocation startLoc = S->getLocStart();
01664   buf = "goto __continue_label_";
01665   buf += utostr(ObjCBcLabelNo.back());
01666   ReplaceText(startLoc, strlen("continue"), buf);
01667 
01668   return nullptr;
01669 }
01670 
01671 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
01672 ///  It rewrites:
01673 /// for ( type elem in collection) { stmts; }
01674 
01675 /// Into:
01676 /// {
01677 ///   type elem;
01678 ///   struct __objcFastEnumerationState enumState = { 0 };
01679 ///   id __rw_items[16];
01680 ///   id l_collection = (id)collection;
01681 ///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
01682 ///                                       objects:__rw_items count:16];
01683 /// if (limit) {
01684 ///   unsigned long startMutations = *enumState.mutationsPtr;
01685 ///   do {
01686 ///        unsigned long counter = 0;
01687 ///        do {
01688 ///             if (startMutations != *enumState.mutationsPtr)
01689 ///               objc_enumerationMutation(l_collection);
01690 ///             elem = (type)enumState.itemsPtr[counter++];
01691 ///             stmts;
01692 ///             __continue_label: ;
01693 ///        } while (counter < limit);
01694 ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
01695 ///                                  objects:__rw_items count:16]));
01696 ///   elem = nil;
01697 ///   __break_label: ;
01698 ///  }
01699 ///  else
01700 ///       elem = nil;
01701 ///  }
01702 ///
01703 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
01704                                                 SourceLocation OrigEnd) {
01705   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
01706   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
01707          "ObjCForCollectionStmt Statement stack mismatch");
01708   assert(!ObjCBcLabelNo.empty() &&
01709          "ObjCForCollectionStmt - Label No stack empty");
01710 
01711   SourceLocation startLoc = S->getLocStart();
01712   const char *startBuf = SM->getCharacterData(startLoc);
01713   StringRef elementName;
01714   std::string elementTypeAsString;
01715   std::string buf;
01716   // line directive first.
01717   SourceLocation ForEachLoc = S->getForLoc();
01718   ConvertSourceLocationToLineDirective(ForEachLoc, buf);
01719   buf += "{\n\t";
01720   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
01721     // type elem;
01722     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
01723     QualType ElementType = cast<ValueDecl>(D)->getType();
01724     if (ElementType->isObjCQualifiedIdType() ||
01725         ElementType->isObjCQualifiedInterfaceType())
01726       // Simply use 'id' for all qualified types.
01727       elementTypeAsString = "id";
01728     else
01729       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
01730     buf += elementTypeAsString;
01731     buf += " ";
01732     elementName = D->getName();
01733     buf += elementName;
01734     buf += ";\n\t";
01735   }
01736   else {
01737     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
01738     elementName = DR->getDecl()->getName();
01739     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
01740     if (VD->getType()->isObjCQualifiedIdType() ||
01741         VD->getType()->isObjCQualifiedInterfaceType())
01742       // Simply use 'id' for all qualified types.
01743       elementTypeAsString = "id";
01744     else
01745       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
01746   }
01747 
01748   // struct __objcFastEnumerationState enumState = { 0 };
01749   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
01750   // id __rw_items[16];
01751   buf += "id __rw_items[16];\n\t";
01752   // id l_collection = (id)
01753   buf += "id l_collection = (id)";
01754   // Find start location of 'collection' the hard way!
01755   const char *startCollectionBuf = startBuf;
01756   startCollectionBuf += 3;  // skip 'for'
01757   startCollectionBuf = strchr(startCollectionBuf, '(');
01758   startCollectionBuf++; // skip '('
01759   // find 'in' and skip it.
01760   while (*startCollectionBuf != ' ' ||
01761          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
01762          (*(startCollectionBuf+3) != ' ' &&
01763           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
01764     startCollectionBuf++;
01765   startCollectionBuf += 3;
01766 
01767   // Replace: "for (type element in" with string constructed thus far.
01768   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
01769   // Replace ')' in for '(' type elem in collection ')' with ';'
01770   SourceLocation rightParenLoc = S->getRParenLoc();
01771   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
01772   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
01773   buf = ";\n\t";
01774 
01775   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
01776   //                                   objects:__rw_items count:16];
01777   // which is synthesized into:
01778   // NSUInteger limit =
01779   // ((NSUInteger (*)
01780   //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
01781   //  (void *)objc_msgSend)((id)l_collection,
01782   //                        sel_registerName(
01783   //                          "countByEnumeratingWithState:objects:count:"),
01784   //                        (struct __objcFastEnumerationState *)&state,
01785   //                        (id *)__rw_items, (NSUInteger)16);
01786   buf += "_WIN_NSUInteger limit =\n\t\t";
01787   SynthCountByEnumWithState(buf);
01788   buf += ";\n\t";
01789   /// if (limit) {
01790   ///   unsigned long startMutations = *enumState.mutationsPtr;
01791   ///   do {
01792   ///        unsigned long counter = 0;
01793   ///        do {
01794   ///             if (startMutations != *enumState.mutationsPtr)
01795   ///               objc_enumerationMutation(l_collection);
01796   ///             elem = (type)enumState.itemsPtr[counter++];
01797   buf += "if (limit) {\n\t";
01798   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
01799   buf += "do {\n\t\t";
01800   buf += "unsigned long counter = 0;\n\t\t";
01801   buf += "do {\n\t\t\t";
01802   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
01803   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
01804   buf += elementName;
01805   buf += " = (";
01806   buf += elementTypeAsString;
01807   buf += ")enumState.itemsPtr[counter++];";
01808   // Replace ')' in for '(' type elem in collection ')' with all of these.
01809   ReplaceText(lparenLoc, 1, buf);
01810 
01811   ///            __continue_label: ;
01812   ///        } while (counter < limit);
01813   ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
01814   ///                                  objects:__rw_items count:16]));
01815   ///   elem = nil;
01816   ///   __break_label: ;
01817   ///  }
01818   ///  else
01819   ///       elem = nil;
01820   ///  }
01821   ///
01822   buf = ";\n\t";
01823   buf += "__continue_label_";
01824   buf += utostr(ObjCBcLabelNo.back());
01825   buf += ": ;";
01826   buf += "\n\t\t";
01827   buf += "} while (counter < limit);\n\t";
01828   buf += "} while ((limit = ";
01829   SynthCountByEnumWithState(buf);
01830   buf += "));\n\t";
01831   buf += elementName;
01832   buf += " = ((";
01833   buf += elementTypeAsString;
01834   buf += ")0);\n\t";
01835   buf += "__break_label_";
01836   buf += utostr(ObjCBcLabelNo.back());
01837   buf += ": ;\n\t";
01838   buf += "}\n\t";
01839   buf += "else\n\t\t";
01840   buf += elementName;
01841   buf += " = ((";
01842   buf += elementTypeAsString;
01843   buf += ")0);\n\t";
01844   buf += "}\n";
01845 
01846   // Insert all these *after* the statement body.
01847   // FIXME: If this should support Obj-C++, support CXXTryStmt
01848   if (isa<CompoundStmt>(S->getBody())) {
01849     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
01850     InsertText(endBodyLoc, buf);
01851   } else {
01852     /* Need to treat single statements specially. For example:
01853      *
01854      *     for (A *a in b) if (stuff()) break;
01855      *     for (A *a in b) xxxyy;
01856      *
01857      * The following code simply scans ahead to the semi to find the actual end.
01858      */
01859     const char *stmtBuf = SM->getCharacterData(OrigEnd);
01860     const char *semiBuf = strchr(stmtBuf, ';');
01861     assert(semiBuf && "Can't find ';'");
01862     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
01863     InsertText(endBodyLoc, buf);
01864   }
01865   Stmts.pop_back();
01866   ObjCBcLabelNo.pop_back();
01867   return nullptr;
01868 }
01869 
01870 static void Write_RethrowObject(std::string &buf) {
01871   buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
01872   buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
01873   buf += "\tid rethrow;\n";
01874   buf += "\t} _fin_force_rethow(_rethrow);";
01875 }
01876 
01877 /// RewriteObjCSynchronizedStmt -
01878 /// This routine rewrites @synchronized(expr) stmt;
01879 /// into:
01880 /// objc_sync_enter(expr);
01881 /// @try stmt @finally { objc_sync_exit(expr); }
01882 ///
01883 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
01884   // Get the start location and compute the semi location.
01885   SourceLocation startLoc = S->getLocStart();
01886   const char *startBuf = SM->getCharacterData(startLoc);
01887 
01888   assert((*startBuf == '@') && "bogus @synchronized location");
01889 
01890   std::string buf;
01891   SourceLocation SynchLoc = S->getAtSynchronizedLoc();
01892   ConvertSourceLocationToLineDirective(SynchLoc, buf);
01893   buf += "{ id _rethrow = 0; id _sync_obj = (id)";
01894   
01895   const char *lparenBuf = startBuf;
01896   while (*lparenBuf != '(') lparenBuf++;
01897   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
01898   
01899   buf = "; objc_sync_enter(_sync_obj);\n";
01900   buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
01901   buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
01902   buf += "\n\tid sync_exit;";
01903   buf += "\n\t} _sync_exit(_sync_obj);\n";
01904 
01905   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
01906   // the sync expression is typically a message expression that's already
01907   // been rewritten! (which implies the SourceLocation's are invalid).
01908   SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
01909   const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
01910   while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
01911   RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
01912   
01913   SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
01914   const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
01915   assert (*LBraceLocBuf == '{');
01916   ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
01917   
01918   SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
01919   assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
01920          "bogus @synchronized block");
01921   
01922   buf = "} catch (id e) {_rethrow = e;}\n";
01923   Write_RethrowObject(buf);
01924   buf += "}\n";
01925   buf += "}\n";
01926 
01927   ReplaceText(startRBraceLoc, 1, buf);
01928 
01929   return nullptr;
01930 }
01931 
01932 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
01933 {
01934   // Perform a bottom up traversal of all children.
01935   for (Stmt::child_range CI = S->children(); CI; ++CI)
01936     if (*CI)
01937       WarnAboutReturnGotoStmts(*CI);
01938 
01939   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
01940     Diags.Report(Context->getFullLoc(S->getLocStart()),
01941                  TryFinallyContainsReturnDiag);
01942   }
01943   return;
01944 }
01945 
01946 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
01947   SourceLocation startLoc = S->getAtLoc();
01948   ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
01949   ReplaceText(S->getSubStmt()->getLocStart(), 1, 
01950               "{ __AtAutoreleasePool __autoreleasepool; ");
01951 
01952   return nullptr;
01953 }
01954 
01955 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
01956   ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
01957   bool noCatch = S->getNumCatchStmts() == 0;
01958   std::string buf;
01959   SourceLocation TryLocation = S->getAtTryLoc();
01960   ConvertSourceLocationToLineDirective(TryLocation, buf);
01961   
01962   if (finalStmt) {
01963     if (noCatch)
01964       buf += "{ id volatile _rethrow = 0;\n";
01965     else {
01966       buf += "{ id volatile _rethrow = 0;\ntry {\n";
01967     }
01968   }
01969   // Get the start location and compute the semi location.
01970   SourceLocation startLoc = S->getLocStart();
01971   const char *startBuf = SM->getCharacterData(startLoc);
01972 
01973   assert((*startBuf == '@') && "bogus @try location");
01974   if (finalStmt)
01975     ReplaceText(startLoc, 1, buf);
01976   else
01977     // @try -> try
01978     ReplaceText(startLoc, 1, "");
01979   
01980   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
01981     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
01982     VarDecl *catchDecl = Catch->getCatchParamDecl();
01983     
01984     startLoc = Catch->getLocStart();
01985     bool AtRemoved = false;
01986     if (catchDecl) {
01987       QualType t = catchDecl->getType();
01988       if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
01989         // Should be a pointer to a class.
01990         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
01991         if (IDecl) {
01992           std::string Result;
01993           ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
01994           
01995           startBuf = SM->getCharacterData(startLoc);
01996           assert((*startBuf == '@') && "bogus @catch location");
01997           SourceLocation rParenLoc = Catch->getRParenLoc();
01998           const char *rParenBuf = SM->getCharacterData(rParenLoc);
01999           
02000           // _objc_exc_Foo *_e as argument to catch.
02001           Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
02002           Result += " *_"; Result += catchDecl->getNameAsString();
02003           Result += ")";
02004           ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
02005           // Foo *e = (Foo *)_e;
02006           Result.clear();
02007           Result = "{ ";
02008           Result += IDecl->getNameAsString();
02009           Result += " *"; Result += catchDecl->getNameAsString();
02010           Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
02011           Result += "_"; Result += catchDecl->getNameAsString();
02012           
02013           Result += "; ";
02014           SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
02015           ReplaceText(lBraceLoc, 1, Result);
02016           AtRemoved = true;
02017         }
02018       }
02019     }
02020     if (!AtRemoved)
02021       // @catch -> catch
02022       ReplaceText(startLoc, 1, "");
02023       
02024   }
02025   if (finalStmt) {
02026     buf.clear();
02027     SourceLocation FinallyLoc = finalStmt->getLocStart();
02028     
02029     if (noCatch) {
02030       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
02031       buf += "catch (id e) {_rethrow = e;}\n";
02032     }
02033     else {
02034       buf += "}\n";
02035       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
02036       buf += "catch (id e) {_rethrow = e;}\n";
02037     }
02038     
02039     SourceLocation startFinalLoc = finalStmt->getLocStart();
02040     ReplaceText(startFinalLoc, 8, buf);
02041     Stmt *body = finalStmt->getFinallyBody();
02042     SourceLocation startFinalBodyLoc = body->getLocStart();
02043     buf.clear();
02044     Write_RethrowObject(buf);
02045     ReplaceText(startFinalBodyLoc, 1, buf);
02046     
02047     SourceLocation endFinalBodyLoc = body->getLocEnd();
02048     ReplaceText(endFinalBodyLoc, 1, "}\n}");
02049     // Now check for any return/continue/go statements within the @try.
02050     WarnAboutReturnGotoStmts(S->getTryBody());
02051   }
02052 
02053   return nullptr;
02054 }
02055 
02056 // This can't be done with ReplaceStmt(S, ThrowExpr), since
02057 // the throw expression is typically a message expression that's already
02058 // been rewritten! (which implies the SourceLocation's are invalid).
02059 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
02060   // Get the start location and compute the semi location.
02061   SourceLocation startLoc = S->getLocStart();
02062   const char *startBuf = SM->getCharacterData(startLoc);
02063 
02064   assert((*startBuf == '@') && "bogus @throw location");
02065 
02066   std::string buf;
02067   /* void objc_exception_throw(id) __attribute__((noreturn)); */
02068   if (S->getThrowExpr())
02069     buf = "objc_exception_throw(";
02070   else
02071     buf = "throw";
02072 
02073   // handle "@  throw" correctly.
02074   const char *wBuf = strchr(startBuf, 'w');
02075   assert((*wBuf == 'w') && "@throw: can't find 'w'");
02076   ReplaceText(startLoc, wBuf-startBuf+1, buf);
02077 
02078   SourceLocation endLoc = S->getLocEnd();
02079   const char *endBuf = SM->getCharacterData(endLoc);
02080   const char *semiBuf = strchr(endBuf, ';');
02081   assert((*semiBuf == ';') && "@throw: can't find ';'");
02082   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
02083   if (S->getThrowExpr())
02084     ReplaceText(semiLoc, 1, ");");
02085   return nullptr;
02086 }
02087 
02088 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
02089   // Create a new string expression.
02090   std::string StrEncoding;
02091   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
02092   Expr *Replacement = getStringLiteral(StrEncoding);
02093   ReplaceStmt(Exp, Replacement);
02094 
02095   // Replace this subexpr in the parent.
02096   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02097   return Replacement;
02098 }
02099 
02100 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
02101   if (!SelGetUidFunctionDecl)
02102     SynthSelGetUidFunctionDecl();
02103   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
02104   // Create a call to sel_registerName("selName").
02105   SmallVector<Expr*, 8> SelExprs;
02106   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
02107   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02108                                                  &SelExprs[0], SelExprs.size());
02109   ReplaceStmt(Exp, SelExp);
02110   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02111   return SelExp;
02112 }
02113 
02114 CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
02115   FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
02116                                                     SourceLocation EndLoc) {
02117   // Get the type, we will need to reference it in a couple spots.
02118   QualType msgSendType = FD->getType();
02119 
02120   // Create a reference to the objc_msgSend() declaration.
02121   DeclRefExpr *DRE =
02122     new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
02123 
02124   // Now, we cast the reference to a pointer to the objc_msgSend type.
02125   QualType pToFunc = Context->getPointerType(msgSendType);
02126   ImplicitCastExpr *ICE = 
02127     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
02128                              DRE, nullptr, VK_RValue);
02129 
02130   const FunctionType *FT = msgSendType->getAs<FunctionType>();
02131 
02132   CallExpr *Exp =  
02133     new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
02134                            FT->getCallResultType(*Context),
02135                            VK_RValue, EndLoc);
02136   return Exp;
02137 }
02138 
02139 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
02140                                 const char *&startRef, const char *&endRef) {
02141   while (startBuf < endBuf) {
02142     if (*startBuf == '<')
02143       startRef = startBuf; // mark the start.
02144     if (*startBuf == '>') {
02145       if (startRef && *startRef == '<') {
02146         endRef = startBuf; // mark the end.
02147         return true;
02148       }
02149       return false;
02150     }
02151     startBuf++;
02152   }
02153   return false;
02154 }
02155 
02156 static void scanToNextArgument(const char *&argRef) {
02157   int angle = 0;
02158   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
02159     if (*argRef == '<')
02160       angle++;
02161     else if (*argRef == '>')
02162       angle--;
02163     argRef++;
02164   }
02165   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
02166 }
02167 
02168 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
02169   if (T->isObjCQualifiedIdType())
02170     return true;
02171   if (const PointerType *PT = T->getAs<PointerType>()) {
02172     if (PT->getPointeeType()->isObjCQualifiedIdType())
02173       return true;
02174   }
02175   if (T->isObjCObjectPointerType()) {
02176     T = T->getPointeeType();
02177     return T->isObjCQualifiedInterfaceType();
02178   }
02179   if (T->isArrayType()) {
02180     QualType ElemTy = Context->getBaseElementType(T);
02181     return needToScanForQualifiers(ElemTy);
02182   }
02183   return false;
02184 }
02185 
02186 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
02187   QualType Type = E->getType();
02188   if (needToScanForQualifiers(Type)) {
02189     SourceLocation Loc, EndLoc;
02190 
02191     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
02192       Loc = ECE->getLParenLoc();
02193       EndLoc = ECE->getRParenLoc();
02194     } else {
02195       Loc = E->getLocStart();
02196       EndLoc = E->getLocEnd();
02197     }
02198     // This will defend against trying to rewrite synthesized expressions.
02199     if (Loc.isInvalid() || EndLoc.isInvalid())
02200       return;
02201 
02202     const char *startBuf = SM->getCharacterData(Loc);
02203     const char *endBuf = SM->getCharacterData(EndLoc);
02204     const char *startRef = nullptr, *endRef = nullptr;
02205     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02206       // Get the locations of the startRef, endRef.
02207       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
02208       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
02209       // Comment out the protocol references.
02210       InsertText(LessLoc, "/*");
02211       InsertText(GreaterLoc, "*/");
02212     }
02213   }
02214 }
02215 
02216 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
02217   SourceLocation Loc;
02218   QualType Type;
02219   const FunctionProtoType *proto = nullptr;
02220   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
02221     Loc = VD->getLocation();
02222     Type = VD->getType();
02223   }
02224   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
02225     Loc = FD->getLocation();
02226     // Check for ObjC 'id' and class types that have been adorned with protocol
02227     // information (id<p>, C<p>*). The protocol references need to be rewritten!
02228     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
02229     assert(funcType && "missing function type");
02230     proto = dyn_cast<FunctionProtoType>(funcType);
02231     if (!proto)
02232       return;
02233     Type = proto->getReturnType();
02234   }
02235   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
02236     Loc = FD->getLocation();
02237     Type = FD->getType();
02238   }
02239   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
02240     Loc = TD->getLocation();
02241     Type = TD->getUnderlyingType();
02242   }
02243   else
02244     return;
02245 
02246   if (needToScanForQualifiers(Type)) {
02247     // Since types are unique, we need to scan the buffer.
02248 
02249     const char *endBuf = SM->getCharacterData(Loc);
02250     const char *startBuf = endBuf;
02251     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
02252       startBuf--; // scan backward (from the decl location) for return type.
02253     const char *startRef = nullptr, *endRef = nullptr;
02254     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02255       // Get the locations of the startRef, endRef.
02256       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
02257       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
02258       // Comment out the protocol references.
02259       InsertText(LessLoc, "/*");
02260       InsertText(GreaterLoc, "*/");
02261     }
02262   }
02263   if (!proto)
02264       return; // most likely, was a variable
02265   // Now check arguments.
02266   const char *startBuf = SM->getCharacterData(Loc);
02267   const char *startFuncBuf = startBuf;
02268   for (unsigned i = 0; i < proto->getNumParams(); i++) {
02269     if (needToScanForQualifiers(proto->getParamType(i))) {
02270       // Since types are unique, we need to scan the buffer.
02271 
02272       const char *endBuf = startBuf;
02273       // scan forward (from the decl location) for argument types.
02274       scanToNextArgument(endBuf);
02275       const char *startRef = nullptr, *endRef = nullptr;
02276       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02277         // Get the locations of the startRef, endRef.
02278         SourceLocation LessLoc =
02279           Loc.getLocWithOffset(startRef-startFuncBuf);
02280         SourceLocation GreaterLoc =
02281           Loc.getLocWithOffset(endRef-startFuncBuf+1);
02282         // Comment out the protocol references.
02283         InsertText(LessLoc, "/*");
02284         InsertText(GreaterLoc, "*/");
02285       }
02286       startBuf = ++endBuf;
02287     }
02288     else {
02289       // If the function name is derived from a macro expansion, then the
02290       // argument buffer will not follow the name. Need to speak with Chris.
02291       while (*startBuf && *startBuf != ')' && *startBuf != ',')
02292         startBuf++; // scan forward (from the decl location) for argument types.
02293       startBuf++;
02294     }
02295   }
02296 }
02297 
02298 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
02299   QualType QT = ND->getType();
02300   const Type* TypePtr = QT->getAs<Type>();
02301   if (!isa<TypeOfExprType>(TypePtr))
02302     return;
02303   while (isa<TypeOfExprType>(TypePtr)) {
02304     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
02305     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
02306     TypePtr = QT->getAs<Type>();
02307   }
02308   // FIXME. This will not work for multiple declarators; as in:
02309   // __typeof__(a) b,c,d;
02310   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
02311   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
02312   const char *startBuf = SM->getCharacterData(DeclLoc);
02313   if (ND->getInit()) {
02314     std::string Name(ND->getNameAsString());
02315     TypeAsString += " " + Name + " = ";
02316     Expr *E = ND->getInit();
02317     SourceLocation startLoc;
02318     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
02319       startLoc = ECE->getLParenLoc();
02320     else
02321       startLoc = E->getLocStart();
02322     startLoc = SM->getExpansionLoc(startLoc);
02323     const char *endBuf = SM->getCharacterData(startLoc);
02324     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
02325   }
02326   else {
02327     SourceLocation X = ND->getLocEnd();
02328     X = SM->getExpansionLoc(X);
02329     const char *endBuf = SM->getCharacterData(X);
02330     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
02331   }
02332 }
02333 
02334 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
02335 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
02336   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
02337   SmallVector<QualType, 16> ArgTys;
02338   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02339   QualType getFuncType =
02340     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
02341   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02342                                                SourceLocation(),
02343                                                SourceLocation(),
02344                                                SelGetUidIdent, getFuncType,
02345                                                nullptr, SC_Extern);
02346 }
02347 
02348 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
02349   // declared in <objc/objc.h>
02350   if (FD->getIdentifier() &&
02351       FD->getName() == "sel_registerName") {
02352     SelGetUidFunctionDecl = FD;
02353     return;
02354   }
02355   RewriteObjCQualifiedInterfaceTypes(FD);
02356 }
02357 
02358 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
02359   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
02360   const char *argPtr = TypeString.c_str();
02361   if (!strchr(argPtr, '^')) {
02362     Str += TypeString;
02363     return;
02364   }
02365   while (*argPtr) {
02366     Str += (*argPtr == '^' ? '*' : *argPtr);
02367     argPtr++;
02368   }
02369 }
02370 
02371 // FIXME. Consolidate this routine with RewriteBlockPointerType.
02372 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
02373                                                   ValueDecl *VD) {
02374   QualType Type = VD->getType();
02375   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
02376   const char *argPtr = TypeString.c_str();
02377   int paren = 0;
02378   while (*argPtr) {
02379     switch (*argPtr) {
02380       case '(':
02381         Str += *argPtr;
02382         paren++;
02383         break;
02384       case ')':
02385         Str += *argPtr;
02386         paren--;
02387         break;
02388       case '^':
02389         Str += '*';
02390         if (paren == 1)
02391           Str += VD->getNameAsString();
02392         break;
02393       default:
02394         Str += *argPtr;
02395         break;
02396     }
02397     argPtr++;
02398   }
02399 }
02400 
02401 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
02402   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
02403   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
02404   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
02405   if (!proto)
02406     return;
02407   QualType Type = proto->getReturnType();
02408   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
02409   FdStr += " ";
02410   FdStr += FD->getName();
02411   FdStr +=  "(";
02412   unsigned numArgs = proto->getNumParams();
02413   for (unsigned i = 0; i < numArgs; i++) {
02414     QualType ArgType = proto->getParamType(i);
02415   RewriteBlockPointerType(FdStr, ArgType);
02416   if (i+1 < numArgs)
02417     FdStr += ", ";
02418   }
02419   if (FD->isVariadic()) {
02420     FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
02421   }
02422   else
02423     FdStr +=  ");\n";
02424   InsertText(FunLocStart, FdStr);
02425 }
02426 
02427 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
02428 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
02429   if (SuperConstructorFunctionDecl)
02430     return;
02431   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
02432   SmallVector<QualType, 16> ArgTys;
02433   QualType argT = Context->getObjCIdType();
02434   assert(!argT.isNull() && "Can't find 'id' type");
02435   ArgTys.push_back(argT);
02436   ArgTys.push_back(argT);
02437   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02438                                                ArgTys);
02439   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02440                                                      SourceLocation(),
02441                                                      SourceLocation(),
02442                                                      msgSendIdent, msgSendType,
02443                                                      nullptr, SC_Extern);
02444 }
02445 
02446 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
02447 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
02448   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
02449   SmallVector<QualType, 16> ArgTys;
02450   QualType argT = Context->getObjCIdType();
02451   assert(!argT.isNull() && "Can't find 'id' type");
02452   ArgTys.push_back(argT);
02453   argT = Context->getObjCSelType();
02454   assert(!argT.isNull() && "Can't find 'SEL' type");
02455   ArgTys.push_back(argT);
02456   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02457                                                ArgTys, /*isVariadic=*/true);
02458   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02459                                              SourceLocation(),
02460                                              SourceLocation(),
02461                                              msgSendIdent, msgSendType, nullptr,
02462                                              SC_Extern);
02463 }
02464 
02465 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
02466 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
02467   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
02468   SmallVector<QualType, 2> ArgTys;
02469   ArgTys.push_back(Context->VoidTy);
02470   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02471                                                ArgTys, /*isVariadic=*/true);
02472   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02473                                                   SourceLocation(),
02474                                                   SourceLocation(),
02475                                                   msgSendIdent, msgSendType,
02476                                                   nullptr, SC_Extern);
02477 }
02478 
02479 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
02480 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
02481   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
02482   SmallVector<QualType, 16> ArgTys;
02483   QualType argT = Context->getObjCIdType();
02484   assert(!argT.isNull() && "Can't find 'id' type");
02485   ArgTys.push_back(argT);
02486   argT = Context->getObjCSelType();
02487   assert(!argT.isNull() && "Can't find 'SEL' type");
02488   ArgTys.push_back(argT);
02489   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02490                                                ArgTys, /*isVariadic=*/true);
02491   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02492                                                   SourceLocation(),
02493                                                   SourceLocation(),
02494                                                   msgSendIdent, msgSendType,
02495                                                   nullptr, SC_Extern);
02496 }
02497 
02498 // SynthMsgSendSuperStretFunctionDecl -
02499 // id objc_msgSendSuper_stret(void);
02500 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
02501   IdentifierInfo *msgSendIdent =
02502     &Context->Idents.get("objc_msgSendSuper_stret");
02503   SmallVector<QualType, 2> ArgTys;
02504   ArgTys.push_back(Context->VoidTy);
02505   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02506                                                ArgTys, /*isVariadic=*/true);
02507   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02508                                                        SourceLocation(),
02509                                                        SourceLocation(),
02510                                                        msgSendIdent,
02511                                                        msgSendType, nullptr,
02512                                                        SC_Extern);
02513 }
02514 
02515 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
02516 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
02517   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
02518   SmallVector<QualType, 16> ArgTys;
02519   QualType argT = Context->getObjCIdType();
02520   assert(!argT.isNull() && "Can't find 'id' type");
02521   ArgTys.push_back(argT);
02522   argT = Context->getObjCSelType();
02523   assert(!argT.isNull() && "Can't find 'SEL' type");
02524   ArgTys.push_back(argT);
02525   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
02526                                                ArgTys, /*isVariadic=*/true);
02527   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02528                                                   SourceLocation(),
02529                                                   SourceLocation(),
02530                                                   msgSendIdent, msgSendType,
02531                                                   nullptr, SC_Extern);
02532 }
02533 
02534 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
02535 void RewriteModernObjC::SynthGetClassFunctionDecl() {
02536   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
02537   SmallVector<QualType, 16> ArgTys;
02538   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02539   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
02540                                                 ArgTys);
02541   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02542                                               SourceLocation(),
02543                                               SourceLocation(),
02544                                               getClassIdent, getClassType,
02545                                               nullptr, SC_Extern);
02546 }
02547 
02548 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
02549 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
02550   IdentifierInfo *getSuperClassIdent = 
02551     &Context->Idents.get("class_getSuperclass");
02552   SmallVector<QualType, 16> ArgTys;
02553   ArgTys.push_back(Context->getObjCClassType());
02554   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
02555                                                 ArgTys);
02556   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02557                                                    SourceLocation(),
02558                                                    SourceLocation(),
02559                                                    getSuperClassIdent,
02560                                                    getClassType, nullptr,
02561                                                    SC_Extern);
02562 }
02563 
02564 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
02565 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
02566   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
02567   SmallVector<QualType, 16> ArgTys;
02568   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02569   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
02570                                                 ArgTys);
02571   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02572                                                   SourceLocation(),
02573                                                   SourceLocation(),
02574                                                   getClassIdent, getClassType,
02575                                                   nullptr, SC_Extern);
02576 }
02577 
02578 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
02579   assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
02580   QualType strType = getConstantStringStructType();
02581 
02582   std::string S = "__NSConstantStringImpl_";
02583 
02584   std::string tmpName = InFileName;
02585   unsigned i;
02586   for (i=0; i < tmpName.length(); i++) {
02587     char c = tmpName.at(i);
02588     // replace any non-alphanumeric characters with '_'.
02589     if (!isAlphanumeric(c))
02590       tmpName[i] = '_';
02591   }
02592   S += tmpName;
02593   S += "_";
02594   S += utostr(NumObjCStringLiterals++);
02595 
02596   Preamble += "static __NSConstantStringImpl " + S;
02597   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
02598   Preamble += "0x000007c8,"; // utf8_str
02599   // The pretty printer for StringLiteral handles escape characters properly.
02600   std::string prettyBufS;
02601   llvm::raw_string_ostream prettyBuf(prettyBufS);
02602   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
02603   Preamble += prettyBuf.str();
02604   Preamble += ",";
02605   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
02606 
02607   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
02608                                    SourceLocation(), &Context->Idents.get(S),
02609                                    strType, nullptr, SC_Static);
02610   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
02611                                                SourceLocation());
02612   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
02613                                  Context->getPointerType(DRE->getType()),
02614                                            VK_RValue, OK_Ordinary,
02615                                            SourceLocation());
02616   // cast to NSConstantString *
02617   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
02618                                             CK_CPointerToObjCPointerCast, Unop);
02619   ReplaceStmt(Exp, cast);
02620   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02621   return cast;
02622 }
02623 
02624 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
02625   unsigned IntSize =
02626     static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
02627   
02628   Expr *FlagExp = IntegerLiteral::Create(*Context, 
02629                                          llvm::APInt(IntSize, Exp->getValue()), 
02630                                          Context->IntTy, Exp->getLocation());
02631   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
02632                                             CK_BitCast, FlagExp);
02633   ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), 
02634                                           cast);
02635   ReplaceStmt(Exp, PE);
02636   return PE;
02637 }
02638 
02639 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
02640   // synthesize declaration of helper functions needed in this routine.
02641   if (!SelGetUidFunctionDecl)
02642     SynthSelGetUidFunctionDecl();
02643   // use objc_msgSend() for all.
02644   if (!MsgSendFunctionDecl)
02645     SynthMsgSendFunctionDecl();
02646   if (!GetClassFunctionDecl)
02647     SynthGetClassFunctionDecl();
02648   
02649   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
02650   SourceLocation StartLoc = Exp->getLocStart();
02651   SourceLocation EndLoc = Exp->getLocEnd();
02652   
02653   // Synthesize a call to objc_msgSend().
02654   SmallVector<Expr*, 4> MsgExprs;
02655   SmallVector<Expr*, 4> ClsExprs;
02656   
02657   // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
02658   ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
02659   ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
02660   
02661   IdentifierInfo *clsName = BoxingClass->getIdentifier();
02662   ClsExprs.push_back(getStringLiteral(clsName->getName()));
02663   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
02664                                                &ClsExprs[0],
02665                                                ClsExprs.size(), 
02666                                                StartLoc, EndLoc);
02667   MsgExprs.push_back(Cls);
02668   
02669   // Create a call to sel_registerName("<BoxingMethod>:"), etc.
02670   // it will be the 2nd argument.
02671   SmallVector<Expr*, 4> SelExprs;
02672   SelExprs.push_back(
02673       getStringLiteral(BoxingMethod->getSelector().getAsString()));
02674   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02675                                                   &SelExprs[0], SelExprs.size(),
02676                                                   StartLoc, EndLoc);
02677   MsgExprs.push_back(SelExp);
02678   
02679   // User provided sub-expression is the 3rd, and last, argument.
02680   Expr *subExpr  = Exp->getSubExpr();
02681   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
02682     QualType type = ICE->getType();
02683     const Expr *SubExpr = ICE->IgnoreParenImpCasts();
02684     CastKind CK = CK_BitCast;
02685     if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
02686       CK = CK_IntegralToBoolean;
02687     subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
02688   }
02689   MsgExprs.push_back(subExpr);
02690   
02691   SmallVector<QualType, 4> ArgTypes;
02692   ArgTypes.push_back(Context->getObjCIdType());
02693   ArgTypes.push_back(Context->getObjCSelType());
02694   for (const auto PI : BoxingMethod->parameters())
02695     ArgTypes.push_back(PI->getType());
02696   
02697   QualType returnType = Exp->getType();
02698   // Get the type, we will need to reference it in a couple spots.
02699   QualType msgSendType = MsgSendFlavor->getType();
02700   
02701   // Create a reference to the objc_msgSend() declaration.
02702   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
02703                                                VK_LValue, SourceLocation());
02704   
02705   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
02706                                             Context->getPointerType(Context->VoidTy),
02707                                             CK_BitCast, DRE);
02708   
02709   // Now do the "normal" pointer to function cast.
02710   QualType castType =
02711     getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
02712   castType = Context->getPointerType(castType);
02713   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
02714                                   cast);
02715   
02716   // Don't forget the parens to enforce the proper binding.
02717   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
02718   
02719   const FunctionType *FT = msgSendType->getAs<FunctionType>();
02720   CallExpr *CE = new (Context)
02721       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
02722   ReplaceStmt(Exp, CE);
02723   return CE;
02724 }
02725 
02726 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
02727   // synthesize declaration of helper functions needed in this routine.
02728   if (!SelGetUidFunctionDecl)
02729     SynthSelGetUidFunctionDecl();
02730   // use objc_msgSend() for all.
02731   if (!MsgSendFunctionDecl)
02732     SynthMsgSendFunctionDecl();
02733   if (!GetClassFunctionDecl)
02734     SynthGetClassFunctionDecl();
02735   
02736   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
02737   SourceLocation StartLoc = Exp->getLocStart();
02738   SourceLocation EndLoc = Exp->getLocEnd();
02739   
02740   // Build the expression: __NSContainer_literal(int, ...).arr
02741   QualType IntQT = Context->IntTy;
02742   QualType NSArrayFType =
02743     getSimpleFunctionType(Context->VoidTy, IntQT, true);
02744   std::string NSArrayFName("__NSContainer_literal");
02745   FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
02746   DeclRefExpr *NSArrayDRE = 
02747     new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
02748                               SourceLocation());
02749 
02750   SmallVector<Expr*, 16> InitExprs;
02751   unsigned NumElements = Exp->getNumElements();
02752   unsigned UnsignedIntSize = 
02753     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
02754   Expr *count = IntegerLiteral::Create(*Context,
02755                                        llvm::APInt(UnsignedIntSize, NumElements),
02756                                        Context->UnsignedIntTy, SourceLocation());
02757   InitExprs.push_back(count);
02758   for (unsigned i = 0; i < NumElements; i++)
02759     InitExprs.push_back(Exp->getElement(i));
02760   Expr *NSArrayCallExpr = 
02761     new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
02762                            NSArrayFType, VK_LValue, SourceLocation());
02763 
02764   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
02765                                     SourceLocation(),
02766                                     &Context->Idents.get("arr"),
02767                                     Context->getPointerType(Context->VoidPtrTy),
02768                                     nullptr, /*BitWidth=*/nullptr,
02769                                     /*Mutable=*/true, ICIS_NoInit);
02770   MemberExpr *ArrayLiteralME = 
02771     new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD, 
02772                              SourceLocation(),
02773                              ARRFD->getType(), VK_LValue,
02774                              OK_Ordinary);
02775   QualType ConstIdT = Context->getObjCIdType().withConst();
02776   CStyleCastExpr * ArrayLiteralObjects = 
02777     NoTypeInfoCStyleCastExpr(Context, 
02778                              Context->getPointerType(ConstIdT),
02779                              CK_BitCast,
02780                              ArrayLiteralME);
02781   
02782   // Synthesize a call to objc_msgSend().
02783   SmallVector<Expr*, 32> MsgExprs;
02784   SmallVector<Expr*, 4> ClsExprs;
02785   QualType expType = Exp->getType();
02786   
02787   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
02788   ObjCInterfaceDecl *Class = 
02789     expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
02790   
02791   IdentifierInfo *clsName = Class->getIdentifier();
02792   ClsExprs.push_back(getStringLiteral(clsName->getName()));
02793   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
02794                                                &ClsExprs[0],
02795                                                ClsExprs.size(), 
02796                                                StartLoc, EndLoc);
02797   MsgExprs.push_back(Cls);
02798   
02799   // Create a call to sel_registerName("arrayWithObjects:count:").
02800   // it will be the 2nd argument.
02801   SmallVector<Expr*, 4> SelExprs;
02802   ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
02803   SelExprs.push_back(
02804       getStringLiteral(ArrayMethod->getSelector().getAsString()));
02805   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02806                                                   &SelExprs[0], SelExprs.size(),
02807                                                   StartLoc, EndLoc);
02808   MsgExprs.push_back(SelExp);
02809   
02810   // (const id [])objects
02811   MsgExprs.push_back(ArrayLiteralObjects);
02812   
02813   // (NSUInteger)cnt
02814   Expr *cnt = IntegerLiteral::Create(*Context,
02815                                      llvm::APInt(UnsignedIntSize, NumElements),
02816                                      Context->UnsignedIntTy, SourceLocation());
02817   MsgExprs.push_back(cnt);
02818   
02819   
02820   SmallVector<QualType, 4> ArgTypes;
02821   ArgTypes.push_back(Context->getObjCIdType());
02822   ArgTypes.push_back(Context->getObjCSelType());
02823   for (const auto *PI : ArrayMethod->params())
02824     ArgTypes.push_back(PI->getType());
02825   
02826   QualType returnType = Exp->getType();
02827   // Get the type, we will need to reference it in a couple spots.
02828   QualType msgSendType = MsgSendFlavor->getType();
02829   
02830   // Create a reference to the objc_msgSend() declaration.
02831   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
02832                                                VK_LValue, SourceLocation());
02833   
02834   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
02835                                             Context->getPointerType(Context->VoidTy),
02836                                             CK_BitCast, DRE);
02837   
02838   // Now do the "normal" pointer to function cast.
02839   QualType castType =
02840   getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
02841   castType = Context->getPointerType(castType);
02842   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
02843                                   cast);
02844   
02845   // Don't forget the parens to enforce the proper binding.
02846   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
02847   
02848   const FunctionType *FT = msgSendType->getAs<FunctionType>();
02849   CallExpr *CE = new (Context)
02850       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
02851   ReplaceStmt(Exp, CE);
02852   return CE;
02853 }
02854 
02855 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
02856   // synthesize declaration of helper functions needed in this routine.
02857   if (!SelGetUidFunctionDecl)
02858     SynthSelGetUidFunctionDecl();
02859   // use objc_msgSend() for all.
02860   if (!MsgSendFunctionDecl)
02861     SynthMsgSendFunctionDecl();
02862   if (!GetClassFunctionDecl)
02863     SynthGetClassFunctionDecl();
02864   
02865   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
02866   SourceLocation StartLoc = Exp->getLocStart();
02867   SourceLocation EndLoc = Exp->getLocEnd();
02868   
02869   // Build the expression: __NSContainer_literal(int, ...).arr
02870   QualType IntQT = Context->IntTy;
02871   QualType NSDictFType =
02872     getSimpleFunctionType(Context->VoidTy, IntQT, true);
02873   std::string NSDictFName("__NSContainer_literal");
02874   FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
02875   DeclRefExpr *NSDictDRE = 
02876     new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
02877                               SourceLocation());
02878   
02879   SmallVector<Expr*, 16> KeyExprs;
02880   SmallVector<Expr*, 16> ValueExprs;
02881   
02882   unsigned NumElements = Exp->getNumElements();
02883   unsigned UnsignedIntSize = 
02884     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
02885   Expr *count = IntegerLiteral::Create(*Context,
02886                                        llvm::APInt(UnsignedIntSize, NumElements),
02887                                        Context->UnsignedIntTy, SourceLocation());
02888   KeyExprs.push_back(count);
02889   ValueExprs.push_back(count);
02890   for (unsigned i = 0; i < NumElements; i++) {
02891     ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
02892     KeyExprs.push_back(Element.Key);
02893     ValueExprs.push_back(Element.Value);
02894   }
02895   
02896   // (const id [])objects
02897   Expr *NSValueCallExpr = 
02898     new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
02899                            NSDictFType, VK_LValue, SourceLocation());
02900 
02901   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
02902                                        SourceLocation(),
02903                                        &Context->Idents.get("arr"),
02904                                        Context->getPointerType(Context->VoidPtrTy),
02905                                        nullptr, /*BitWidth=*/nullptr,
02906                                        /*Mutable=*/true, ICIS_NoInit);
02907   MemberExpr *DictLiteralValueME = 
02908     new (Context) MemberExpr(NSValueCallExpr, false, ARRFD, 
02909                              SourceLocation(),
02910                              ARRFD->getType(), VK_LValue,
02911                              OK_Ordinary);
02912   QualType ConstIdT = Context->getObjCIdType().withConst();
02913   CStyleCastExpr * DictValueObjects = 
02914     NoTypeInfoCStyleCastExpr(Context, 
02915                              Context->getPointerType(ConstIdT),
02916                              CK_BitCast,
02917                              DictLiteralValueME);
02918   // (const id <NSCopying> [])keys
02919   Expr *NSKeyCallExpr = 
02920     new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
02921                            NSDictFType, VK_LValue, SourceLocation());
02922   
02923   MemberExpr *DictLiteralKeyME = 
02924     new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD, 
02925                              SourceLocation(),
02926                              ARRFD->getType(), VK_LValue,
02927                              OK_Ordinary);
02928   
02929   CStyleCastExpr * DictKeyObjects = 
02930     NoTypeInfoCStyleCastExpr(Context, 
02931                              Context->getPointerType(ConstIdT),
02932                              CK_BitCast,
02933                              DictLiteralKeyME);
02934   
02935   
02936   
02937   // Synthesize a call to objc_msgSend().
02938   SmallVector<Expr*, 32> MsgExprs;
02939   SmallVector<Expr*, 4> ClsExprs;
02940   QualType expType = Exp->getType();
02941   
02942   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
02943   ObjCInterfaceDecl *Class = 
02944   expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
02945   
02946   IdentifierInfo *clsName = Class->getIdentifier();
02947   ClsExprs.push_back(getStringLiteral(clsName->getName()));
02948   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
02949                                                &ClsExprs[0],
02950                                                ClsExprs.size(), 
02951                                                StartLoc, EndLoc);
02952   MsgExprs.push_back(Cls);
02953   
02954   // Create a call to sel_registerName("arrayWithObjects:count:").
02955   // it will be the 2nd argument.
02956   SmallVector<Expr*, 4> SelExprs;
02957   ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
02958   SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
02959   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02960                                                   &SelExprs[0], SelExprs.size(),
02961                                                   StartLoc, EndLoc);
02962   MsgExprs.push_back(SelExp);
02963   
02964   // (const id [])objects
02965   MsgExprs.push_back(DictValueObjects);
02966   
02967   // (const id <NSCopying> [])keys
02968   MsgExprs.push_back(DictKeyObjects);
02969   
02970   // (NSUInteger)cnt
02971   Expr *cnt = IntegerLiteral::Create(*Context,
02972                                      llvm::APInt(UnsignedIntSize, NumElements),
02973                                      Context->UnsignedIntTy, SourceLocation());
02974   MsgExprs.push_back(cnt);
02975   
02976   
02977   SmallVector<QualType, 8> ArgTypes;
02978   ArgTypes.push_back(Context->getObjCIdType());
02979   ArgTypes.push_back(Context->getObjCSelType());
02980   for (const auto *PI : DictMethod->params()) {
02981     QualType T = PI->getType();
02982     if (const PointerType* PT = T->getAs<PointerType>()) {
02983       QualType PointeeTy = PT->getPointeeType();
02984       convertToUnqualifiedObjCType(PointeeTy);
02985       T = Context->getPointerType(PointeeTy);
02986     }
02987     ArgTypes.push_back(T);
02988   }
02989   
02990   QualType returnType = Exp->getType();
02991   // Get the type, we will need to reference it in a couple spots.
02992   QualType msgSendType = MsgSendFlavor->getType();
02993   
02994   // Create a reference to the objc_msgSend() declaration.
02995   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
02996                                                VK_LValue, SourceLocation());
02997   
02998   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
02999                                             Context->getPointerType(Context->VoidTy),
03000                                             CK_BitCast, DRE);
03001   
03002   // Now do the "normal" pointer to function cast.
03003   QualType castType =
03004   getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
03005   castType = Context->getPointerType(castType);
03006   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
03007                                   cast);
03008   
03009   // Don't forget the parens to enforce the proper binding.
03010   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
03011   
03012   const FunctionType *FT = msgSendType->getAs<FunctionType>();
03013   CallExpr *CE = new (Context)
03014       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
03015   ReplaceStmt(Exp, CE);
03016   return CE;
03017 }
03018 
03019 // struct __rw_objc_super { 
03020 //   struct objc_object *object; struct objc_object *superClass; 
03021 // };
03022 QualType RewriteModernObjC::getSuperStructType() {
03023   if (!SuperStructDecl) {
03024     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
03025                                          SourceLocation(), SourceLocation(),
03026                                          &Context->Idents.get("__rw_objc_super"));
03027     QualType FieldTypes[2];
03028 
03029     // struct objc_object *object;
03030     FieldTypes[0] = Context->getObjCIdType();
03031     // struct objc_object *superClass;
03032     FieldTypes[1] = Context->getObjCIdType();
03033 
03034     // Create fields
03035     for (unsigned i = 0; i < 2; ++i) {
03036       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
03037                                                  SourceLocation(),
03038                                                  SourceLocation(), nullptr,
03039                                                  FieldTypes[i], nullptr,
03040                                                  /*BitWidth=*/nullptr,
03041                                                  /*Mutable=*/false,
03042                                                  ICIS_NoInit));
03043     }
03044 
03045     SuperStructDecl->completeDefinition();
03046   }
03047   return Context->getTagDeclType(SuperStructDecl);
03048 }
03049 
03050 QualType RewriteModernObjC::getConstantStringStructType() {
03051   if (!ConstantStringDecl) {
03052     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
03053                                             SourceLocation(), SourceLocation(),
03054                          &Context->Idents.get("__NSConstantStringImpl"));
03055     QualType FieldTypes[4];
03056 
03057     // struct objc_object *receiver;
03058     FieldTypes[0] = Context->getObjCIdType();
03059     // int flags;
03060     FieldTypes[1] = Context->IntTy;
03061     // char *str;
03062     FieldTypes[2] = Context->getPointerType(Context->CharTy);
03063     // long length;
03064     FieldTypes[3] = Context->LongTy;
03065 
03066     // Create fields
03067     for (unsigned i = 0; i < 4; ++i) {
03068       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
03069                                                     ConstantStringDecl,
03070                                                     SourceLocation(),
03071                                                     SourceLocation(), nullptr,
03072                                                     FieldTypes[i], nullptr,
03073                                                     /*BitWidth=*/nullptr,
03074                                                     /*Mutable=*/true,
03075                                                     ICIS_NoInit));
03076     }
03077 
03078     ConstantStringDecl->completeDefinition();
03079   }
03080   return Context->getTagDeclType(ConstantStringDecl);
03081 }
03082 
03083 /// getFunctionSourceLocation - returns start location of a function
03084 /// definition. Complication arises when function has declared as
03085 /// extern "C" or extern "C" {...}
03086 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
03087                                                  FunctionDecl *FD) {
03088   if (FD->isExternC()  && !FD->isMain()) {
03089     const DeclContext *DC = FD->getDeclContext();
03090     if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
03091       // if it is extern "C" {...}, return function decl's own location.
03092       if (!LSD->getRBraceLoc().isValid())
03093         return LSD->getExternLoc();
03094   }
03095   if (FD->getStorageClass() != SC_None)
03096     R.RewriteBlockLiteralFunctionDecl(FD);
03097   return FD->getTypeSpecStartLoc();
03098 }
03099 
03100 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
03101   
03102   SourceLocation Location = D->getLocation();
03103   
03104   if (Location.isFileID() && GenerateLineInfo) {
03105     std::string LineString("\n#line ");
03106     PresumedLoc PLoc = SM->getPresumedLoc(Location);
03107     LineString += utostr(PLoc.getLine());
03108     LineString += " \"";
03109     LineString += Lexer::Stringify(PLoc.getFilename());
03110     if (isa<ObjCMethodDecl>(D))
03111       LineString += "\"";
03112     else LineString += "\"\n";
03113     
03114     Location = D->getLocStart();
03115     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
03116       if (FD->isExternC()  && !FD->isMain()) {
03117         const DeclContext *DC = FD->getDeclContext();
03118         if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
03119           // if it is extern "C" {...}, return function decl's own location.
03120           if (!LSD->getRBraceLoc().isValid())
03121             Location = LSD->getExternLoc();
03122       }
03123     }
03124     InsertText(Location, LineString);
03125   }
03126 }
03127 
03128 /// SynthMsgSendStretCallExpr - This routine translates message expression
03129 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
03130 /// nil check on receiver must be performed before calling objc_msgSend_stret.
03131 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
03132 /// msgSendType - function type of objc_msgSend_stret(...)
03133 /// returnType - Result type of the method being synthesized.
03134 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
03135 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, 
03136 /// starting with receiver.
03137 /// Method - Method being rewritten.
03138 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
03139                                                  QualType returnType, 
03140                                                  SmallVectorImpl<QualType> &ArgTypes,
03141                                                  SmallVectorImpl<Expr*> &MsgExprs,
03142                                                  ObjCMethodDecl *Method) {
03143   // Now do the "normal" pointer to function cast.
03144   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
03145                                             Method ? Method->isVariadic()
03146                                                    : false);
03147   castType = Context->getPointerType(castType);
03148   
03149   // build type for containing the objc_msgSend_stret object.
03150   static unsigned stretCount=0;
03151   std::string name = "__Stret"; name += utostr(stretCount);
03152   std::string str = 
03153     "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
03154   str += "namespace {\n";
03155   str += "struct "; str += name;
03156   str += " {\n\t";
03157   str += name;
03158   str += "(id receiver, SEL sel";
03159   for (unsigned i = 2; i < ArgTypes.size(); i++) {
03160     std::string ArgName = "arg"; ArgName += utostr(i);
03161     ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
03162     str += ", "; str += ArgName;
03163   }
03164   // could be vararg.
03165   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
03166     std::string ArgName = "arg"; ArgName += utostr(i);
03167     MsgExprs[i]->getType().getAsStringInternal(ArgName,
03168                                                Context->getPrintingPolicy());
03169     str += ", "; str += ArgName;
03170   }
03171   
03172   str += ") {\n";
03173   str += "\t  unsigned size = sizeof(";
03174   str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
03175   
03176   str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
03177   
03178   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
03179   str += ")(void *)objc_msgSend)(receiver, sel";
03180   for (unsigned i = 2; i < ArgTypes.size(); i++) {
03181     str += ", arg"; str += utostr(i);
03182   }
03183   // could be vararg.
03184   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
03185     str += ", arg"; str += utostr(i);
03186   }
03187   str+= ");\n";
03188   
03189   str += "\t  else if (receiver == 0)\n";
03190   str += "\t    memset((void*)&s, 0, sizeof(s));\n";
03191   str += "\t  else\n";
03192   
03193   
03194   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
03195   str += ")(void *)objc_msgSend_stret)(receiver, sel";
03196   for (unsigned i = 2; i < ArgTypes.size(); i++) {
03197     str += ", arg"; str += utostr(i);
03198   }
03199   // could be vararg.
03200   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
03201     str += ", arg"; str += utostr(i);
03202   }
03203   str += ");\n";
03204   
03205   
03206   str += "\t}\n";
03207   str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
03208   str += " s;\n";
03209   str += "};\n};\n\n";
03210   SourceLocation FunLocStart;
03211   if (CurFunctionDef)
03212     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
03213   else {
03214     assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
03215     FunLocStart = CurMethodDef->getLocStart();
03216   }
03217 
03218   InsertText(FunLocStart, str);
03219   ++stretCount;
03220   
03221   // AST for __Stretn(receiver, args).s;
03222   IdentifierInfo *ID = &Context->Idents.get(name);
03223   FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
03224                                           SourceLocation(), ID, castType,
03225                                           nullptr, SC_Extern, false, false);
03226   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
03227                                                SourceLocation());
03228   CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
03229                                           castType, VK_LValue, SourceLocation());
03230 
03231   FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
03232                                     SourceLocation(),
03233                                     &Context->Idents.get("s"),
03234                                     returnType, nullptr,
03235                                     /*BitWidth=*/nullptr,
03236                                     /*Mutable=*/true, ICIS_NoInit);
03237   MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
03238                                             FieldD->getType(), VK_LValue,
03239                                             OK_Ordinary);
03240 
03241   return ME;
03242 }
03243 
03244 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
03245                                     SourceLocation StartLoc,
03246                                     SourceLocation EndLoc) {
03247   if (!SelGetUidFunctionDecl)
03248     SynthSelGetUidFunctionDecl();
03249   if (!MsgSendFunctionDecl)
03250     SynthMsgSendFunctionDecl();
03251   if (!MsgSendSuperFunctionDecl)
03252     SynthMsgSendSuperFunctionDecl();
03253   if (!MsgSendStretFunctionDecl)
03254     SynthMsgSendStretFunctionDecl();
03255   if (!MsgSendSuperStretFunctionDecl)
03256     SynthMsgSendSuperStretFunctionDecl();
03257   if (!MsgSendFpretFunctionDecl)
03258     SynthMsgSendFpretFunctionDecl();
03259   if (!GetClassFunctionDecl)
03260     SynthGetClassFunctionDecl();
03261   if (!GetSuperClassFunctionDecl)
03262     SynthGetSuperClassFunctionDecl();
03263   if (!GetMetaClassFunctionDecl)
03264     SynthGetMetaClassFunctionDecl();
03265 
03266   // default to objc_msgSend().
03267   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
03268   // May need to use objc_msgSend_stret() as well.
03269   FunctionDecl *MsgSendStretFlavor = nullptr;
03270   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
03271     QualType resultType = mDecl->getReturnType();
03272     if (resultType->isRecordType())
03273       MsgSendStretFlavor = MsgSendStretFunctionDecl;
03274     else if (resultType->isRealFloatingType())
03275       MsgSendFlavor = MsgSendFpretFunctionDecl;
03276   }
03277 
03278   // Synthesize a call to objc_msgSend().
03279   SmallVector<Expr*, 8> MsgExprs;
03280   switch (Exp->getReceiverKind()) {
03281   case ObjCMessageExpr::SuperClass: {
03282     MsgSendFlavor = MsgSendSuperFunctionDecl;
03283     if (MsgSendStretFlavor)
03284       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
03285     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
03286 
03287     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
03288 
03289     SmallVector<Expr*, 4> InitExprs;
03290 
03291     // set the receiver to self, the first argument to all methods.
03292     InitExprs.push_back(
03293       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
03294                                CK_BitCast,
03295                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
03296                                              false,
03297                                              Context->getObjCIdType(),
03298                                              VK_RValue,
03299                                              SourceLocation()))
03300                         ); // set the 'receiver'.
03301 
03302     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
03303     SmallVector<Expr*, 8> ClsExprs;
03304     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
03305     // (Class)objc_getClass("CurrentClass")
03306     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
03307                                                  &ClsExprs[0],
03308                                                  ClsExprs.size(),
03309                                                  StartLoc,
03310                                                  EndLoc);
03311     ClsExprs.clear();
03312     ClsExprs.push_back(Cls);
03313     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
03314                                        &ClsExprs[0], ClsExprs.size(),
03315                                        StartLoc, EndLoc);
03316     
03317     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
03318     // To turn off a warning, type-cast to 'id'
03319     InitExprs.push_back( // set 'super class', using class_getSuperclass().
03320                         NoTypeInfoCStyleCastExpr(Context,
03321                                                  Context->getObjCIdType(),
03322                                                  CK_BitCast, Cls));
03323     // struct __rw_objc_super
03324     QualType superType = getSuperStructType();
03325     Expr *SuperRep;
03326 
03327     if (LangOpts.MicrosoftExt) {
03328       SynthSuperConstructorFunctionDecl();
03329       // Simulate a constructor call...
03330       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
03331                                                    false, superType, VK_LValue,
03332                                                    SourceLocation());
03333       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
03334                                         superType, VK_LValue,
03335                                         SourceLocation());
03336       // The code for super is a little tricky to prevent collision with
03337       // the structure definition in the header. The rewriter has it's own
03338       // internal definition (__rw_objc_super) that is uses. This is why
03339       // we need the cast below. For example:
03340       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
03341       //
03342       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
03343                                Context->getPointerType(SuperRep->getType()),
03344                                              VK_RValue, OK_Ordinary,
03345                                              SourceLocation());
03346       SuperRep = NoTypeInfoCStyleCastExpr(Context,
03347                                           Context->getPointerType(superType),
03348                                           CK_BitCast, SuperRep);
03349     } else {
03350       // (struct __rw_objc_super) { <exprs from above> }
03351       InitListExpr *ILE =
03352         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
03353                                    SourceLocation());
03354       TypeSourceInfo *superTInfo
03355         = Context->getTrivialTypeSourceInfo(superType);
03356       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
03357                                                    superType, VK_LValue,
03358                                                    ILE, false);
03359       // struct __rw_objc_super *
03360       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
03361                                Context->getPointerType(SuperRep->getType()),
03362                                              VK_RValue, OK_Ordinary,
03363                                              SourceLocation());
03364     }
03365     MsgExprs.push_back(SuperRep);
03366     break;
03367   }
03368 
03369   case ObjCMessageExpr::Class: {
03370     SmallVector<Expr*, 8> ClsExprs;
03371     ObjCInterfaceDecl *Class
03372       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
03373     IdentifierInfo *clsName = Class->getIdentifier();
03374     ClsExprs.push_back(getStringLiteral(clsName->getName()));
03375     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
03376                                                  &ClsExprs[0],
03377                                                  ClsExprs.size(), 
03378                                                  StartLoc, EndLoc);
03379     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
03380                                                  Context->getObjCIdType(),
03381                                                  CK_BitCast, Cls);
03382     MsgExprs.push_back(ArgExpr);
03383     break;
03384   }
03385 
03386   case ObjCMessageExpr::SuperInstance:{
03387     MsgSendFlavor = MsgSendSuperFunctionDecl;
03388     if (MsgSendStretFlavor)
03389       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
03390     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
03391     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
03392     SmallVector<Expr*, 4> InitExprs;
03393 
03394     InitExprs.push_back(
03395       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
03396                                CK_BitCast,
03397                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
03398                                              false,
03399                                              Context->getObjCIdType(),
03400                                              VK_RValue, SourceLocation()))
03401                         ); // set the 'receiver'.
03402     
03403     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
03404     SmallVector<Expr*, 8> ClsExprs;
03405     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
03406     // (Class)objc_getClass("CurrentClass")
03407     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
03408                                                  &ClsExprs[0],
03409                                                  ClsExprs.size(), 
03410                                                  StartLoc, EndLoc);
03411     ClsExprs.clear();
03412     ClsExprs.push_back(Cls);
03413     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
03414                                        &ClsExprs[0], ClsExprs.size(),
03415                                        StartLoc, EndLoc);
03416     
03417     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
03418     // To turn off a warning, type-cast to 'id'
03419     InitExprs.push_back(
03420       // set 'super class', using class_getSuperclass().
03421       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
03422                                CK_BitCast, Cls));
03423     // struct __rw_objc_super
03424     QualType superType = getSuperStructType();
03425     Expr *SuperRep;
03426 
03427     if (LangOpts.MicrosoftExt) {
03428       SynthSuperConstructorFunctionDecl();
03429       // Simulate a constructor call...
03430       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
03431                                                    false, superType, VK_LValue,
03432                                                    SourceLocation());
03433       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
03434                                         superType, VK_LValue, SourceLocation());
03435       // The code for super is a little tricky to prevent collision with
03436       // the structure definition in the header. The rewriter has it's own
03437       // internal definition (__rw_objc_super) that is uses. This is why
03438       // we need the cast below. For example:
03439       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
03440       //
03441       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
03442                                Context->getPointerType(SuperRep->getType()),
03443                                VK_RValue, OK_Ordinary,
03444                                SourceLocation());
03445       SuperRep = NoTypeInfoCStyleCastExpr(Context,
03446                                Context->getPointerType(superType),
03447                                CK_BitCast, SuperRep);
03448     } else {
03449       // (struct __rw_objc_super) { <exprs from above> }
03450       InitListExpr *ILE =
03451         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
03452                                    SourceLocation());
03453       TypeSourceInfo *superTInfo
03454         = Context->getTrivialTypeSourceInfo(superType);
03455       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
03456                                                    superType, VK_RValue, ILE,
03457                                                    false);
03458     }
03459     MsgExprs.push_back(SuperRep);
03460     break;
03461   }
03462 
03463   case ObjCMessageExpr::Instance: {
03464     // Remove all type-casts because it may contain objc-style types; e.g.
03465     // Foo<Proto> *.
03466     Expr *recExpr = Exp->getInstanceReceiver();
03467     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
03468       recExpr = CE->getSubExpr();
03469     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
03470                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
03471                                      ? CK_BlockPointerToObjCPointerCast
03472                                      : CK_CPointerToObjCPointerCast;
03473 
03474     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
03475                                        CK, recExpr);
03476     MsgExprs.push_back(recExpr);
03477     break;
03478   }
03479   }
03480 
03481   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
03482   SmallVector<Expr*, 8> SelExprs;
03483   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
03484   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
03485                                                  &SelExprs[0], SelExprs.size(),
03486                                                   StartLoc,
03487                                                   EndLoc);
03488   MsgExprs.push_back(SelExp);
03489 
03490   // Now push any user supplied arguments.
03491   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
03492     Expr *userExpr = Exp->getArg(i);
03493     // Make all implicit casts explicit...ICE comes in handy:-)
03494     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
03495       // Reuse the ICE type, it is exactly what the doctor ordered.
03496       QualType type = ICE->getType();
03497       if (needToScanForQualifiers(type))
03498         type = Context->getObjCIdType();
03499       // Make sure we convert "type (^)(...)" to "type (*)(...)".
03500       (void)convertBlockPointerToFunctionPointer(type);
03501       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
03502       CastKind CK;
03503       if (SubExpr->getType()->isIntegralType(*Context) && 
03504           type->isBooleanType()) {
03505         CK = CK_IntegralToBoolean;
03506       } else if (type->isObjCObjectPointerType()) {
03507         if (SubExpr->getType()->isBlockPointerType()) {
03508           CK = CK_BlockPointerToObjCPointerCast;
03509         } else if (SubExpr->getType()->isPointerType()) {
03510           CK = CK_CPointerToObjCPointerCast;
03511         } else {
03512           CK = CK_BitCast;
03513         }
03514       } else {
03515         CK = CK_BitCast;
03516       }
03517 
03518       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
03519     }
03520     // Make id<P...> cast into an 'id' cast.
03521     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
03522       if (CE->getType()->isObjCQualifiedIdType()) {
03523         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
03524           userExpr = CE->getSubExpr();
03525         CastKind CK;
03526         if (userExpr->getType()->isIntegralType(*Context)) {
03527           CK = CK_IntegralToPointer;
03528         } else if (userExpr->getType()->isBlockPointerType()) {
03529           CK = CK_BlockPointerToObjCPointerCast;
03530         } else if (userExpr->getType()->isPointerType()) {
03531           CK = CK_CPointerToObjCPointerCast;
03532         } else {
03533           CK = CK_BitCast;
03534         }
03535         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
03536                                             CK, userExpr);
03537       }
03538     }
03539     MsgExprs.push_back(userExpr);
03540     // We've transferred the ownership to MsgExprs. For now, we *don't* null
03541     // out the argument in the original expression (since we aren't deleting
03542     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
03543     //Exp->setArg(i, 0);
03544   }
03545   // Generate the funky cast.
03546   CastExpr *cast;
03547   SmallVector<QualType, 8> ArgTypes;
03548   QualType returnType;
03549 
03550   // Push 'id' and 'SEL', the 2 implicit arguments.
03551   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
03552     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
03553   else
03554     ArgTypes.push_back(Context->getObjCIdType());
03555   ArgTypes.push_back(Context->getObjCSelType());
03556   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
03557     // Push any user argument types.
03558     for (const auto *PI : OMD->params()) {
03559       QualType t = PI->getType()->isObjCQualifiedIdType()
03560                      ? Context->getObjCIdType()
03561                      : PI->getType();
03562       // Make sure we convert "t (^)(...)" to "t (*)(...)".
03563       (void)convertBlockPointerToFunctionPointer(t);
03564       ArgTypes.push_back(t);
03565     }
03566     returnType = Exp->getType();
03567     convertToUnqualifiedObjCType(returnType);
03568     (void)convertBlockPointerToFunctionPointer(returnType);
03569   } else {
03570     returnType = Context->getObjCIdType();
03571   }
03572   // Get the type, we will need to reference it in a couple spots.
03573   QualType msgSendType = MsgSendFlavor->getType();
03574 
03575   // Create a reference to the objc_msgSend() declaration.
03576   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
03577                                                VK_LValue, SourceLocation());
03578 
03579   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
03580   // If we don't do this cast, we get the following bizarre warning/note:
03581   // xx.m:13: warning: function called through a non-compatible type
03582   // xx.m:13: note: if this code is reached, the program will abort
03583   cast = NoTypeInfoCStyleCastExpr(Context,
03584                                   Context->getPointerType(Context->VoidTy),
03585                                   CK_BitCast, DRE);
03586 
03587   // Now do the "normal" pointer to function cast.
03588   // If we don't have a method decl, force a variadic cast.
03589   const ObjCMethodDecl *MD = Exp->getMethodDecl();
03590   QualType castType =
03591     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
03592   castType = Context->getPointerType(castType);
03593   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
03594                                   cast);
03595 
03596   // Don't forget the parens to enforce the proper binding.
03597   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
03598 
03599   const FunctionType *FT = msgSendType->getAs<FunctionType>();
03600   CallExpr *CE = new (Context)
03601       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
03602   Stmt *ReplacingStmt = CE;
03603   if (MsgSendStretFlavor) {
03604     // We have the method which returns a struct/union. Must also generate
03605     // call to objc_msgSend_stret and hang both varieties on a conditional
03606     // expression which dictate which one to envoke depending on size of
03607     // method's return type.
03608 
03609     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
03610                                            returnType,
03611                                            ArgTypes, MsgExprs,
03612                                            Exp->getMethodDecl());
03613     ReplacingStmt = STCE;
03614   }
03615   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03616   return ReplacingStmt;
03617 }
03618 
03619 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
03620   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
03621                                          Exp->getLocEnd());
03622 
03623   // Now do the actual rewrite.
03624   ReplaceStmt(Exp, ReplacingStmt);
03625 
03626   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03627   return ReplacingStmt;
03628 }
03629 
03630 // typedef struct objc_object Protocol;
03631 QualType RewriteModernObjC::getProtocolType() {
03632   if (!ProtocolTypeDecl) {
03633     TypeSourceInfo *TInfo
03634       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
03635     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
03636                                            SourceLocation(), SourceLocation(),
03637                                            &Context->Idents.get("Protocol"),
03638                                            TInfo);
03639   }
03640   return Context->getTypeDeclType(ProtocolTypeDecl);
03641 }
03642 
03643 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
03644 /// a synthesized/forward data reference (to the protocol's metadata).
03645 /// The forward references (and metadata) are generated in
03646 /// RewriteModernObjC::HandleTranslationUnit().
03647 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
03648   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + 
03649                       Exp->getProtocol()->getNameAsString();
03650   IdentifierInfo *ID = &Context->Idents.get(Name);
03651   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
03652                                 SourceLocation(), ID, getProtocolType(),
03653                                 nullptr, SC_Extern);
03654   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
03655                                                VK_LValue, SourceLocation());
03656   CastExpr *castExpr =
03657     NoTypeInfoCStyleCastExpr(
03658       Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
03659   ReplaceStmt(Exp, castExpr);
03660   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
03661   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03662   return castExpr;
03663 
03664 }
03665 
03666 bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
03667                                              const char *endBuf) {
03668   while (startBuf < endBuf) {
03669     if (*startBuf == '#') {
03670       // Skip whitespace.
03671       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
03672         ;
03673       if (!strncmp(startBuf, "if", strlen("if")) ||
03674           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
03675           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
03676           !strncmp(startBuf, "define", strlen("define")) ||
03677           !strncmp(startBuf, "undef", strlen("undef")) ||
03678           !strncmp(startBuf, "else", strlen("else")) ||
03679           !strncmp(startBuf, "elif", strlen("elif")) ||
03680           !strncmp(startBuf, "endif", strlen("endif")) ||
03681           !strncmp(startBuf, "pragma", strlen("pragma")) ||
03682           !strncmp(startBuf, "include", strlen("include")) ||
03683           !strncmp(startBuf, "import", strlen("import")) ||
03684           !strncmp(startBuf, "include_next", strlen("include_next")))
03685         return true;
03686     }
03687     startBuf++;
03688   }
03689   return false;
03690 }
03691 
03692 /// IsTagDefinedInsideClass - This routine checks that a named tagged type 
03693 /// is defined inside an objective-c class. If so, it returns true. 
03694 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, 
03695                                                 TagDecl *Tag,
03696                                                 bool &IsNamedDefinition) {
03697   if (!IDecl)
03698     return false;
03699   SourceLocation TagLocation;
03700   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
03701     RD = RD->getDefinition();
03702     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
03703       return false;
03704     IsNamedDefinition = true;
03705     TagLocation = RD->getLocation();
03706     return Context->getSourceManager().isBeforeInTranslationUnit(
03707                                           IDecl->getLocation(), TagLocation);
03708   }
03709   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
03710     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
03711       return false;
03712     IsNamedDefinition = true;
03713     TagLocation = ED->getLocation();
03714     return Context->getSourceManager().isBeforeInTranslationUnit(
03715                                           IDecl->getLocation(), TagLocation);
03716 
03717   }
03718   return false;
03719 }
03720 
03721 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
03722 /// It handles elaborated types, as well as enum types in the process.
03723 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, 
03724                                                  std::string &Result) {
03725   if (isa<TypedefType>(Type)) {
03726     Result += "\t";
03727     return false;
03728   }
03729     
03730   if (Type->isArrayType()) {
03731     QualType ElemTy = Context->getBaseElementType(Type);
03732     return RewriteObjCFieldDeclType(ElemTy, Result);
03733   }
03734   else if (Type->isRecordType()) {
03735     RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
03736     if (RD->isCompleteDefinition()) {
03737       if (RD->isStruct())
03738         Result += "\n\tstruct ";
03739       else if (RD->isUnion())
03740         Result += "\n\tunion ";
03741       else
03742         assert(false && "class not allowed as an ivar type");
03743       
03744       Result += RD->getName();
03745       if (GlobalDefinedTags.count(RD)) {
03746         // struct/union is defined globally, use it.
03747         Result += " ";
03748         return true;
03749       }
03750       Result += " {\n";
03751       for (auto *FD : RD->fields())
03752         RewriteObjCFieldDecl(FD, Result);
03753       Result += "\t} "; 
03754       return true;
03755     }
03756   }
03757   else if (Type->isEnumeralType()) {
03758     EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
03759     if (ED->isCompleteDefinition()) {
03760       Result += "\n\tenum ";
03761       Result += ED->getName();
03762       if (GlobalDefinedTags.count(ED)) {
03763         // Enum is globall defined, use it.
03764         Result += " ";
03765         return true;
03766       }
03767       
03768       Result += " {\n";
03769       for (const auto *EC : ED->enumerators()) {
03770         Result += "\t"; Result += EC->getName(); Result += " = ";
03771         llvm::APSInt Val = EC->getInitVal();
03772         Result += Val.toString(10);
03773         Result += ",\n";
03774       }
03775       Result += "\t} "; 
03776       return true;
03777     }
03778   }
03779   
03780   Result += "\t";
03781   convertObjCTypeToCStyleType(Type);
03782   return false;
03783 }
03784 
03785 
03786 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
03787 /// It handles elaborated types, as well as enum types in the process.
03788 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, 
03789                                              std::string &Result) {
03790   QualType Type = fieldDecl->getType();
03791   std::string Name = fieldDecl->getNameAsString();
03792   
03793   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); 
03794   if (!EleboratedType)
03795     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
03796   Result += Name;
03797   if (fieldDecl->isBitField()) {
03798     Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
03799   }
03800   else if (EleboratedType && Type->isArrayType()) {
03801     const ArrayType *AT = Context->getAsArrayType(Type);
03802     do {
03803       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
03804         Result += "[";
03805         llvm::APInt Dim = CAT->getSize();
03806         Result += utostr(Dim.getZExtValue());
03807         Result += "]";
03808       }
03809       AT = Context->getAsArrayType(AT->getElementType());
03810     } while (AT);
03811   }
03812   
03813   Result += ";\n";
03814 }
03815 
03816 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
03817 /// named aggregate types into the input buffer.
03818 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 
03819                                              std::string &Result) {
03820   QualType Type = fieldDecl->getType();
03821   if (isa<TypedefType>(Type))
03822     return;
03823   if (Type->isArrayType())
03824     Type = Context->getBaseElementType(Type);
03825   ObjCContainerDecl *IDecl = 
03826     dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
03827 
03828   TagDecl *TD = nullptr;
03829   if (Type->isRecordType()) {
03830     TD = Type->getAs<RecordType>()->getDecl();
03831   }
03832   else if (Type->isEnumeralType()) {
03833     TD = Type->getAs<EnumType>()->getDecl();
03834   }
03835   
03836   if (TD) {
03837     if (GlobalDefinedTags.count(TD))
03838       return;
03839     
03840     bool IsNamedDefinition = false;
03841     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
03842       RewriteObjCFieldDeclType(Type, Result);
03843       Result += ";";
03844     }
03845     if (IsNamedDefinition)
03846       GlobalDefinedTags.insert(TD);
03847   }
03848     
03849 }
03850 
03851 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
03852   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
03853   if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
03854     return IvarGroupNumber[IV];
03855   }
03856   unsigned GroupNo = 0;
03857   SmallVector<const ObjCIvarDecl *, 8> IVars;
03858   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
03859        IVD; IVD = IVD->getNextIvar())
03860     IVars.push_back(IVD);
03861   
03862   for (unsigned i = 0, e = IVars.size(); i < e; i++)
03863     if (IVars[i]->isBitField()) {
03864       IvarGroupNumber[IVars[i++]] = ++GroupNo;
03865       while (i < e && IVars[i]->isBitField())
03866         IvarGroupNumber[IVars[i++]] = GroupNo;
03867       if (i < e)
03868         --i;
03869     }
03870 
03871   ObjCInterefaceHasBitfieldGroups.insert(CDecl);
03872   return IvarGroupNumber[IV];
03873 }
03874 
03875 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
03876                               ObjCIvarDecl *IV,
03877                               SmallVectorImpl<ObjCIvarDecl *> &IVars) {
03878   std::string StructTagName;
03879   ObjCIvarBitfieldGroupType(IV, StructTagName);
03880   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
03881                                       Context->getTranslationUnitDecl(),
03882                                       SourceLocation(), SourceLocation(),
03883                                       &Context->Idents.get(StructTagName));
03884   for (unsigned i=0, e = IVars.size(); i < e; i++) {
03885     ObjCIvarDecl *Ivar = IVars[i];
03886     RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
03887                                   &Context->Idents.get(Ivar->getName()),
03888                                   Ivar->getType(),
03889                                   nullptr, /*Expr *BW */Ivar->getBitWidth(),
03890                                   false, ICIS_NoInit));
03891   }
03892   RD->completeDefinition();
03893   return Context->getTagDeclType(RD);
03894 }
03895 
03896 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
03897   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
03898   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
03899   std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
03900   if (GroupRecordType.count(tuple))
03901     return GroupRecordType[tuple];
03902   
03903   SmallVector<ObjCIvarDecl *, 8> IVars;
03904   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
03905        IVD; IVD = IVD->getNextIvar()) {
03906     if (IVD->isBitField())
03907       IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
03908     else {
03909       if (!IVars.empty()) {
03910         unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
03911         // Generate the struct type for this group of bitfield ivars.
03912         GroupRecordType[std::make_pair(CDecl, GroupNo)] =
03913           SynthesizeBitfieldGroupStructType(IVars[0], IVars);
03914         IVars.clear();
03915       }
03916     }
03917   }
03918   if (!IVars.empty()) {
03919     // Do the last one.
03920     unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
03921     GroupRecordType[std::make_pair(CDecl, GroupNo)] =
03922       SynthesizeBitfieldGroupStructType(IVars[0], IVars);
03923   }
03924   QualType RetQT = GroupRecordType[tuple];
03925   assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
03926   
03927   return RetQT;
03928 }
03929 
03930 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
03931 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
03932 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
03933                                                   std::string &Result) {
03934   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
03935   Result += CDecl->getName();
03936   Result += "__GRBF_";
03937   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
03938   Result += utostr(GroupNo);
03939   return;
03940 }
03941 
03942 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
03943 /// Name of the struct would be: classname__T_n where n is the group number for
03944 /// this ivar.
03945 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
03946                                                   std::string &Result) {
03947   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
03948   Result += CDecl->getName();
03949   Result += "__T_";
03950   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
03951   Result += utostr(GroupNo);
03952   return;
03953 }
03954 
03955 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
03956 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
03957 /// this ivar.
03958 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
03959                                                     std::string &Result) {
03960   Result += "OBJC_IVAR_$_";
03961   ObjCIvarBitfieldGroupDecl(IV, Result);
03962 }
03963 
03964 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
03965       while ((IX < ENDIX) && VEC[IX]->isBitField()) \
03966         ++IX; \
03967       if (IX < ENDIX) \
03968         --IX; \
03969 }
03970 
03971 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
03972 /// an objective-c class with ivars.
03973 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
03974                                                std::string &Result) {
03975   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
03976   assert(CDecl->getName() != "" &&
03977          "Name missing in SynthesizeObjCInternalStruct");
03978   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
03979   SmallVector<ObjCIvarDecl *, 8> IVars;
03980   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
03981        IVD; IVD = IVD->getNextIvar())
03982     IVars.push_back(IVD);
03983   
03984   SourceLocation LocStart = CDecl->getLocStart();
03985   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
03986   
03987   const char *startBuf = SM->getCharacterData(LocStart);
03988   const char *endBuf = SM->getCharacterData(LocEnd);
03989   
03990   // If no ivars and no root or if its root, directly or indirectly,
03991   // have no ivars (thus not synthesized) then no need to synthesize this class.
03992   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
03993       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
03994     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
03995     ReplaceText(LocStart, endBuf-startBuf, Result);
03996     return;
03997   }
03998   
03999   // Insert named struct/union definitions inside class to
04000   // outer scope. This follows semantics of locally defined
04001   // struct/unions in objective-c classes.
04002   for (unsigned i = 0, e = IVars.size(); i < e; i++)
04003     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
04004   
04005   // Insert named structs which are syntheized to group ivar bitfields
04006   // to outer scope as well.
04007   for (unsigned i = 0, e = IVars.size(); i < e; i++)
04008     if (IVars[i]->isBitField()) {
04009       ObjCIvarDecl *IV = IVars[i];
04010       QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
04011       RewriteObjCFieldDeclType(QT, Result);
04012       Result += ";";
04013       // skip over ivar bitfields in this group.
04014       SKIP_BITFIELDS(i , e, IVars);
04015     }
04016     
04017   Result += "\nstruct ";
04018   Result += CDecl->getNameAsString();
04019   Result += "_IMPL {\n";
04020   
04021   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
04022     Result += "\tstruct "; Result += RCDecl->getNameAsString();
04023     Result += "_IMPL "; Result += RCDecl->getNameAsString();
04024     Result += "_IVARS;\n";
04025   }
04026   
04027   for (unsigned i = 0, e = IVars.size(); i < e; i++) {
04028     if (IVars[i]->isBitField()) {
04029       ObjCIvarDecl *IV = IVars[i];
04030       Result += "\tstruct ";
04031       ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
04032       ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
04033       // skip over ivar bitfields in this group.
04034       SKIP_BITFIELDS(i , e, IVars);
04035     }
04036     else
04037       RewriteObjCFieldDecl(IVars[i], Result);
04038   }
04039 
04040   Result += "};\n";
04041   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
04042   ReplaceText(LocStart, endBuf-startBuf, Result);
04043   // Mark this struct as having been generated.
04044   if (!ObjCSynthesizedStructs.insert(CDecl))
04045     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
04046 }
04047 
04048 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
04049 /// have been referenced in an ivar access expression.
04050 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
04051                                                   std::string &Result) {
04052   // write out ivar offset symbols which have been referenced in an ivar
04053   // access expression.
04054   llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
04055   if (Ivars.empty())
04056     return;
04057   
04058   llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
04059   for (ObjCIvarDecl *IvarDecl : Ivars) {
04060     const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
04061     unsigned GroupNo = 0;
04062     if (IvarDecl->isBitField()) {
04063       GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
04064       if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
04065         continue;
04066     }
04067     Result += "\n";
04068     if (LangOpts.MicrosoftExt)
04069       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
04070     Result += "extern \"C\" ";
04071     if (LangOpts.MicrosoftExt && 
04072         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
04073         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
04074         Result += "__declspec(dllimport) ";
04075 
04076     Result += "unsigned long ";
04077     if (IvarDecl->isBitField()) {
04078       ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
04079       GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
04080     }
04081     else
04082       WriteInternalIvarName(CDecl, IvarDecl, Result);
04083     Result += ";";
04084   }
04085 }
04086 
04087 //===----------------------------------------------------------------------===//
04088 // Meta Data Emission
04089 //===----------------------------------------------------------------------===//
04090 
04091 
04092 /// RewriteImplementations - This routine rewrites all method implementations
04093 /// and emits meta-data.
04094 
04095 void RewriteModernObjC::RewriteImplementations() {
04096   int ClsDefCount = ClassImplementation.size();
04097   int CatDefCount = CategoryImplementation.size();
04098 
04099   // Rewrite implemented methods
04100   for (int i = 0; i < ClsDefCount; i++) {
04101     ObjCImplementationDecl *OIMP = ClassImplementation[i];
04102     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
04103     if (CDecl->isImplicitInterfaceDecl())
04104       assert(false &&
04105              "Legacy implicit interface rewriting not supported in moder abi");
04106     RewriteImplementationDecl(OIMP);
04107   }
04108 
04109   for (int i = 0; i < CatDefCount; i++) {
04110     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
04111     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
04112     if (CDecl->isImplicitInterfaceDecl())
04113       assert(false &&
04114              "Legacy implicit interface rewriting not supported in moder abi");
04115     RewriteImplementationDecl(CIMP);
04116   }
04117 }
04118 
04119 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, 
04120                                      const std::string &Name,
04121                                      ValueDecl *VD, bool def) {
04122   assert(BlockByRefDeclNo.count(VD) && 
04123          "RewriteByRefString: ByRef decl missing");
04124   if (def)
04125     ResultStr += "struct ";
04126   ResultStr += "__Block_byref_" + Name + 
04127     "_" + utostr(BlockByRefDeclNo[VD]) ;
04128 }
04129 
04130 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
04131   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
04132     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
04133   return false;
04134 }
04135 
04136 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
04137                                                    StringRef funcName,
04138                                                    std::string Tag) {
04139   const FunctionType *AFT = CE->getFunctionType();
04140   QualType RT = AFT->getReturnType();
04141   std::string StructRef = "struct " + Tag;
04142   SourceLocation BlockLoc = CE->getExprLoc();
04143   std::string S;
04144   ConvertSourceLocationToLineDirective(BlockLoc, S);
04145   
04146   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
04147          funcName.str() + "_block_func_" + utostr(i);
04148 
04149   BlockDecl *BD = CE->getBlockDecl();
04150 
04151   if (isa<FunctionNoProtoType>(AFT)) {
04152     // No user-supplied arguments. Still need to pass in a pointer to the
04153     // block (to reference imported block decl refs).
04154     S += "(" + StructRef + " *__cself)";
04155   } else if (BD->param_empty()) {
04156     S += "(" + StructRef + " *__cself)";
04157   } else {
04158     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
04159     assert(FT && "SynthesizeBlockFunc: No function proto");
04160     S += '(';
04161     // first add the implicit argument.
04162     S += StructRef + " *__cself, ";
04163     std::string ParamStr;
04164     for (BlockDecl::param_iterator AI = BD->param_begin(),
04165          E = BD->param_end(); AI != E; ++AI) {
04166       if (AI != BD->param_begin()) S += ", ";
04167       ParamStr = (*AI)->getNameAsString();
04168       QualType QT = (*AI)->getType();
04169       (void)convertBlockPointerToFunctionPointer(QT);
04170       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
04171       S += ParamStr;
04172     }
04173     if (FT->isVariadic()) {
04174       if (!BD->param_empty()) S += ", ";
04175       S += "...";
04176     }
04177     S += ')';
04178   }
04179   S += " {\n";
04180 
04181   // Create local declarations to avoid rewriting all closure decl ref exprs.
04182   // First, emit a declaration for all "by ref" decls.
04183   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
04184        E = BlockByRefDecls.end(); I != E; ++I) {
04185     S += "  ";
04186     std::string Name = (*I)->getNameAsString();
04187     std::string TypeString;
04188     RewriteByRefString(TypeString, Name, (*I));
04189     TypeString += " *";
04190     Name = TypeString + Name;
04191     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
04192   }
04193   // Next, emit a declaration for all "by copy" declarations.
04194   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
04195        E = BlockByCopyDecls.end(); I != E; ++I) {
04196     S += "  ";
04197     // Handle nested closure invocation. For example:
04198     //
04199     //   void (^myImportedClosure)(void);
04200     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
04201     //
04202     //   void (^anotherClosure)(void);
04203     //   anotherClosure = ^(void) {
04204     //     myImportedClosure(); // import and invoke the closure
04205     //   };
04206     //
04207     if (isTopLevelBlockPointerType((*I)->getType())) {
04208       RewriteBlockPointerTypeVariable(S, (*I));
04209       S += " = (";
04210       RewriteBlockPointerType(S, (*I)->getType());
04211       S += ")";
04212       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
04213     }
04214     else {
04215       std::string Name = (*I)->getNameAsString();
04216       QualType QT = (*I)->getType();
04217       if (HasLocalVariableExternalStorage(*I))
04218         QT = Context->getPointerType(QT);
04219       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
04220       S += Name + " = __cself->" + 
04221                               (*I)->getNameAsString() + "; // bound by copy\n";
04222     }
04223   }
04224   std::string RewrittenStr = RewrittenBlockExprs[CE];
04225   const char *cstr = RewrittenStr.c_str();
04226   while (*cstr++ != '{') ;
04227   S += cstr;
04228   S += "\n";
04229   return S;
04230 }
04231 
04232 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
04233                                                    StringRef funcName,
04234                                                    std::string Tag) {
04235   std::string StructRef = "struct " + Tag;
04236   std::string S = "static void __";
04237 
04238   S += funcName;
04239   S += "_block_copy_" + utostr(i);
04240   S += "(" + StructRef;
04241   S += "*dst, " + StructRef;
04242   S += "*src) {";
04243   for (ValueDecl *VD : ImportedBlockDecls) {
04244     S += "_Block_object_assign((void*)&dst->";
04245     S += VD->getNameAsString();
04246     S += ", (void*)src->";
04247     S += VD->getNameAsString();
04248     if (BlockByRefDeclsPtrSet.count(VD))
04249       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
04250     else if (VD->getType()->isBlockPointerType())
04251       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
04252     else
04253       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
04254   }
04255   S += "}\n";
04256   
04257   S += "\nstatic void __";
04258   S += funcName;
04259   S += "_block_dispose_" + utostr(i);
04260   S += "(" + StructRef;
04261   S += "*src) {";
04262   for (ValueDecl *VD : ImportedBlockDecls) {
04263     S += "_Block_object_dispose((void*)src->";
04264     S += VD->getNameAsString();
04265     if (BlockByRefDeclsPtrSet.count(VD))
04266       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
04267     else if (VD->getType()->isBlockPointerType())
04268       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
04269     else
04270       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
04271   }
04272   S += "}\n";
04273   return S;
04274 }
04275 
04276 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, 
04277                                              std::string Desc) {
04278   std::string S = "\nstruct " + Tag;
04279   std::string Constructor = "  " + Tag;
04280 
04281   S += " {\n  struct __block_impl impl;\n";
04282   S += "  struct " + Desc;
04283   S += "* Desc;\n";
04284 
04285   Constructor += "(void *fp, "; // Invoke function pointer.
04286   Constructor += "struct " + Desc; // Descriptor pointer.
04287   Constructor += " *desc";
04288 
04289   if (BlockDeclRefs.size()) {
04290     // Output all "by copy" declarations.
04291     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
04292          E = BlockByCopyDecls.end(); I != E; ++I) {
04293       S += "  ";
04294       std::string FieldName = (*I)->getNameAsString();
04295       std::string ArgName = "_" + FieldName;
04296       // Handle nested closure invocation. For example:
04297       //
04298       //   void (^myImportedBlock)(void);
04299       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
04300       //
04301       //   void (^anotherBlock)(void);
04302       //   anotherBlock = ^(void) {
04303       //     myImportedBlock(); // import and invoke the closure
04304       //   };
04305       //
04306       if (isTopLevelBlockPointerType((*I)->getType())) {
04307         S += "struct __block_impl *";
04308         Constructor += ", void *" + ArgName;
04309       } else {
04310         QualType QT = (*I)->getType();
04311         if (HasLocalVariableExternalStorage(*I))
04312           QT = Context->getPointerType(QT);
04313         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
04314         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
04315         Constructor += ", " + ArgName;
04316       }
04317       S += FieldName + ";\n";
04318     }
04319     // Output all "by ref" declarations.
04320     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
04321          E = BlockByRefDecls.end(); I != E; ++I) {
04322       S += "  ";
04323       std::string FieldName = (*I)->getNameAsString();
04324       std::string ArgName = "_" + FieldName;
04325       {
04326         std::string TypeString;
04327         RewriteByRefString(TypeString, FieldName, (*I));
04328         TypeString += " *";
04329         FieldName = TypeString + FieldName;
04330         ArgName = TypeString + ArgName;
04331         Constructor += ", " + ArgName;
04332       }
04333       S += FieldName + "; // by ref\n";
04334     }
04335     // Finish writing the constructor.
04336     Constructor += ", int flags=0)";
04337     // Initialize all "by copy" arguments.
04338     bool firsTime = true;
04339     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
04340          E = BlockByCopyDecls.end(); I != E; ++I) {
04341       std::string Name = (*I)->getNameAsString();
04342         if (firsTime) {
04343           Constructor += " : ";
04344           firsTime = false;
04345         }
04346         else
04347           Constructor += ", ";
04348         if (isTopLevelBlockPointerType((*I)->getType()))
04349           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
04350         else
04351           Constructor += Name + "(_" + Name + ")";
04352     }
04353     // Initialize all "by ref" arguments.
04354     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
04355          E = BlockByRefDecls.end(); I != E; ++I) {
04356       std::string Name = (*I)->getNameAsString();
04357       if (firsTime) {
04358         Constructor += " : ";
04359         firsTime = false;
04360       }
04361       else
04362         Constructor += ", ";
04363       Constructor += Name + "(_" + Name + "->__forwarding)";
04364     }
04365     
04366     Constructor += " {\n";
04367     if (GlobalVarDecl)
04368       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
04369     else
04370       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
04371     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
04372 
04373     Constructor += "    Desc = desc;\n";
04374   } else {
04375     // Finish writing the constructor.
04376     Constructor += ", int flags=0) {\n";
04377     if (GlobalVarDecl)
04378       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
04379     else
04380       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
04381     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
04382     Constructor += "    Desc = desc;\n";
04383   }
04384   Constructor += "  ";
04385   Constructor += "}\n";
04386   S += Constructor;
04387   S += "};\n";
04388   return S;
04389 }
04390 
04391 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, 
04392                                                    std::string ImplTag, int i,
04393                                                    StringRef FunName,
04394                                                    unsigned hasCopy) {
04395   std::string S = "\nstatic struct " + DescTag;
04396   
04397   S += " {\n  size_t reserved;\n";
04398   S += "  size_t Block_size;\n";
04399   if (hasCopy) {
04400     S += "  void (*copy)(struct ";
04401     S += ImplTag; S += "*, struct ";
04402     S += ImplTag; S += "*);\n";
04403     
04404     S += "  void (*dispose)(struct ";
04405     S += ImplTag; S += "*);\n";
04406   }
04407   S += "} ";
04408 
04409   S += DescTag + "_DATA = { 0, sizeof(struct ";
04410   S += ImplTag + ")";
04411   if (hasCopy) {
04412     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
04413     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
04414   }
04415   S += "};\n";
04416   return S;
04417 }
04418 
04419 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
04420                                           StringRef FunName) {
04421   bool RewriteSC = (GlobalVarDecl &&
04422                     !Blocks.empty() &&
04423                     GlobalVarDecl->getStorageClass() == SC_Static &&
04424                     GlobalVarDecl->getType().getCVRQualifiers());
04425   if (RewriteSC) {
04426     std::string SC(" void __");
04427     SC += GlobalVarDecl->getNameAsString();
04428     SC += "() {}";
04429     InsertText(FunLocStart, SC);
04430   }
04431   
04432   // Insert closures that were part of the function.
04433   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
04434     CollectBlockDeclRefInfo(Blocks[i]);
04435     // Need to copy-in the inner copied-in variables not actually used in this
04436     // block.
04437     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
04438       DeclRefExpr *Exp = InnerDeclRefs[count++];
04439       ValueDecl *VD = Exp->getDecl();
04440       BlockDeclRefs.push_back(Exp);
04441       if (!VD->hasAttr<BlocksAttr>()) {
04442         if (!BlockByCopyDeclsPtrSet.count(VD)) {
04443           BlockByCopyDeclsPtrSet.insert(VD);
04444           BlockByCopyDecls.push_back(VD);
04445         }
04446         continue;
04447       }
04448 
04449       if (!BlockByRefDeclsPtrSet.count(VD)) {
04450         BlockByRefDeclsPtrSet.insert(VD);
04451         BlockByRefDecls.push_back(VD);
04452       }
04453 
04454       // imported objects in the inner blocks not used in the outer
04455       // blocks must be copied/disposed in the outer block as well.
04456       if (VD->getType()->isObjCObjectPointerType() || 
04457           VD->getType()->isBlockPointerType())
04458         ImportedBlockDecls.insert(VD);
04459     }
04460 
04461     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
04462     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
04463 
04464     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
04465 
04466     InsertText(FunLocStart, CI);
04467 
04468     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
04469 
04470     InsertText(FunLocStart, CF);
04471 
04472     if (ImportedBlockDecls.size()) {
04473       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
04474       InsertText(FunLocStart, HF);
04475     }
04476     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
04477                                                ImportedBlockDecls.size() > 0);
04478     InsertText(FunLocStart, BD);
04479 
04480     BlockDeclRefs.clear();
04481     BlockByRefDecls.clear();
04482     BlockByRefDeclsPtrSet.clear();
04483     BlockByCopyDecls.clear();
04484     BlockByCopyDeclsPtrSet.clear();
04485     ImportedBlockDecls.clear();
04486   }
04487   if (RewriteSC) {
04488     // Must insert any 'const/volatile/static here. Since it has been
04489     // removed as result of rewriting of block literals.
04490     std::string SC;
04491     if (GlobalVarDecl->getStorageClass() == SC_Static)
04492       SC = "static ";
04493     if (GlobalVarDecl->getType().isConstQualified())
04494       SC += "const ";
04495     if (GlobalVarDecl->getType().isVolatileQualified())
04496       SC += "volatile ";
04497     if (GlobalVarDecl->getType().isRestrictQualified())
04498       SC += "restrict ";
04499     InsertText(FunLocStart, SC);
04500   }
04501   if (GlobalConstructionExp) {
04502     // extra fancy dance for global literal expression.
04503     
04504     // Always the latest block expression on the block stack.
04505     std::string Tag = "__";
04506     Tag += FunName;
04507     Tag += "_block_impl_";
04508     Tag += utostr(Blocks.size()-1);
04509     std::string globalBuf = "static ";
04510     globalBuf += Tag; globalBuf += " ";
04511     std::string SStr;
04512   
04513     llvm::raw_string_ostream constructorExprBuf(SStr);
04514     GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
04515                                        PrintingPolicy(LangOpts));
04516     globalBuf += constructorExprBuf.str();
04517     globalBuf += ";\n";
04518     InsertText(FunLocStart, globalBuf);
04519     GlobalConstructionExp = nullptr;
04520   }
04521 
04522   Blocks.clear();
04523   InnerDeclRefsCount.clear();
04524   InnerDeclRefs.clear();
04525   RewrittenBlockExprs.clear();
04526 }
04527 
04528 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
04529   SourceLocation FunLocStart = 
04530     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
04531                       : FD->getTypeSpecStartLoc();
04532   StringRef FuncName = FD->getName();
04533 
04534   SynthesizeBlockLiterals(FunLocStart, FuncName);
04535 }
04536 
04537 static void BuildUniqueMethodName(std::string &Name,
04538                                   ObjCMethodDecl *MD) {
04539   ObjCInterfaceDecl *IFace = MD->getClassInterface();
04540   Name = IFace->getName();
04541   Name += "__" + MD->getSelector().getAsString();
04542   // Convert colons to underscores.
04543   std::string::size_type loc = 0;
04544   while ((loc = Name.find(":", loc)) != std::string::npos)
04545     Name.replace(loc, 1, "_");
04546 }
04547 
04548 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
04549   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
04550   //SourceLocation FunLocStart = MD->getLocStart();
04551   SourceLocation FunLocStart = MD->getLocStart();
04552   std::string FuncName;
04553   BuildUniqueMethodName(FuncName, MD);
04554   SynthesizeBlockLiterals(FunLocStart, FuncName);
04555 }
04556 
04557 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
04558   for (Stmt::child_range CI = S->children(); CI; ++CI)
04559     if (*CI) {
04560       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
04561         GetBlockDeclRefExprs(CBE->getBody());
04562       else
04563         GetBlockDeclRefExprs(*CI);
04564     }
04565   // Handle specific things.
04566   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
04567     if (DRE->refersToEnclosingLocal()) {
04568       // FIXME: Handle enums.
04569       if (!isa<FunctionDecl>(DRE->getDecl()))
04570         BlockDeclRefs.push_back(DRE);
04571       if (HasLocalVariableExternalStorage(DRE->getDecl()))
04572         BlockDeclRefs.push_back(DRE);
04573     }
04574   }
04575   
04576   return;
04577 }
04578 
04579 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
04580                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
04581                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
04582   for (Stmt::child_range CI = S->children(); CI; ++CI)
04583     if (*CI) {
04584       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
04585         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
04586         GetInnerBlockDeclRefExprs(CBE->getBody(),
04587                                   InnerBlockDeclRefs,
04588                                   InnerContexts);
04589       }
04590       else
04591         GetInnerBlockDeclRefExprs(*CI,
04592                                   InnerBlockDeclRefs,
04593                                   InnerContexts);
04594 
04595     }
04596   // Handle specific things.
04597   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
04598     if (DRE->refersToEnclosingLocal()) {
04599       if (!isa<FunctionDecl>(DRE->getDecl()) &&
04600           !InnerContexts.count(DRE->getDecl()->getDeclContext()))
04601         InnerBlockDeclRefs.push_back(DRE);
04602       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
04603         if (Var->isFunctionOrMethodVarDecl())
04604           ImportedLocalExternalDecls.insert(Var);
04605     }
04606   }
04607   
04608   return;
04609 }
04610 
04611 /// convertObjCTypeToCStyleType - This routine converts such objc types
04612 /// as qualified objects, and blocks to their closest c/c++ types that
04613 /// it can. It returns true if input type was modified.
04614 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
04615   QualType oldT = T;
04616   convertBlockPointerToFunctionPointer(T);
04617   if (T->isFunctionPointerType()) {
04618     QualType PointeeTy;
04619     if (const PointerType* PT = T->getAs<PointerType>()) {
04620       PointeeTy = PT->getPointeeType();
04621       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
04622         T = convertFunctionTypeOfBlocks(FT);
04623         T = Context->getPointerType(T);
04624       }
04625     }
04626   }
04627   
04628   convertToUnqualifiedObjCType(T);
04629   return T != oldT;
04630 }
04631 
04632 /// convertFunctionTypeOfBlocks - This routine converts a function type
04633 /// whose result type may be a block pointer or whose argument type(s)
04634 /// might be block pointers to an equivalent function type replacing
04635 /// all block pointers to function pointers.
04636 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
04637   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
04638   // FTP will be null for closures that don't take arguments.
04639   // Generate a funky cast.
04640   SmallVector<QualType, 8> ArgTypes;
04641   QualType Res = FT->getReturnType();
04642   bool modified = convertObjCTypeToCStyleType(Res);
04643   
04644   if (FTP) {
04645     for (auto &I : FTP->param_types()) {
04646       QualType t = I;
04647       // Make sure we convert "t (^)(...)" to "t (*)(...)".
04648       if (convertObjCTypeToCStyleType(t))
04649         modified = true;
04650       ArgTypes.push_back(t);
04651     }
04652   }
04653   QualType FuncType;
04654   if (modified)
04655     FuncType = getSimpleFunctionType(Res, ArgTypes);
04656   else FuncType = QualType(FT, 0);
04657   return FuncType;
04658 }
04659 
04660 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
04661   // Navigate to relevant type information.
04662   const BlockPointerType *CPT = nullptr;
04663 
04664   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
04665     CPT = DRE->getType()->getAs<BlockPointerType>();
04666   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
04667     CPT = MExpr->getType()->getAs<BlockPointerType>();
04668   } 
04669   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
04670     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
04671   }
04672   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) 
04673     CPT = IEXPR->getType()->getAs<BlockPointerType>();
04674   else if (const ConditionalOperator *CEXPR = 
04675             dyn_cast<ConditionalOperator>(BlockExp)) {
04676     Expr *LHSExp = CEXPR->getLHS();
04677     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
04678     Expr *RHSExp = CEXPR->getRHS();
04679     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
04680     Expr *CONDExp = CEXPR->getCond();
04681     ConditionalOperator *CondExpr =
04682       new (Context) ConditionalOperator(CONDExp,
04683                                       SourceLocation(), cast<Expr>(LHSStmt),
04684                                       SourceLocation(), cast<Expr>(RHSStmt),
04685                                       Exp->getType(), VK_RValue, OK_Ordinary);
04686     return CondExpr;
04687   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
04688     CPT = IRE->getType()->getAs<BlockPointerType>();
04689   } else if (const PseudoObjectExpr *POE
04690                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
04691     CPT = POE->getType()->castAs<BlockPointerType>();
04692   } else {
04693     assert(1 && "RewriteBlockClass: Bad type");
04694   }
04695   assert(CPT && "RewriteBlockClass: Bad type");
04696   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
04697   assert(FT && "RewriteBlockClass: Bad type");
04698   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
04699   // FTP will be null for closures that don't take arguments.
04700 
04701   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
04702                                       SourceLocation(), SourceLocation(),
04703                                       &Context->Idents.get("__block_impl"));
04704   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
04705 
04706   // Generate a funky cast.
04707   SmallVector<QualType, 8> ArgTypes;
04708 
04709   // Push the block argument type.
04710   ArgTypes.push_back(PtrBlock);
04711   if (FTP) {
04712     for (auto &I : FTP->param_types()) {
04713       QualType t = I;
04714       // Make sure we convert "t (^)(...)" to "t (*)(...)".
04715       if (!convertBlockPointerToFunctionPointer(t))
04716         convertToUnqualifiedObjCType(t);
04717       ArgTypes.push_back(t);
04718     }
04719   }
04720   // Now do the pointer to function cast.
04721   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
04722 
04723   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
04724 
04725   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
04726                                                CK_BitCast,
04727                                                const_cast<Expr*>(BlockExp));
04728   // Don't forget the parens to enforce the proper binding.
04729   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
04730                                           BlkCast);
04731   //PE->dump();
04732 
04733   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
04734                                     SourceLocation(),
04735                                     &Context->Idents.get("FuncPtr"),
04736                                     Context->VoidPtrTy, nullptr,
04737                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
04738                                     ICIS_NoInit);
04739   MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
04740                                             FD->getType(), VK_LValue,
04741                                             OK_Ordinary);
04742 
04743   
04744   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
04745                                                 CK_BitCast, ME);
04746   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
04747 
04748   SmallVector<Expr*, 8> BlkExprs;
04749   // Add the implicit argument.
04750   BlkExprs.push_back(BlkCast);
04751   // Add the user arguments.
04752   for (CallExpr::arg_iterator I = Exp->arg_begin(),
04753        E = Exp->arg_end(); I != E; ++I) {
04754     BlkExprs.push_back(*I);
04755   }
04756   CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
04757                                         Exp->getType(), VK_RValue,
04758                                         SourceLocation());
04759   return CE;
04760 }
04761 
04762 // We need to return the rewritten expression to handle cases where the
04763 // DeclRefExpr is embedded in another expression being rewritten.
04764 // For example:
04765 //
04766 // int main() {
04767 //    __block Foo *f;
04768 //    __block int i;
04769 //
04770 //    void (^myblock)() = ^() {
04771 //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
04772 //        i = 77;
04773 //    };
04774 //}
04775 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
04776   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
04777   // for each DeclRefExp where BYREFVAR is name of the variable.
04778   ValueDecl *VD = DeclRefExp->getDecl();
04779   bool isArrow = DeclRefExp->refersToEnclosingLocal();
04780 
04781   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
04782                                     SourceLocation(),
04783                                     &Context->Idents.get("__forwarding"), 
04784                                     Context->VoidPtrTy, nullptr,
04785                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
04786                                     ICIS_NoInit);
04787   MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
04788                                             FD, SourceLocation(),
04789                                             FD->getType(), VK_LValue,
04790                                             OK_Ordinary);
04791 
04792   StringRef Name = VD->getName();
04793   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
04794                          &Context->Idents.get(Name), 
04795                          Context->VoidPtrTy, nullptr,
04796                          /*BitWidth=*/nullptr, /*Mutable=*/true,
04797                          ICIS_NoInit);
04798   ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
04799                                 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
04800   
04801   
04802   
04803   // Need parens to enforce precedence.
04804   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), 
04805                                           DeclRefExp->getExprLoc(), 
04806                                           ME);
04807   ReplaceStmt(DeclRefExp, PE);
04808   return PE;
04809 }
04810 
04811 // Rewrites the imported local variable V with external storage 
04812 // (static, extern, etc.) as *V
04813 //
04814 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
04815   ValueDecl *VD = DRE->getDecl();
04816   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
04817     if (!ImportedLocalExternalDecls.count(Var))
04818       return DRE;
04819   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
04820                                           VK_LValue, OK_Ordinary,
04821                                           DRE->getLocation());
04822   // Need parens to enforce precedence.
04823   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
04824                                           Exp);
04825   ReplaceStmt(DRE, PE);
04826   return PE;
04827 }
04828 
04829 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
04830   SourceLocation LocStart = CE->getLParenLoc();
04831   SourceLocation LocEnd = CE->getRParenLoc();
04832 
04833   // Need to avoid trying to rewrite synthesized casts.
04834   if (LocStart.isInvalid())
04835     return;
04836   // Need to avoid trying to rewrite casts contained in macros.
04837   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
04838     return;
04839 
04840   const char *startBuf = SM->getCharacterData(LocStart);
04841   const char *endBuf = SM->getCharacterData(LocEnd);
04842   QualType QT = CE->getType();
04843   const Type* TypePtr = QT->getAs<Type>();
04844   if (isa<TypeOfExprType>(TypePtr)) {
04845     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
04846     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
04847     std::string TypeAsString = "(";
04848     RewriteBlockPointerType(TypeAsString, QT);
04849     TypeAsString += ")";
04850     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
04851     return;
04852   }
04853   // advance the location to startArgList.
04854   const char *argPtr = startBuf;
04855 
04856   while (*argPtr++ && (argPtr < endBuf)) {
04857     switch (*argPtr) {
04858     case '^':
04859       // Replace the '^' with '*'.
04860       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
04861       ReplaceText(LocStart, 1, "*");
04862       break;
04863     }
04864   }
04865   return;
04866 }
04867 
04868 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
04869   CastKind CastKind = IC->getCastKind();
04870   if (CastKind != CK_BlockPointerToObjCPointerCast &&
04871       CastKind != CK_AnyPointerToBlockPointerCast)
04872     return;
04873   
04874   QualType QT = IC->getType();
04875   (void)convertBlockPointerToFunctionPointer(QT);
04876   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
04877   std::string Str = "(";
04878   Str += TypeString;
04879   Str += ")";
04880   InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
04881 
04882   return;
04883 }
04884 
04885 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
04886   SourceLocation DeclLoc = FD->getLocation();
04887   unsigned parenCount = 0;
04888 
04889   // We have 1 or more arguments that have closure pointers.
04890   const char *startBuf = SM->getCharacterData(DeclLoc);
04891   const char *startArgList = strchr(startBuf, '(');
04892 
04893   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
04894 
04895   parenCount++;
04896   // advance the location to startArgList.
04897   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
04898   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
04899 
04900   const char *argPtr = startArgList;
04901 
04902   while (*argPtr++ && parenCount) {
04903     switch (*argPtr) {
04904     case '^':
04905       // Replace the '^' with '*'.
04906       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
04907       ReplaceText(DeclLoc, 1, "*");
04908       break;
04909     case '(':
04910       parenCount++;
04911       break;
04912     case ')':
04913       parenCount--;
04914       break;
04915     }
04916   }
04917   return;
04918 }
04919 
04920 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
04921   const FunctionProtoType *FTP;
04922   const PointerType *PT = QT->getAs<PointerType>();
04923   if (PT) {
04924     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
04925   } else {
04926     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
04927     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
04928     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
04929   }
04930   if (FTP) {
04931     for (const auto &I : FTP->param_types())
04932       if (isTopLevelBlockPointerType(I))
04933         return true;
04934   }
04935   return false;
04936 }
04937 
04938 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
04939   const FunctionProtoType *FTP;
04940   const PointerType *PT = QT->getAs<PointerType>();
04941   if (PT) {
04942     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
04943   } else {
04944     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
04945     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
04946     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
04947   }
04948   if (FTP) {
04949     for (const auto &I : FTP->param_types()) {
04950       if (I->isObjCQualifiedIdType())
04951         return true;
04952       if (I->isObjCObjectPointerType() &&
04953           I->getPointeeType()->isObjCQualifiedInterfaceType())
04954         return true;
04955     }
04956         
04957   }
04958   return false;
04959 }
04960 
04961 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
04962                                      const char *&RParen) {
04963   const char *argPtr = strchr(Name, '(');
04964   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
04965 
04966   LParen = argPtr; // output the start.
04967   argPtr++; // skip past the left paren.
04968   unsigned parenCount = 1;
04969 
04970   while (*argPtr && parenCount) {
04971     switch (*argPtr) {
04972     case '(': parenCount++; break;
04973     case ')': parenCount--; break;
04974     default: break;
04975     }
04976     if (parenCount) argPtr++;
04977   }
04978   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
04979   RParen = argPtr; // output the end
04980 }
04981 
04982 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
04983   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
04984     RewriteBlockPointerFunctionArgs(FD);
04985     return;
04986   }
04987   // Handle Variables and Typedefs.
04988   SourceLocation DeclLoc = ND->getLocation();
04989   QualType DeclT;
04990   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
04991     DeclT = VD->getType();
04992   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
04993     DeclT = TDD->getUnderlyingType();
04994   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
04995     DeclT = FD->getType();
04996   else
04997     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
04998 
04999   const char *startBuf = SM->getCharacterData(DeclLoc);
05000   const char *endBuf = startBuf;
05001   // scan backward (from the decl location) for the end of the previous decl.
05002   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
05003     startBuf--;
05004   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
05005   std::string buf;
05006   unsigned OrigLength=0;
05007   // *startBuf != '^' if we are dealing with a pointer to function that
05008   // may take block argument types (which will be handled below).
05009   if (*startBuf == '^') {
05010     // Replace the '^' with '*', computing a negative offset.
05011     buf = '*';
05012     startBuf++;
05013     OrigLength++;
05014   }
05015   while (*startBuf != ')') {
05016     buf += *startBuf;
05017     startBuf++;
05018     OrigLength++;
05019   }
05020   buf += ')';
05021   OrigLength++;
05022   
05023   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
05024       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
05025     // Replace the '^' with '*' for arguments.
05026     // Replace id<P> with id/*<>*/
05027     DeclLoc = ND->getLocation();
05028     startBuf = SM->getCharacterData(DeclLoc);
05029     const char *argListBegin, *argListEnd;
05030     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
05031     while (argListBegin < argListEnd) {
05032       if (*argListBegin == '^')
05033         buf += '*';
05034       else if (*argListBegin ==  '<') {
05035         buf += "/*"; 
05036         buf += *argListBegin++;
05037         OrigLength++;
05038         while (*argListBegin != '>') {
05039           buf += *argListBegin++;
05040           OrigLength++;
05041         }
05042         buf += *argListBegin;
05043         buf += "*/";
05044       }
05045       else
05046         buf += *argListBegin;
05047       argListBegin++;
05048       OrigLength++;
05049     }
05050     buf += ')';
05051     OrigLength++;
05052   }
05053   ReplaceText(Start, OrigLength, buf);
05054   
05055   return;
05056 }
05057 
05058 
05059 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
05060 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
05061 ///                    struct Block_byref_id_object *src) {
05062 ///  _Block_object_assign (&_dest->object, _src->object, 
05063 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
05064 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
05065 ///  _Block_object_assign(&_dest->object, _src->object, 
05066 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
05067 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
05068 /// }
05069 /// And:
05070 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
05071 ///  _Block_object_dispose(_src->object, 
05072 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
05073 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
05074 ///  _Block_object_dispose(_src->object, 
05075 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
05076 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
05077 /// }
05078 
05079 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
05080                                                           int flag) {
05081   std::string S;
05082   if (CopyDestroyCache.count(flag))
05083     return S;
05084   CopyDestroyCache.insert(flag);
05085   S = "static void __Block_byref_id_object_copy_";
05086   S += utostr(flag);
05087   S += "(void *dst, void *src) {\n";
05088   
05089   // offset into the object pointer is computed as:
05090   // void * + void* + int + int + void* + void *
05091   unsigned IntSize = 
05092   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
05093   unsigned VoidPtrSize = 
05094   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
05095   
05096   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
05097   S += " _Block_object_assign((char*)dst + ";
05098   S += utostr(offset);
05099   S += ", *(void * *) ((char*)src + ";
05100   S += utostr(offset);
05101   S += "), ";
05102   S += utostr(flag);
05103   S += ");\n}\n";
05104   
05105   S += "static void __Block_byref_id_object_dispose_";
05106   S += utostr(flag);
05107   S += "(void *src) {\n";
05108   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
05109   S += utostr(offset);
05110   S += "), ";
05111   S += utostr(flag);
05112   S += ");\n}\n";
05113   return S;
05114 }
05115 
05116 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
05117 /// the declaration into:
05118 /// struct __Block_byref_ND {
05119 /// void *__isa;                  // NULL for everything except __weak pointers
05120 /// struct __Block_byref_ND *__forwarding;
05121 /// int32_t __flags;
05122 /// int32_t __size;
05123 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
05124 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
05125 /// typex ND;
05126 /// };
05127 ///
05128 /// It then replaces declaration of ND variable with:
05129 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, 
05130 ///                               __size=sizeof(struct __Block_byref_ND), 
05131 ///                               ND=initializer-if-any};
05132 ///
05133 ///
05134 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
05135                                         bool lastDecl) {
05136   int flag = 0;
05137   int isa = 0;
05138   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
05139   if (DeclLoc.isInvalid())
05140     // If type location is missing, it is because of missing type (a warning).
05141     // Use variable's location which is good for this case.
05142     DeclLoc = ND->getLocation();
05143   const char *startBuf = SM->getCharacterData(DeclLoc);
05144   SourceLocation X = ND->getLocEnd();
05145   X = SM->getExpansionLoc(X);
05146   const char *endBuf = SM->getCharacterData(X);
05147   std::string Name(ND->getNameAsString());
05148   std::string ByrefType;
05149   RewriteByRefString(ByrefType, Name, ND, true);
05150   ByrefType += " {\n";
05151   ByrefType += "  void *__isa;\n";
05152   RewriteByRefString(ByrefType, Name, ND);
05153   ByrefType += " *__forwarding;\n";
05154   ByrefType += " int __flags;\n";
05155   ByrefType += " int __size;\n";
05156   // Add void *__Block_byref_id_object_copy; 
05157   // void *__Block_byref_id_object_dispose; if needed.
05158   QualType Ty = ND->getType();
05159   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
05160   if (HasCopyAndDispose) {
05161     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
05162     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
05163   }
05164 
05165   QualType T = Ty;
05166   (void)convertBlockPointerToFunctionPointer(T);
05167   T.getAsStringInternal(Name, Context->getPrintingPolicy());
05168     
05169   ByrefType += " " + Name + ";\n";
05170   ByrefType += "};\n";
05171   // Insert this type in global scope. It is needed by helper function.
05172   SourceLocation FunLocStart;
05173   if (CurFunctionDef)
05174      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
05175   else {
05176     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
05177     FunLocStart = CurMethodDef->getLocStart();
05178   }
05179   InsertText(FunLocStart, ByrefType);
05180   
05181   if (Ty.isObjCGCWeak()) {
05182     flag |= BLOCK_FIELD_IS_WEAK;
05183     isa = 1;
05184   }
05185   if (HasCopyAndDispose) {
05186     flag = BLOCK_BYREF_CALLER;
05187     QualType Ty = ND->getType();
05188     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
05189     if (Ty->isBlockPointerType())
05190       flag |= BLOCK_FIELD_IS_BLOCK;
05191     else
05192       flag |= BLOCK_FIELD_IS_OBJECT;
05193     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
05194     if (!HF.empty())
05195       Preamble += HF;
05196   }
05197   
05198   // struct __Block_byref_ND ND = 
05199   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), 
05200   //  initializer-if-any};
05201   bool hasInit = (ND->getInit() != nullptr);
05202   // FIXME. rewriter does not support __block c++ objects which
05203   // require construction.
05204   if (hasInit)
05205     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
05206       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
05207       if (CXXDecl && CXXDecl->isDefaultConstructor())
05208         hasInit = false;
05209     }
05210   
05211   unsigned flags = 0;
05212   if (HasCopyAndDispose)
05213     flags |= BLOCK_HAS_COPY_DISPOSE;
05214   Name = ND->getNameAsString();
05215   ByrefType.clear();
05216   RewriteByRefString(ByrefType, Name, ND);
05217   std::string ForwardingCastType("(");
05218   ForwardingCastType += ByrefType + " *)";
05219   ByrefType += " " + Name + " = {(void*)";
05220   ByrefType += utostr(isa);
05221   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
05222   ByrefType += utostr(flags);
05223   ByrefType += ", ";
05224   ByrefType += "sizeof(";
05225   RewriteByRefString(ByrefType, Name, ND);
05226   ByrefType += ")";
05227   if (HasCopyAndDispose) {
05228     ByrefType += ", __Block_byref_id_object_copy_";
05229     ByrefType += utostr(flag);
05230     ByrefType += ", __Block_byref_id_object_dispose_";
05231     ByrefType += utostr(flag);
05232   }
05233   
05234   if (!firstDecl) {
05235     // In multiple __block declarations, and for all but 1st declaration,
05236     // find location of the separating comma. This would be start location
05237     // where new text is to be inserted.
05238     DeclLoc = ND->getLocation();
05239     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
05240     const char *commaBuf = startDeclBuf;
05241     while (*commaBuf != ',')
05242       commaBuf--;
05243     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
05244     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
05245     startBuf = commaBuf;
05246   }
05247   
05248   if (!hasInit) {
05249     ByrefType += "};\n";
05250     unsigned nameSize = Name.size();
05251     // for block or function pointer declaration. Name is aleady
05252     // part of the declaration.
05253     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
05254       nameSize = 1;
05255     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
05256   }
05257   else {
05258     ByrefType += ", ";
05259     SourceLocation startLoc;
05260     Expr *E = ND->getInit();
05261     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
05262       startLoc = ECE->getLParenLoc();
05263     else
05264       startLoc = E->getLocStart();
05265     startLoc = SM->getExpansionLoc(startLoc);
05266     endBuf = SM->getCharacterData(startLoc);
05267     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
05268 
05269     const char separator = lastDecl ? ';' : ',';
05270     const char *startInitializerBuf = SM->getCharacterData(startLoc);
05271     const char *separatorBuf = strchr(startInitializerBuf, separator);
05272     assert((*separatorBuf == separator) && 
05273            "RewriteByRefVar: can't find ';' or ','");
05274     SourceLocation separatorLoc =
05275       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
05276     
05277     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
05278   }
05279   return;
05280 }
05281 
05282 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
05283   // Add initializers for any closure decl refs.
05284   GetBlockDeclRefExprs(Exp->getBody());
05285   if (BlockDeclRefs.size()) {
05286     // Unique all "by copy" declarations.
05287     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
05288       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
05289         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
05290           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
05291           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
05292         }
05293       }
05294     // Unique all "by ref" declarations.
05295     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
05296       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
05297         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
05298           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
05299           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
05300         }
05301       }
05302     // Find any imported blocks...they will need special attention.
05303     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
05304       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
05305           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
05306           BlockDeclRefs[i]->getType()->isBlockPointerType())
05307         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
05308   }
05309 }
05310 
05311 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
05312   IdentifierInfo *ID = &Context->Idents.get(name);
05313   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
05314   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
05315                               SourceLocation(), ID, FType, nullptr, SC_Extern,
05316                               false, false);
05317 }
05318 
05319 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
05320                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
05321   
05322   const BlockDecl *block = Exp->getBlockDecl();
05323   
05324   Blocks.push_back(Exp);
05325 
05326   CollectBlockDeclRefInfo(Exp);
05327   
05328   // Add inner imported variables now used in current block.
05329  int countOfInnerDecls = 0;
05330   if (!InnerBlockDeclRefs.empty()) {
05331     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
05332       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
05333       ValueDecl *VD = Exp->getDecl();
05334       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
05335       // We need to save the copied-in variables in nested
05336       // blocks because it is needed at the end for some of the API generations.
05337       // See SynthesizeBlockLiterals routine.
05338         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
05339         BlockDeclRefs.push_back(Exp);
05340         BlockByCopyDeclsPtrSet.insert(VD);
05341         BlockByCopyDecls.push_back(VD);
05342       }
05343       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
05344         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
05345         BlockDeclRefs.push_back(Exp);
05346         BlockByRefDeclsPtrSet.insert(VD);
05347         BlockByRefDecls.push_back(VD);
05348       }
05349     }
05350     // Find any imported blocks...they will need special attention.
05351     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
05352       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
05353           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
05354           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
05355         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
05356   }
05357   InnerDeclRefsCount.push_back(countOfInnerDecls);
05358   
05359   std::string FuncName;
05360 
05361   if (CurFunctionDef)
05362     FuncName = CurFunctionDef->getNameAsString();
05363   else if (CurMethodDef)
05364     BuildUniqueMethodName(FuncName, CurMethodDef);
05365   else if (GlobalVarDecl)
05366     FuncName = std::string(GlobalVarDecl->getNameAsString());
05367 
05368   bool GlobalBlockExpr = 
05369     block->getDeclContext()->getRedeclContext()->isFileContext();
05370   
05371   if (GlobalBlockExpr && !GlobalVarDecl) {
05372     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
05373     GlobalBlockExpr = false;
05374   }
05375   
05376   std::string BlockNumber = utostr(Blocks.size()-1);
05377 
05378   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
05379 
05380   // Get a pointer to the function type so we can cast appropriately.
05381   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
05382   QualType FType = Context->getPointerType(BFT);
05383 
05384   FunctionDecl *FD;
05385   Expr *NewRep;
05386 
05387   // Simulate a constructor call...
05388   std::string Tag;
05389   
05390   if (GlobalBlockExpr)
05391     Tag = "__global_";
05392   else
05393     Tag = "__";
05394   Tag += FuncName + "_block_impl_" + BlockNumber;
05395   
05396   FD = SynthBlockInitFunctionDecl(Tag);
05397   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
05398                                                SourceLocation());
05399 
05400   SmallVector<Expr*, 4> InitExprs;
05401 
05402   // Initialize the block function.
05403   FD = SynthBlockInitFunctionDecl(Func);
05404   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
05405                                                VK_LValue, SourceLocation());
05406   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
05407                                                 CK_BitCast, Arg);
05408   InitExprs.push_back(castExpr);
05409 
05410   // Initialize the block descriptor.
05411   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
05412 
05413   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
05414                                    SourceLocation(), SourceLocation(),
05415                                    &Context->Idents.get(DescData.c_str()),
05416                                    Context->VoidPtrTy, nullptr,
05417                                    SC_Static);
05418   UnaryOperator *DescRefExpr =
05419     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
05420                                                           Context->VoidPtrTy,
05421                                                           VK_LValue,
05422                                                           SourceLocation()), 
05423                                 UO_AddrOf,
05424                                 Context->getPointerType(Context->VoidPtrTy), 
05425                                 VK_RValue, OK_Ordinary,
05426                                 SourceLocation());
05427   InitExprs.push_back(DescRefExpr); 
05428   
05429   // Add initializers for any closure decl refs.
05430   if (BlockDeclRefs.size()) {
05431     Expr *Exp;
05432     // Output all "by copy" declarations.
05433     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
05434          E = BlockByCopyDecls.end(); I != E; ++I) {
05435       if (isObjCType((*I)->getType())) {
05436         // FIXME: Conform to ABI ([[obj retain] autorelease]).
05437         FD = SynthBlockInitFunctionDecl((*I)->getName());
05438         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
05439                                         VK_LValue, SourceLocation());
05440         if (HasLocalVariableExternalStorage(*I)) {
05441           QualType QT = (*I)->getType();
05442           QT = Context->getPointerType(QT);
05443           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
05444                                             OK_Ordinary, SourceLocation());
05445         }
05446       } else if (isTopLevelBlockPointerType((*I)->getType())) {
05447         FD = SynthBlockInitFunctionDecl((*I)->getName());
05448         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
05449                                         VK_LValue, SourceLocation());
05450         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
05451                                        CK_BitCast, Arg);
05452       } else {
05453         FD = SynthBlockInitFunctionDecl((*I)->getName());
05454         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
05455                                         VK_LValue, SourceLocation());
05456         if (HasLocalVariableExternalStorage(*I)) {
05457           QualType QT = (*I)->getType();
05458           QT = Context->getPointerType(QT);
05459           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
05460                                             OK_Ordinary, SourceLocation());
05461         }
05462         
05463       }
05464       InitExprs.push_back(Exp);
05465     }
05466     // Output all "by ref" declarations.
05467     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
05468          E = BlockByRefDecls.end(); I != E; ++I) {
05469       ValueDecl *ND = (*I);
05470       std::string Name(ND->getNameAsString());
05471       std::string RecName;
05472       RewriteByRefString(RecName, Name, ND, true);
05473       IdentifierInfo *II = &Context->Idents.get(RecName.c_str() 
05474                                                 + sizeof("struct"));
05475       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
05476                                           SourceLocation(), SourceLocation(),
05477                                           II);
05478       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
05479       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
05480       
05481       FD = SynthBlockInitFunctionDecl((*I)->getName());
05482       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
05483                                       SourceLocation());
05484       bool isNestedCapturedVar = false;
05485       if (block)
05486         for (const auto &CI : block->captures()) {
05487           const VarDecl *variable = CI.getVariable();
05488           if (variable == ND && CI.isNested()) {
05489             assert (CI.isByRef() && 
05490                     "SynthBlockInitExpr - captured block variable is not byref");
05491             isNestedCapturedVar = true;
05492             break;
05493           }
05494         }
05495       // captured nested byref variable has its address passed. Do not take
05496       // its address again.
05497       if (!isNestedCapturedVar)
05498           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
05499                                      Context->getPointerType(Exp->getType()),
05500                                      VK_RValue, OK_Ordinary, SourceLocation());
05501       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
05502       InitExprs.push_back(Exp);
05503     }
05504   }
05505   if (ImportedBlockDecls.size()) {
05506     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
05507     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
05508     unsigned IntSize = 
05509       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
05510     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), 
05511                                            Context->IntTy, SourceLocation());
05512     InitExprs.push_back(FlagExp);
05513   }
05514   NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
05515                                   FType, VK_LValue, SourceLocation());
05516   
05517   if (GlobalBlockExpr) {
05518     assert (!GlobalConstructionExp &&
05519             "SynthBlockInitExpr - GlobalConstructionExp must be null");
05520     GlobalConstructionExp = NewRep;
05521     NewRep = DRE;
05522   }
05523   
05524   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
05525                              Context->getPointerType(NewRep->getType()),
05526                              VK_RValue, OK_Ordinary, SourceLocation());
05527   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
05528                                     NewRep);
05529   // Put Paren around the call.
05530   NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
05531                                    NewRep);
05532   
05533   BlockDeclRefs.clear();
05534   BlockByRefDecls.clear();
05535   BlockByRefDeclsPtrSet.clear();
05536   BlockByCopyDecls.clear();
05537   BlockByCopyDeclsPtrSet.clear();
05538   ImportedBlockDecls.clear();
05539   return NewRep;
05540 }
05541 
05542 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
05543   if (const ObjCForCollectionStmt * CS = 
05544       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
05545         return CS->getElement() == DS;
05546   return false;
05547 }
05548 
05549 //===----------------------------------------------------------------------===//
05550 // Function Body / Expression rewriting
05551 //===----------------------------------------------------------------------===//
05552 
05553 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
05554   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
05555       isa<DoStmt>(S) || isa<ForStmt>(S))
05556     Stmts.push_back(S);
05557   else if (isa<ObjCForCollectionStmt>(S)) {
05558     Stmts.push_back(S);
05559     ObjCBcLabelNo.push_back(++BcLabelCount);
05560   }
05561 
05562   // Pseudo-object operations and ivar references need special
05563   // treatment because we're going to recursively rewrite them.
05564   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
05565     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
05566       return RewritePropertyOrImplicitSetter(PseudoOp);
05567     } else {
05568       return RewritePropertyOrImplicitGetter(PseudoOp);
05569     }
05570   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
05571     return RewriteObjCIvarRefExpr(IvarRefExpr);
05572   }
05573   else if (isa<OpaqueValueExpr>(S))
05574     S = cast<OpaqueValueExpr>(S)->getSourceExpr();
05575 
05576   SourceRange OrigStmtRange = S->getSourceRange();
05577 
05578   // Perform a bottom up rewrite of all children.
05579   for (Stmt::child_range CI = S->children(); CI; ++CI)
05580     if (*CI) {
05581       Stmt *childStmt = (*CI);
05582       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
05583       if (newStmt) {
05584         *CI = newStmt;
05585       }
05586     }
05587 
05588   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
05589     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
05590     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
05591     InnerContexts.insert(BE->getBlockDecl());
05592     ImportedLocalExternalDecls.clear();
05593     GetInnerBlockDeclRefExprs(BE->getBody(),
05594                               InnerBlockDeclRefs, InnerContexts);
05595     // Rewrite the block body in place.
05596     Stmt *SaveCurrentBody = CurrentBody;
05597     CurrentBody = BE->getBody();
05598     PropParentMap = nullptr;
05599     // block literal on rhs of a property-dot-sytax assignment
05600     // must be replaced by its synthesize ast so getRewrittenText
05601     // works as expected. In this case, what actually ends up on RHS
05602     // is the blockTranscribed which is the helper function for the
05603     // block literal; as in: self.c = ^() {[ace ARR];};
05604     bool saveDisableReplaceStmt = DisableReplaceStmt;
05605     DisableReplaceStmt = false;
05606     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
05607     DisableReplaceStmt = saveDisableReplaceStmt;
05608     CurrentBody = SaveCurrentBody;
05609     PropParentMap = nullptr;
05610     ImportedLocalExternalDecls.clear();
05611     // Now we snarf the rewritten text and stash it away for later use.
05612     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
05613     RewrittenBlockExprs[BE] = Str;
05614 
05615     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
05616                             
05617     //blockTranscribed->dump();
05618     ReplaceStmt(S, blockTranscribed);
05619     return blockTranscribed;
05620   }
05621   // Handle specific things.
05622   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
05623     return RewriteAtEncode(AtEncode);
05624 
05625   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
05626     return RewriteAtSelector(AtSelector);
05627 
05628   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
05629     return RewriteObjCStringLiteral(AtString);
05630   
05631   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
05632     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
05633   
05634   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
05635     return RewriteObjCBoxedExpr(BoxedExpr);
05636   
05637   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
05638     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
05639   
05640   if (ObjCDictionaryLiteral *DictionaryLitExpr = 
05641         dyn_cast<ObjCDictionaryLiteral>(S))
05642     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
05643 
05644   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
05645 #if 0
05646     // Before we rewrite it, put the original message expression in a comment.
05647     SourceLocation startLoc = MessExpr->getLocStart();
05648     SourceLocation endLoc = MessExpr->getLocEnd();
05649 
05650     const char *startBuf = SM->getCharacterData(startLoc);
05651     const char *endBuf = SM->getCharacterData(endLoc);
05652 
05653     std::string messString;
05654     messString += "// ";
05655     messString.append(startBuf, endBuf-startBuf+1);
05656     messString += "\n";
05657 
05658     // FIXME: Missing definition of
05659     // InsertText(clang::SourceLocation, char const*, unsigned int).
05660     // InsertText(startLoc, messString.c_str(), messString.size());
05661     // Tried this, but it didn't work either...
05662     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
05663 #endif
05664     return RewriteMessageExpr(MessExpr);
05665   }
05666 
05667   if (ObjCAutoreleasePoolStmt *StmtAutoRelease = 
05668         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
05669     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
05670   }
05671   
05672   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
05673     return RewriteObjCTryStmt(StmtTry);
05674 
05675   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
05676     return RewriteObjCSynchronizedStmt(StmtTry);
05677 
05678   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
05679     return RewriteObjCThrowStmt(StmtThrow);
05680 
05681   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
05682     return RewriteObjCProtocolExpr(ProtocolExp);
05683 
05684   if (ObjCForCollectionStmt *StmtForCollection =
05685         dyn_cast<ObjCForCollectionStmt>(S))
05686     return RewriteObjCForCollectionStmt(StmtForCollection,
05687                                         OrigStmtRange.getEnd());
05688   if (BreakStmt *StmtBreakStmt =
05689       dyn_cast<BreakStmt>(S))
05690     return RewriteBreakStmt(StmtBreakStmt);
05691   if (ContinueStmt *StmtContinueStmt =
05692       dyn_cast<ContinueStmt>(S))
05693     return RewriteContinueStmt(StmtContinueStmt);
05694 
05695   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
05696   // and cast exprs.
05697   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
05698     // FIXME: What we're doing here is modifying the type-specifier that
05699     // precedes the first Decl.  In the future the DeclGroup should have
05700     // a separate type-specifier that we can rewrite.
05701     // NOTE: We need to avoid rewriting the DeclStmt if it is within
05702     // the context of an ObjCForCollectionStmt. For example:
05703     //   NSArray *someArray;
05704     //   for (id <FooProtocol> index in someArray) ;
05705     // This is because RewriteObjCForCollectionStmt() does textual rewriting 
05706     // and it depends on the original text locations/positions.
05707     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
05708       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
05709 
05710     // Blocks rewrite rules.
05711     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
05712          DI != DE; ++DI) {
05713       Decl *SD = *DI;
05714       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
05715         if (isTopLevelBlockPointerType(ND->getType()))
05716           RewriteBlockPointerDecl(ND);
05717         else if (ND->getType()->isFunctionPointerType())
05718           CheckFunctionPointerDecl(ND->getType(), ND);
05719         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
05720           if (VD->hasAttr<BlocksAttr>()) {
05721             static unsigned uniqueByrefDeclCount = 0;
05722             assert(!BlockByRefDeclNo.count(ND) &&
05723               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
05724             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
05725             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
05726           }
05727           else           
05728             RewriteTypeOfDecl(VD);
05729         }
05730       }
05731       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
05732         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
05733           RewriteBlockPointerDecl(TD);
05734         else if (TD->getUnderlyingType()->isFunctionPointerType())
05735           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
05736       }
05737     }
05738   }
05739 
05740   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
05741     RewriteObjCQualifiedInterfaceTypes(CE);
05742 
05743   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
05744       isa<DoStmt>(S) || isa<ForStmt>(S)) {
05745     assert(!Stmts.empty() && "Statement stack is empty");
05746     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
05747              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
05748             && "Statement stack mismatch");
05749     Stmts.pop_back();
05750   }
05751   // Handle blocks rewriting.
05752   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
05753     ValueDecl *VD = DRE->getDecl(); 
05754     if (VD->hasAttr<BlocksAttr>())
05755       return RewriteBlockDeclRefExpr(DRE);
05756     if (HasLocalVariableExternalStorage(VD))
05757       return RewriteLocalVariableExternalStorage(DRE);
05758   }
05759   
05760   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
05761     if (CE->getCallee()->getType()->isBlockPointerType()) {
05762       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
05763       ReplaceStmt(S, BlockCall);
05764       return BlockCall;
05765     }
05766   }
05767   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
05768     RewriteCastExpr(CE);
05769   }
05770   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
05771     RewriteImplicitCastObjCExpr(ICE);
05772   }
05773 #if 0
05774 
05775   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
05776     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
05777                                                    ICE->getSubExpr(),
05778                                                    SourceLocation());
05779     // Get the new text.
05780     std::string SStr;
05781     llvm::raw_string_ostream Buf(SStr);
05782     Replacement->printPretty(Buf);
05783     const std::string &Str = Buf.str();
05784 
05785     printf("CAST = %s\n", &Str[0]);
05786     InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
05787     delete S;
05788     return Replacement;
05789   }
05790 #endif
05791   // Return this stmt unmodified.
05792   return S;
05793 }
05794 
05795 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
05796   for (auto *FD : RD->fields()) {
05797     if (isTopLevelBlockPointerType(FD->getType()))
05798       RewriteBlockPointerDecl(FD);
05799     if (FD->getType()->isObjCQualifiedIdType() ||
05800         FD->getType()->isObjCQualifiedInterfaceType())
05801       RewriteObjCQualifiedInterfaceTypes(FD);
05802   }
05803 }
05804 
05805 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
05806 /// main file of the input.
05807 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
05808   switch (D->getKind()) {
05809     case Decl::Function: {
05810       FunctionDecl *FD = cast<FunctionDecl>(D);
05811       if (FD->isOverloadedOperator())
05812         return;
05813 
05814       // Since function prototypes don't have ParmDecl's, we check the function
05815       // prototype. This enables us to rewrite function declarations and
05816       // definitions using the same code.
05817       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
05818 
05819       if (!FD->isThisDeclarationADefinition())
05820         break;
05821 
05822       // FIXME: If this should support Obj-C++, support CXXTryStmt
05823       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
05824         CurFunctionDef = FD;
05825         CurrentBody = Body;
05826         Body =
05827         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
05828         FD->setBody(Body);
05829         CurrentBody = nullptr;
05830         if (PropParentMap) {
05831           delete PropParentMap;
05832           PropParentMap = nullptr;
05833         }
05834         // This synthesizes and inserts the block "impl" struct, invoke function,
05835         // and any copy/dispose helper functions.
05836         InsertBlockLiteralsWithinFunction(FD);
05837         RewriteLineDirective(D);
05838         CurFunctionDef = nullptr;
05839       }
05840       break;
05841     }
05842     case Decl::ObjCMethod: {
05843       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
05844       if (CompoundStmt *Body = MD->getCompoundBody()) {
05845         CurMethodDef = MD;
05846         CurrentBody = Body;
05847         Body =
05848           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
05849         MD->setBody(Body);
05850         CurrentBody = nullptr;
05851         if (PropParentMap) {
05852           delete PropParentMap;
05853           PropParentMap = nullptr;
05854         }
05855         InsertBlockLiteralsWithinMethod(MD);
05856         RewriteLineDirective(D);
05857         CurMethodDef = nullptr;
05858       }
05859       break;
05860     }
05861     case Decl::ObjCImplementation: {
05862       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
05863       ClassImplementation.push_back(CI);
05864       break;
05865     }
05866     case Decl::ObjCCategoryImpl: {
05867       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
05868       CategoryImplementation.push_back(CI);
05869       break;
05870     }
05871     case Decl::Var: {
05872       VarDecl *VD = cast<VarDecl>(D);
05873       RewriteObjCQualifiedInterfaceTypes(VD);
05874       if (isTopLevelBlockPointerType(VD->getType()))
05875         RewriteBlockPointerDecl(VD);
05876       else if (VD->getType()->isFunctionPointerType()) {
05877         CheckFunctionPointerDecl(VD->getType(), VD);
05878         if (VD->getInit()) {
05879           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
05880             RewriteCastExpr(CE);
05881           }
05882         }
05883       } else if (VD->getType()->isRecordType()) {
05884         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
05885         if (RD->isCompleteDefinition())
05886           RewriteRecordBody(RD);
05887       }
05888       if (VD->getInit()) {
05889         GlobalVarDecl = VD;
05890         CurrentBody = VD->getInit();
05891         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
05892         CurrentBody = nullptr;
05893         if (PropParentMap) {
05894           delete PropParentMap;
05895           PropParentMap = nullptr;
05896         }
05897         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
05898         GlobalVarDecl = nullptr;
05899 
05900         // This is needed for blocks.
05901         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
05902             RewriteCastExpr(CE);
05903         }
05904       }
05905       break;
05906     }
05907     case Decl::TypeAlias:
05908     case Decl::Typedef: {
05909       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
05910         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
05911           RewriteBlockPointerDecl(TD);
05912         else if (TD->getUnderlyingType()->isFunctionPointerType())
05913           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
05914         else
05915           RewriteObjCQualifiedInterfaceTypes(TD);
05916       }
05917       break;
05918     }
05919     case Decl::CXXRecord:
05920     case Decl::Record: {
05921       RecordDecl *RD = cast<RecordDecl>(D);
05922       if (RD->isCompleteDefinition()) 
05923         RewriteRecordBody(RD);
05924       break;
05925     }
05926     default:
05927       break;
05928   }
05929   // Nothing yet.
05930 }
05931 
05932 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
05933 /// protocol reference symbols in the for of:
05934 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
05935 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, 
05936                                                  ObjCProtocolDecl *PDecl,
05937                                                  std::string &Result) {
05938   // Also output .objc_protorefs$B section and its meta-data.
05939   if (Context->getLangOpts().MicrosoftExt)
05940     Result += "static ";
05941   Result += "struct _protocol_t *";
05942   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
05943   Result += PDecl->getNameAsString();
05944   Result += " = &";
05945   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
05946   Result += ";\n";
05947 }
05948 
05949 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
05950   if (Diags.hasErrorOccurred())
05951     return;
05952 
05953   RewriteInclude();
05954 
05955   for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
05956     // translation of function bodies were postponed until all class and
05957     // their extensions and implementations are seen. This is because, we
05958     // cannot build grouping structs for bitfields until they are all seen.
05959     FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
05960     HandleTopLevelSingleDecl(FDecl);
05961   }
05962 
05963   // Here's a great place to add any extra declarations that may be needed.
05964   // Write out meta data for each @protocol(<expr>).
05965   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
05966     RewriteObjCProtocolMetaData(ProtDecl, Preamble);
05967     Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
05968   }
05969 
05970   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
05971   
05972   if (ClassImplementation.size() || CategoryImplementation.size())
05973     RewriteImplementations();
05974   
05975   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
05976     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
05977     // Write struct declaration for the class matching its ivar declarations.
05978     // Note that for modern abi, this is postponed until the end of TU
05979     // because class extensions and the implementation might declare their own
05980     // private ivars.
05981     RewriteInterfaceDecl(CDecl);
05982   }
05983   
05984   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
05985   // we are done.
05986   if (const RewriteBuffer *RewriteBuf =
05987       Rewrite.getRewriteBufferFor(MainFileID)) {
05988     //printf("Changed:\n");
05989     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
05990   } else {
05991     llvm::errs() << "No changes\n";
05992   }
05993 
05994   if (ClassImplementation.size() || CategoryImplementation.size() ||
05995       ProtocolExprDecls.size()) {
05996     // Rewrite Objective-c meta data*
05997     std::string ResultStr;
05998     RewriteMetaDataIntoBuffer(ResultStr);
05999     // Emit metadata.
06000     *OutFile << ResultStr;
06001   }
06002   // Emit ImageInfo;
06003   {
06004     std::string ResultStr;
06005     WriteImageInfo(ResultStr);
06006     *OutFile << ResultStr;
06007   }
06008   OutFile->flush();
06009 }
06010 
06011 void RewriteModernObjC::Initialize(ASTContext &context) {
06012   InitializeCommon(context);
06013   
06014   Preamble += "#ifndef __OBJC2__\n";
06015   Preamble += "#define __OBJC2__\n";
06016   Preamble += "#endif\n";
06017 
06018   // declaring objc_selector outside the parameter list removes a silly
06019   // scope related warning...
06020   if (IsHeader)
06021     Preamble = "#pragma once\n";
06022   Preamble += "struct objc_selector; struct objc_class;\n";
06023   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
06024   Preamble += "\n\tstruct objc_object *superClass; ";
06025   // Add a constructor for creating temporary objects.
06026   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
06027   Preamble += ": object(o), superClass(s) {} ";
06028   Preamble += "\n};\n";
06029   
06030   if (LangOpts.MicrosoftExt) {
06031     // Define all sections using syntax that makes sense.
06032     // These are currently generated.
06033     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
06034     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
06035     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
06036     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
06037     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
06038     // These are generated but not necessary for functionality.
06039     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
06040     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
06041     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
06042     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
06043     
06044     // These need be generated for performance. Currently they are not,
06045     // using API calls instead.
06046     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
06047     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
06048     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
06049     
06050   }
06051   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
06052   Preamble += "typedef struct objc_object Protocol;\n";
06053   Preamble += "#define _REWRITER_typedef_Protocol\n";
06054   Preamble += "#endif\n";
06055   if (LangOpts.MicrosoftExt) {
06056     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
06057     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
06058   } 
06059   else
06060     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
06061   
06062   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
06063   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
06064   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
06065   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
06066   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
06067 
06068   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
06069   Preamble += "(const char *);\n";
06070   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
06071   Preamble += "(struct objc_class *);\n";
06072   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
06073   Preamble += "(const char *);\n";
06074   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
06075   // @synchronized hooks.
06076   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
06077   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
06078   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
06079   Preamble += "#ifdef _WIN64\n";
06080   Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
06081   Preamble += "#else\n";
06082   Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
06083   Preamble += "#endif\n";
06084   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
06085   Preamble += "struct __objcFastEnumerationState {\n\t";
06086   Preamble += "unsigned long state;\n\t";
06087   Preamble += "void **itemsPtr;\n\t";
06088   Preamble += "unsigned long *mutationsPtr;\n\t";
06089   Preamble += "unsigned long extra[5];\n};\n";
06090   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
06091   Preamble += "#define __FASTENUMERATIONSTATE\n";
06092   Preamble += "#endif\n";
06093   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
06094   Preamble += "struct __NSConstantStringImpl {\n";
06095   Preamble += "  int *isa;\n";
06096   Preamble += "  int flags;\n";
06097   Preamble += "  char *str;\n";
06098   Preamble += "#if _WIN64\n";
06099   Preamble += "  long long length;\n";
06100   Preamble += "#else\n";
06101   Preamble += "  long length;\n";
06102   Preamble += "#endif\n";
06103   Preamble += "};\n";
06104   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
06105   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
06106   Preamble += "#else\n";
06107   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
06108   Preamble += "#endif\n";
06109   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
06110   Preamble += "#endif\n";
06111   // Blocks preamble.
06112   Preamble += "#ifndef BLOCK_IMPL\n";
06113   Preamble += "#define BLOCK_IMPL\n";
06114   Preamble += "struct __block_impl {\n";
06115   Preamble += "  void *isa;\n";
06116   Preamble += "  int Flags;\n";
06117   Preamble += "  int Reserved;\n";
06118   Preamble += "  void *FuncPtr;\n";
06119   Preamble += "};\n";
06120   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
06121   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
06122   Preamble += "extern \"C\" __declspec(dllexport) "
06123   "void _Block_object_assign(void *, const void *, const int);\n";
06124   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
06125   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
06126   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
06127   Preamble += "#else\n";
06128   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
06129   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
06130   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
06131   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
06132   Preamble += "#endif\n";
06133   Preamble += "#endif\n";
06134   if (LangOpts.MicrosoftExt) {
06135     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
06136     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
06137     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
06138     Preamble += "#define __attribute__(X)\n";
06139     Preamble += "#endif\n";
06140     Preamble += "#ifndef __weak\n";
06141     Preamble += "#define __weak\n";
06142     Preamble += "#endif\n";
06143     Preamble += "#ifndef __block\n";
06144     Preamble += "#define __block\n";
06145     Preamble += "#endif\n";
06146   }
06147   else {
06148     Preamble += "#define __block\n";
06149     Preamble += "#define __weak\n";
06150   }
06151   
06152   // Declarations required for modern objective-c array and dictionary literals.
06153   Preamble += "\n#include <stdarg.h>\n";
06154   Preamble += "struct __NSContainer_literal {\n";
06155   Preamble += "  void * *arr;\n";
06156   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
06157   Preamble += "\tva_list marker;\n";
06158   Preamble += "\tva_start(marker, count);\n";
06159   Preamble += "\tarr = new void *[count];\n";
06160   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
06161   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
06162   Preamble += "\tva_end( marker );\n";
06163   Preamble += "  };\n";
06164   Preamble += "  ~__NSContainer_literal() {\n";
06165   Preamble += "\tdelete[] arr;\n";
06166   Preamble += "  }\n";
06167   Preamble += "};\n";
06168   
06169   // Declaration required for implementation of @autoreleasepool statement.
06170   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
06171   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
06172   Preamble += "struct __AtAutoreleasePool {\n";
06173   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
06174   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
06175   Preamble += "  void * atautoreleasepoolobj;\n";
06176   Preamble += "};\n";
06177   
06178   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
06179   // as this avoids warning in any 64bit/32bit compilation model.
06180   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
06181 }
06182 
06183 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
06184 /// ivar offset.
06185 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
06186                                                          std::string &Result) {
06187   Result += "__OFFSETOFIVAR__(struct ";
06188   Result += ivar->getContainingInterface()->getNameAsString();
06189   if (LangOpts.MicrosoftExt)
06190     Result += "_IMPL";
06191   Result += ", ";
06192   if (ivar->isBitField())
06193     ObjCIvarBitfieldGroupDecl(ivar, Result);
06194   else
06195     Result += ivar->getNameAsString();
06196   Result += ")";
06197 }
06198 
06199 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
06200 /// struct _prop_t {
06201 ///   const char *name;
06202 ///   char *attributes;
06203 /// }
06204 
06205 /// struct _prop_list_t {
06206 ///   uint32_t entsize;      // sizeof(struct _prop_t)
06207 ///   uint32_t count_of_properties;
06208 ///   struct _prop_t prop_list[count_of_properties];
06209 /// }
06210 
06211 /// struct _protocol_t;
06212 
06213 /// struct _protocol_list_t {
06214 ///   long protocol_count;   // Note, this is 32/64 bit
06215 ///   struct _protocol_t * protocol_list[protocol_count];
06216 /// }
06217 
06218 /// struct _objc_method {
06219 ///   SEL _cmd;
06220 ///   const char *method_type;
06221 ///   char *_imp;
06222 /// }
06223 
06224 /// struct _method_list_t {
06225 ///   uint32_t entsize;  // sizeof(struct _objc_method)
06226 ///   uint32_t method_count;
06227 ///   struct _objc_method method_list[method_count];
06228 /// }
06229 
06230 /// struct _protocol_t {
06231 ///   id isa;  // NULL
06232 ///   const char *protocol_name;
06233 ///   const struct _protocol_list_t * protocol_list; // super protocols
06234 ///   const struct method_list_t *instance_methods;
06235 ///   const struct method_list_t *class_methods;
06236 ///   const struct method_list_t *optionalInstanceMethods;
06237 ///   const struct method_list_t *optionalClassMethods;
06238 ///   const struct _prop_list_t * properties;
06239 ///   const uint32_t size;  // sizeof(struct _protocol_t)
06240 ///   const uint32_t flags;  // = 0
06241 ///   const char ** extendedMethodTypes;
06242 /// }
06243 
06244 /// struct _ivar_t {
06245 ///   unsigned long int *offset;  // pointer to ivar offset location
06246 ///   const char *name;
06247 ///   const char *type;
06248 ///   uint32_t alignment;
06249 ///   uint32_t size;
06250 /// }
06251 
06252 /// struct _ivar_list_t {
06253 ///   uint32 entsize;  // sizeof(struct _ivar_t)
06254 ///   uint32 count;
06255 ///   struct _ivar_t list[count];
06256 /// }
06257 
06258 /// struct _class_ro_t {
06259 ///   uint32_t flags;
06260 ///   uint32_t instanceStart;
06261 ///   uint32_t instanceSize;
06262 ///   uint32_t reserved;  // only when building for 64bit targets
06263 ///   const uint8_t *ivarLayout;
06264 ///   const char *name;
06265 ///   const struct _method_list_t *baseMethods;
06266 ///   const struct _protocol_list_t *baseProtocols;
06267 ///   const struct _ivar_list_t *ivars;
06268 ///   const uint8_t *weakIvarLayout;
06269 ///   const struct _prop_list_t *properties;
06270 /// }
06271 
06272 /// struct _class_t {
06273 ///   struct _class_t *isa;
06274 ///   struct _class_t *superclass;
06275 ///   void *cache;
06276 ///   IMP *vtable;
06277 ///   struct _class_ro_t *ro;
06278 /// }
06279 
06280 /// struct _category_t {
06281 ///   const char *name;
06282 ///   struct _class_t *cls;
06283 ///   const struct _method_list_t *instance_methods;
06284 ///   const struct _method_list_t *class_methods;
06285 ///   const struct _protocol_list_t *protocols;
06286 ///   const struct _prop_list_t *properties;
06287 /// }
06288 
06289 /// MessageRefTy - LLVM for:
06290 /// struct _message_ref_t {
06291 ///   IMP messenger;
06292 ///   SEL name;
06293 /// };
06294 
06295 /// SuperMessageRefTy - LLVM for:
06296 /// struct _super_message_ref_t {
06297 ///   SUPER_IMP messenger;
06298 ///   SEL name;
06299 /// };
06300 
06301 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
06302   static bool meta_data_declared = false;
06303   if (meta_data_declared)
06304     return;
06305   
06306   Result += "\nstruct _prop_t {\n";
06307   Result += "\tconst char *name;\n";
06308   Result += "\tconst char *attributes;\n";
06309   Result += "};\n";
06310   
06311   Result += "\nstruct _protocol_t;\n";
06312   
06313   Result += "\nstruct _objc_method {\n";
06314   Result += "\tstruct objc_selector * _cmd;\n";
06315   Result += "\tconst char *method_type;\n";
06316   Result += "\tvoid  *_imp;\n";
06317   Result += "};\n";
06318   
06319   Result += "\nstruct _protocol_t {\n";
06320   Result += "\tvoid * isa;  // NULL\n";
06321   Result += "\tconst char *protocol_name;\n";
06322   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
06323   Result += "\tconst struct method_list_t *instance_methods;\n";
06324   Result += "\tconst struct method_list_t *class_methods;\n";
06325   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
06326   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
06327   Result += "\tconst struct _prop_list_t * properties;\n";
06328   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
06329   Result += "\tconst unsigned int flags;  // = 0\n";
06330   Result += "\tconst char ** extendedMethodTypes;\n";
06331   Result += "};\n";
06332   
06333   Result += "\nstruct _ivar_t {\n";
06334   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
06335   Result += "\tconst char *name;\n";
06336   Result += "\tconst char *type;\n";
06337   Result += "\tunsigned int alignment;\n";
06338   Result += "\tunsigned int  size;\n";
06339   Result += "};\n";
06340   
06341   Result += "\nstruct _class_ro_t {\n";
06342   Result += "\tunsigned int flags;\n";
06343   Result += "\tunsigned int instanceStart;\n";
06344   Result += "\tunsigned int instanceSize;\n";
06345   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
06346   if (Triple.getArch() == llvm::Triple::x86_64)
06347     Result += "\tunsigned int reserved;\n";
06348   Result += "\tconst unsigned char *ivarLayout;\n";
06349   Result += "\tconst char *name;\n";
06350   Result += "\tconst struct _method_list_t *baseMethods;\n";
06351   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
06352   Result += "\tconst struct _ivar_list_t *ivars;\n";
06353   Result += "\tconst unsigned char *weakIvarLayout;\n";
06354   Result += "\tconst struct _prop_list_t *properties;\n";
06355   Result += "};\n";
06356   
06357   Result += "\nstruct _class_t {\n";
06358   Result += "\tstruct _class_t *isa;\n";
06359   Result += "\tstruct _class_t *superclass;\n";
06360   Result += "\tvoid *cache;\n";
06361   Result += "\tvoid *vtable;\n";
06362   Result += "\tstruct _class_ro_t *ro;\n";
06363   Result += "};\n";
06364   
06365   Result += "\nstruct _category_t {\n";
06366   Result += "\tconst char *name;\n";
06367   Result += "\tstruct _class_t *cls;\n";
06368   Result += "\tconst struct _method_list_t *instance_methods;\n";
06369   Result += "\tconst struct _method_list_t *class_methods;\n";
06370   Result += "\tconst struct _protocol_list_t *protocols;\n";
06371   Result += "\tconst struct _prop_list_t *properties;\n";
06372   Result += "};\n";
06373   
06374   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
06375   Result += "#pragma warning(disable:4273)\n";
06376   meta_data_declared = true;
06377 }
06378 
06379 static void Write_protocol_list_t_TypeDecl(std::string &Result,
06380                                            long super_protocol_count) {
06381   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
06382   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
06383   Result += "\tstruct _protocol_t *super_protocols[";
06384   Result += utostr(super_protocol_count); Result += "];\n";
06385   Result += "}";
06386 }
06387 
06388 static void Write_method_list_t_TypeDecl(std::string &Result,
06389                                          unsigned int method_count) {
06390   Result += "struct /*_method_list_t*/"; Result += " {\n";
06391   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
06392   Result += "\tunsigned int method_count;\n";
06393   Result += "\tstruct _objc_method method_list[";
06394   Result += utostr(method_count); Result += "];\n";
06395   Result += "}";
06396 }
06397 
06398 static void Write__prop_list_t_TypeDecl(std::string &Result,
06399                                         unsigned int property_count) {
06400   Result += "struct /*_prop_list_t*/"; Result += " {\n";
06401   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
06402   Result += "\tunsigned int count_of_properties;\n";
06403   Result += "\tstruct _prop_t prop_list[";
06404   Result += utostr(property_count); Result += "];\n";
06405   Result += "}";
06406 }
06407 
06408 static void Write__ivar_list_t_TypeDecl(std::string &Result,
06409                                         unsigned int ivar_count) {
06410   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
06411   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
06412   Result += "\tunsigned int count;\n";
06413   Result += "\tstruct _ivar_t ivar_list[";
06414   Result += utostr(ivar_count); Result += "];\n";
06415   Result += "}";
06416 }
06417 
06418 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
06419                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
06420                                             StringRef VarName,
06421                                             StringRef ProtocolName) {
06422   if (SuperProtocols.size() > 0) {
06423     Result += "\nstatic ";
06424     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
06425     Result += " "; Result += VarName;
06426     Result += ProtocolName; 
06427     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
06428     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
06429     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
06430       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
06431       Result += "\t&"; Result += "_OBJC_PROTOCOL_"; 
06432       Result += SuperPD->getNameAsString();
06433       if (i == e-1)
06434         Result += "\n};\n";
06435       else
06436         Result += ",\n";
06437     }
06438   }
06439 }
06440 
06441 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
06442                                             ASTContext *Context, std::string &Result,
06443                                             ArrayRef<ObjCMethodDecl *> Methods,
06444                                             StringRef VarName,
06445                                             StringRef TopLevelDeclName,
06446                                             bool MethodImpl) {
06447   if (Methods.size() > 0) {
06448     Result += "\nstatic ";
06449     Write_method_list_t_TypeDecl(Result, Methods.size());
06450     Result += " "; Result += VarName;
06451     Result += TopLevelDeclName; 
06452     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
06453     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
06454     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
06455     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
06456       ObjCMethodDecl *MD = Methods[i];
06457       if (i == 0)
06458         Result += "\t{{(struct objc_selector *)\"";
06459       else
06460         Result += "\t{(struct objc_selector *)\"";
06461       Result += (MD)->getSelector().getAsString(); Result += "\"";
06462       Result += ", ";
06463       std::string MethodTypeString;
06464       Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
06465       Result += "\""; Result += MethodTypeString; Result += "\"";
06466       Result += ", ";
06467       if (!MethodImpl)
06468         Result += "0";
06469       else {
06470         Result += "(void *)";
06471         Result += RewriteObj.MethodInternalNames[MD];
06472       }
06473       if (i  == e-1)
06474         Result += "}}\n";
06475       else
06476         Result += "},\n";
06477     }
06478     Result += "};\n";
06479   }
06480 }
06481 
06482 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
06483                                            ASTContext *Context, std::string &Result,
06484                                            ArrayRef<ObjCPropertyDecl *> Properties,
06485                                            const Decl *Container,
06486                                            StringRef VarName,
06487                                            StringRef ProtocolName) {
06488   if (Properties.size() > 0) {
06489     Result += "\nstatic ";
06490     Write__prop_list_t_TypeDecl(Result, Properties.size());
06491     Result += " "; Result += VarName;
06492     Result += ProtocolName; 
06493     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
06494     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
06495     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
06496     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
06497       ObjCPropertyDecl *PropDecl = Properties[i];
06498       if (i == 0)
06499         Result += "\t{{\"";
06500       else
06501         Result += "\t{\"";
06502       Result += PropDecl->getName(); Result += "\",";
06503       std::string PropertyTypeString, QuotePropertyTypeString;
06504       Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
06505       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
06506       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
06507       if (i  == e-1)
06508         Result += "}}\n";
06509       else
06510         Result += "},\n";
06511     }
06512     Result += "};\n";
06513   }
06514 }
06515 
06516 // Metadata flags
06517 enum MetaDataDlags {
06518   CLS = 0x0,
06519   CLS_META = 0x1,
06520   CLS_ROOT = 0x2,
06521   OBJC2_CLS_HIDDEN = 0x10,
06522   CLS_EXCEPTION = 0x20,
06523   
06524   /// (Obsolete) ARC-specific: this class has a .release_ivars method
06525   CLS_HAS_IVAR_RELEASER = 0x40,
06526   /// class was compiled with -fobjc-arr
06527   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
06528 };
06529 
06530 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, 
06531                                           unsigned int flags, 
06532                                           const std::string &InstanceStart, 
06533                                           const std::string &InstanceSize,
06534                                           ArrayRef<ObjCMethodDecl *>baseMethods,
06535                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
06536                                           ArrayRef<ObjCIvarDecl *>ivars,
06537                                           ArrayRef<ObjCPropertyDecl *>Properties,
06538                                           StringRef VarName,
06539                                           StringRef ClassName) {
06540   Result += "\nstatic struct _class_ro_t ";
06541   Result += VarName; Result += ClassName;
06542   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
06543   Result += "\t"; 
06544   Result += llvm::utostr(flags); Result += ", "; 
06545   Result += InstanceStart; Result += ", ";
06546   Result += InstanceSize; Result += ", \n";
06547   Result += "\t";
06548   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
06549   if (Triple.getArch() == llvm::Triple::x86_64)
06550     // uint32_t const reserved; // only when building for 64bit targets
06551     Result += "(unsigned int)0, \n\t";
06552   // const uint8_t * const ivarLayout;
06553   Result += "0, \n\t";
06554   Result += "\""; Result += ClassName; Result += "\",\n\t";
06555   bool metaclass = ((flags & CLS_META) != 0);
06556   if (baseMethods.size() > 0) {
06557     Result += "(const struct _method_list_t *)&";
06558     if (metaclass)
06559       Result += "_OBJC_$_CLASS_METHODS_";
06560     else
06561       Result += "_OBJC_$_INSTANCE_METHODS_";
06562     Result += ClassName;
06563     Result += ",\n\t";
06564   }
06565   else
06566     Result += "0, \n\t";
06567 
06568   if (!metaclass && baseProtocols.size() > 0) {
06569     Result += "(const struct _objc_protocol_list *)&";
06570     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
06571     Result += ",\n\t";
06572   }
06573   else
06574     Result += "0, \n\t";
06575 
06576   if (!metaclass && ivars.size() > 0) {
06577     Result += "(const struct _ivar_list_t *)&";
06578     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
06579     Result += ",\n\t";
06580   }
06581   else
06582     Result += "0, \n\t";
06583 
06584   // weakIvarLayout
06585   Result += "0, \n\t";
06586   if (!metaclass && Properties.size() > 0) {
06587     Result += "(const struct _prop_list_t *)&";
06588     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
06589     Result += ",\n";
06590   }
06591   else
06592     Result += "0, \n";
06593 
06594   Result += "};\n";
06595 }
06596 
06597 static void Write_class_t(ASTContext *Context, std::string &Result,
06598                           StringRef VarName,
06599                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
06600   bool rootClass = (!CDecl->getSuperClass());
06601   const ObjCInterfaceDecl *RootClass = CDecl;
06602   
06603   if (!rootClass) {
06604     // Find the Root class
06605     RootClass = CDecl->getSuperClass();
06606     while (RootClass->getSuperClass()) {
06607       RootClass = RootClass->getSuperClass();
06608     }
06609   }
06610 
06611   if (metaclass && rootClass) {
06612     // Need to handle a case of use of forward declaration.
06613     Result += "\n";
06614     Result += "extern \"C\" ";
06615     if (CDecl->getImplementation())
06616       Result += "__declspec(dllexport) ";
06617     else
06618       Result += "__declspec(dllimport) ";
06619     
06620     Result += "struct _class_t OBJC_CLASS_$_";
06621     Result += CDecl->getNameAsString();
06622     Result += ";\n";
06623   }
06624   // Also, for possibility of 'super' metadata class not having been defined yet.
06625   if (!rootClass) {
06626     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
06627     Result += "\n";
06628     Result += "extern \"C\" ";
06629     if (SuperClass->getImplementation())
06630       Result += "__declspec(dllexport) ";
06631     else
06632       Result += "__declspec(dllimport) ";
06633 
06634     Result += "struct _class_t "; 
06635     Result += VarName;
06636     Result += SuperClass->getNameAsString();
06637     Result += ";\n";
06638     
06639     if (metaclass && RootClass != SuperClass) {
06640       Result += "extern \"C\" ";
06641       if (RootClass->getImplementation())
06642         Result += "__declspec(dllexport) ";
06643       else
06644         Result += "__declspec(dllimport) ";
06645 
06646       Result += "struct _class_t "; 
06647       Result += VarName;
06648       Result += RootClass->getNameAsString();
06649       Result += ";\n";
06650     }
06651   }
06652   
06653   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; 
06654   Result += VarName; Result += CDecl->getNameAsString();
06655   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
06656   Result += "\t";
06657   if (metaclass) {
06658     if (!rootClass) {
06659       Result += "0, // &"; Result += VarName;
06660       Result += RootClass->getNameAsString();
06661       Result += ",\n\t";
06662       Result += "0, // &"; Result += VarName;
06663       Result += CDecl->getSuperClass()->getNameAsString();
06664       Result += ",\n\t";
06665     }
06666     else {
06667       Result += "0, // &"; Result += VarName; 
06668       Result += CDecl->getNameAsString();
06669       Result += ",\n\t";
06670       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
06671       Result += ",\n\t";
06672     }
06673   }
06674   else {
06675     Result += "0, // &OBJC_METACLASS_$_"; 
06676     Result += CDecl->getNameAsString();
06677     Result += ",\n\t";
06678     if (!rootClass) {
06679       Result += "0, // &"; Result += VarName;
06680       Result += CDecl->getSuperClass()->getNameAsString();
06681       Result += ",\n\t";
06682     }
06683     else 
06684       Result += "0,\n\t";
06685   }
06686   Result += "0, // (void *)&_objc_empty_cache,\n\t";
06687   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
06688   if (metaclass)
06689     Result += "&_OBJC_METACLASS_RO_$_";
06690   else
06691     Result += "&_OBJC_CLASS_RO_$_";
06692   Result += CDecl->getNameAsString();
06693   Result += ",\n};\n";
06694   
06695   // Add static function to initialize some of the meta-data fields.
06696   // avoid doing it twice.
06697   if (metaclass)
06698     return;
06699   
06700   const ObjCInterfaceDecl *SuperClass = 
06701     rootClass ? CDecl : CDecl->getSuperClass();
06702   
06703   Result += "static void OBJC_CLASS_SETUP_$_";
06704   Result += CDecl->getNameAsString();
06705   Result += "(void ) {\n";
06706   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
06707   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
06708   Result += RootClass->getNameAsString(); Result += ";\n";
06709   
06710   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
06711   Result += ".superclass = ";
06712   if (rootClass)
06713     Result += "&OBJC_CLASS_$_";
06714   else
06715      Result += "&OBJC_METACLASS_$_";
06716 
06717   Result += SuperClass->getNameAsString(); Result += ";\n";
06718   
06719   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
06720   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
06721   
06722   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
06723   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
06724   Result += CDecl->getNameAsString(); Result += ";\n";
06725   
06726   if (!rootClass) {
06727     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
06728     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
06729     Result += SuperClass->getNameAsString(); Result += ";\n";
06730   }
06731   
06732   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
06733   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
06734   Result += "}\n";
06735 }
06736 
06737 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, 
06738                              std::string &Result,
06739                              ObjCCategoryDecl *CatDecl,
06740                              ObjCInterfaceDecl *ClassDecl,
06741                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
06742                              ArrayRef<ObjCMethodDecl *> ClassMethods,
06743                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
06744                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
06745   StringRef CatName = CatDecl->getName();
06746   StringRef ClassName = ClassDecl->getName();
06747   // must declare an extern class object in case this class is not implemented 
06748   // in this TU.
06749   Result += "\n";
06750   Result += "extern \"C\" ";
06751   if (ClassDecl->getImplementation())
06752     Result += "__declspec(dllexport) ";
06753   else
06754     Result += "__declspec(dllimport) ";
06755   
06756   Result += "struct _class_t ";
06757   Result += "OBJC_CLASS_$_"; Result += ClassName;
06758   Result += ";\n";
06759   
06760   Result += "\nstatic struct _category_t ";
06761   Result += "_OBJC_$_CATEGORY_";
06762   Result += ClassName; Result += "_$_"; Result += CatName;
06763   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
06764   Result += "{\n";
06765   Result += "\t\""; Result += ClassName; Result += "\",\n";
06766   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
06767   Result += ",\n";
06768   if (InstanceMethods.size() > 0) {
06769     Result += "\t(const struct _method_list_t *)&";  
06770     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
06771     Result += ClassName; Result += "_$_"; Result += CatName;
06772     Result += ",\n";
06773   }
06774   else
06775     Result += "\t0,\n";
06776   
06777   if (ClassMethods.size() > 0) {
06778     Result += "\t(const struct _method_list_t *)&";  
06779     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
06780     Result += ClassName; Result += "_$_"; Result += CatName;
06781     Result += ",\n";
06782   }
06783   else
06784     Result += "\t0,\n";
06785   
06786   if (RefedProtocols.size() > 0) {
06787     Result += "\t(const struct _protocol_list_t *)&";  
06788     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
06789     Result += ClassName; Result += "_$_"; Result += CatName;
06790     Result += ",\n";
06791   }
06792   else
06793     Result += "\t0,\n";
06794   
06795   if (ClassProperties.size() > 0) {
06796     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
06797     Result += ClassName; Result += "_$_"; Result += CatName;
06798     Result += ",\n";
06799   }
06800   else
06801     Result += "\t0,\n";
06802   
06803   Result += "};\n";
06804   
06805   // Add static function to initialize the class pointer in the category structure.
06806   Result += "static void OBJC_CATEGORY_SETUP_$_";
06807   Result += ClassDecl->getNameAsString();
06808   Result += "_$_";
06809   Result += CatName;
06810   Result += "(void ) {\n";
06811   Result += "\t_OBJC_$_CATEGORY_"; 
06812   Result += ClassDecl->getNameAsString();
06813   Result += "_$_";
06814   Result += CatName;
06815   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
06816   Result += ";\n}\n";
06817 }
06818 
06819 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
06820                                            ASTContext *Context, std::string &Result,
06821                                            ArrayRef<ObjCMethodDecl *> Methods,
06822                                            StringRef VarName,
06823                                            StringRef ProtocolName) {
06824   if (Methods.size() == 0)
06825     return;
06826   
06827   Result += "\nstatic const char *";
06828   Result += VarName; Result += ProtocolName;
06829   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
06830   Result += "{\n";
06831   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
06832     ObjCMethodDecl *MD = Methods[i];
06833     std::string MethodTypeString, QuoteMethodTypeString;
06834     Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
06835     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
06836     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
06837     if (i == e-1)
06838       Result += "\n};\n";
06839     else {
06840       Result += ",\n";
06841     }
06842   }
06843 }
06844 
06845 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
06846                                 ASTContext *Context,
06847                                 std::string &Result, 
06848                                 ArrayRef<ObjCIvarDecl *> Ivars, 
06849                                 ObjCInterfaceDecl *CDecl) {
06850   // FIXME. visibilty of offset symbols may have to be set; for Darwin
06851   // this is what happens:
06852   /**
06853    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
06854        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
06855        Class->getVisibility() == HiddenVisibility)
06856      Visibility shoud be: HiddenVisibility;
06857    else
06858      Visibility shoud be: DefaultVisibility;
06859   */
06860   
06861   Result += "\n";
06862   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
06863     ObjCIvarDecl *IvarDecl = Ivars[i];
06864     if (Context->getLangOpts().MicrosoftExt)
06865       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
06866     
06867     if (!Context->getLangOpts().MicrosoftExt ||
06868         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
06869         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
06870       Result += "extern \"C\" unsigned long int "; 
06871     else
06872       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
06873     if (Ivars[i]->isBitField())
06874       RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
06875     else
06876       WriteInternalIvarName(CDecl, IvarDecl, Result);
06877     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
06878     Result += " = ";
06879     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
06880     Result += ";\n";
06881     if (Ivars[i]->isBitField()) {
06882       // skip over rest of the ivar bitfields.
06883       SKIP_BITFIELDS(i , e, Ivars);
06884     }
06885   }
06886 }
06887 
06888 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
06889                                            ASTContext *Context, std::string &Result,
06890                                            ArrayRef<ObjCIvarDecl *> OriginalIvars,
06891                                            StringRef VarName,
06892                                            ObjCInterfaceDecl *CDecl) {
06893   if (OriginalIvars.size() > 0) {
06894     Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
06895     SmallVector<ObjCIvarDecl *, 8> Ivars;
06896     // strip off all but the first ivar bitfield from each group of ivars.
06897     // Such ivars in the ivar list table will be replaced by their grouping struct
06898     // 'ivar'.
06899     for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
06900       if (OriginalIvars[i]->isBitField()) {
06901         Ivars.push_back(OriginalIvars[i]);
06902         // skip over rest of the ivar bitfields.
06903         SKIP_BITFIELDS(i , e, OriginalIvars);
06904       }
06905       else
06906         Ivars.push_back(OriginalIvars[i]);
06907     }
06908     
06909     Result += "\nstatic ";
06910     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
06911     Result += " "; Result += VarName;
06912     Result += CDecl->getNameAsString();
06913     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
06914     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
06915     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
06916     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
06917       ObjCIvarDecl *IvarDecl = Ivars[i];
06918       if (i == 0)
06919         Result += "\t{{";
06920       else
06921         Result += "\t {";
06922       Result += "(unsigned long int *)&";
06923       if (Ivars[i]->isBitField())
06924         RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
06925       else
06926         WriteInternalIvarName(CDecl, IvarDecl, Result);
06927       Result += ", ";
06928       
06929       Result += "\"";
06930       if (Ivars[i]->isBitField())
06931         RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
06932       else
06933         Result += IvarDecl->getName();
06934       Result += "\", ";
06935       
06936       QualType IVQT = IvarDecl->getType();
06937       if (IvarDecl->isBitField())
06938         IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
06939       
06940       std::string IvarTypeString, QuoteIvarTypeString;
06941       Context->getObjCEncodingForType(IVQT, IvarTypeString,
06942                                       IvarDecl);
06943       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
06944       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
06945       
06946       // FIXME. this alignment represents the host alignment and need be changed to
06947       // represent the target alignment.
06948       unsigned Align = Context->getTypeAlign(IVQT)/8;
06949       Align = llvm::Log2_32(Align);
06950       Result += llvm::utostr(Align); Result += ", ";
06951       CharUnits Size = Context->getTypeSizeInChars(IVQT);
06952       Result += llvm::utostr(Size.getQuantity());
06953       if (i  == e-1)
06954         Result += "}}\n";
06955       else
06956         Result += "},\n";
06957     }
06958     Result += "};\n";
06959   }
06960 }
06961 
06962 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
06963 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, 
06964                                                     std::string &Result) {
06965   
06966   // Do not synthesize the protocol more than once.
06967   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
06968     return;
06969   WriteModernMetadataDeclarations(Context, Result);
06970   
06971   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
06972     PDecl = Def;
06973   // Must write out all protocol definitions in current qualifier list,
06974   // and in their nested qualifiers before writing out current definition.
06975   for (auto *I : PDecl->protocols())
06976     RewriteObjCProtocolMetaData(I, Result);
06977   
06978   // Construct method lists.
06979   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
06980   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
06981   for (auto *MD : PDecl->instance_methods()) {
06982     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06983       OptInstanceMethods.push_back(MD);
06984     } else {
06985       InstanceMethods.push_back(MD);
06986     }
06987   }
06988   
06989   for (auto *MD : PDecl->class_methods()) {
06990     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06991       OptClassMethods.push_back(MD);
06992     } else {
06993       ClassMethods.push_back(MD);
06994     }
06995   }
06996   std::vector<ObjCMethodDecl *> AllMethods;
06997   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
06998     AllMethods.push_back(InstanceMethods[i]);
06999   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
07000     AllMethods.push_back(ClassMethods[i]);
07001   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
07002     AllMethods.push_back(OptInstanceMethods[i]);
07003   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
07004     AllMethods.push_back(OptClassMethods[i]);
07005 
07006   Write__extendedMethodTypes_initializer(*this, Context, Result,
07007                                          AllMethods,
07008                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
07009                                          PDecl->getNameAsString());
07010   // Protocol's super protocol list
07011   SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());  
07012   Write_protocol_list_initializer(Context, Result, SuperProtocols,
07013                                   "_OBJC_PROTOCOL_REFS_",
07014                                   PDecl->getNameAsString());
07015   
07016   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, 
07017                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
07018                                   PDecl->getNameAsString(), false);
07019   
07020   Write_method_list_t_initializer(*this, Context, Result, ClassMethods, 
07021                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
07022                                   PDecl->getNameAsString(), false);
07023 
07024   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, 
07025                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
07026                                   PDecl->getNameAsString(), false);
07027   
07028   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, 
07029                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
07030                                   PDecl->getNameAsString(), false);
07031   
07032   // Protocol's property metadata.
07033   SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
07034   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
07035                                  /* Container */nullptr,
07036                                  "_OBJC_PROTOCOL_PROPERTIES_",
07037                                  PDecl->getNameAsString());
07038 
07039   // Writer out root metadata for current protocol: struct _protocol_t
07040   Result += "\n";
07041   if (LangOpts.MicrosoftExt)
07042     Result += "static ";
07043   Result += "struct _protocol_t _OBJC_PROTOCOL_";
07044   Result += PDecl->getNameAsString();
07045   Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
07046   Result += "\t0,\n"; // id is; is null
07047   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
07048   if (SuperProtocols.size() > 0) {
07049     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
07050     Result += PDecl->getNameAsString(); Result += ",\n";
07051   }
07052   else
07053     Result += "\t0,\n";
07054   if (InstanceMethods.size() > 0) {
07055     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; 
07056     Result += PDecl->getNameAsString(); Result += ",\n";
07057   }
07058   else
07059     Result += "\t0,\n";
07060 
07061   if (ClassMethods.size() > 0) {
07062     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; 
07063     Result += PDecl->getNameAsString(); Result += ",\n";
07064   }
07065   else
07066     Result += "\t0,\n";
07067   
07068   if (OptInstanceMethods.size() > 0) {
07069     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; 
07070     Result += PDecl->getNameAsString(); Result += ",\n";
07071   }
07072   else
07073     Result += "\t0,\n";
07074   
07075   if (OptClassMethods.size() > 0) {
07076     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; 
07077     Result += PDecl->getNameAsString(); Result += ",\n";
07078   }
07079   else
07080     Result += "\t0,\n";
07081   
07082   if (ProtocolProperties.size() > 0) {
07083     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; 
07084     Result += PDecl->getNameAsString(); Result += ",\n";
07085   }
07086   else
07087     Result += "\t0,\n";
07088   
07089   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
07090   Result += "\t0,\n";
07091   
07092   if (AllMethods.size() > 0) {
07093     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
07094     Result += PDecl->getNameAsString();
07095     Result += "\n};\n";
07096   }
07097   else
07098     Result += "\t0\n};\n";
07099   
07100   if (LangOpts.MicrosoftExt)
07101     Result += "static ";
07102   Result += "struct _protocol_t *";
07103   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
07104   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
07105   Result += ";\n";
07106     
07107   // Mark this protocol as having been generated.
07108   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
07109     llvm_unreachable("protocol already synthesized");
07110   
07111 }
07112 
07113 void RewriteModernObjC::RewriteObjCProtocolListMetaData(
07114                                 const ObjCList<ObjCProtocolDecl> &Protocols,
07115                                 StringRef prefix, StringRef ClassName,
07116                                 std::string &Result) {
07117   if (Protocols.empty()) return;
07118   
07119   for (unsigned i = 0; i != Protocols.size(); i++)
07120     RewriteObjCProtocolMetaData(Protocols[i], Result);
07121   
07122   // Output the top lovel protocol meta-data for the class.
07123   /* struct _objc_protocol_list {
07124    struct _objc_protocol_list *next;
07125    int    protocol_count;
07126    struct _objc_protocol *class_protocols[];
07127    }
07128    */
07129   Result += "\n";
07130   if (LangOpts.MicrosoftExt)
07131     Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
07132   Result += "static struct {\n";
07133   Result += "\tstruct _objc_protocol_list *next;\n";
07134   Result += "\tint    protocol_count;\n";
07135   Result += "\tstruct _objc_protocol *class_protocols[";
07136   Result += utostr(Protocols.size());
07137   Result += "];\n} _OBJC_";
07138   Result += prefix;
07139   Result += "_PROTOCOLS_";
07140   Result += ClassName;
07141   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
07142   "{\n\t0, ";
07143   Result += utostr(Protocols.size());
07144   Result += "\n";
07145   
07146   Result += "\t,{&_OBJC_PROTOCOL_";
07147   Result += Protocols[0]->getNameAsString();
07148   Result += " \n";
07149   
07150   for (unsigned i = 1; i != Protocols.size(); i++) {
07151     Result += "\t ,&_OBJC_PROTOCOL_";
07152     Result += Protocols[i]->getNameAsString();
07153     Result += "\n";
07154   }
07155   Result += "\t }\n};\n";
07156 }
07157 
07158 /// hasObjCExceptionAttribute - Return true if this class or any super
07159 /// class has the __objc_exception__ attribute.
07160 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
07161 static bool hasObjCExceptionAttribute(ASTContext &Context,
07162                                       const ObjCInterfaceDecl *OID) {
07163   if (OID->hasAttr<ObjCExceptionAttr>())
07164     return true;
07165   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
07166     return hasObjCExceptionAttribute(Context, Super);
07167   return false;
07168 }
07169 
07170 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
07171                                            std::string &Result) {
07172   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
07173   
07174   // Explicitly declared @interface's are already synthesized.
07175   if (CDecl->isImplicitInterfaceDecl())
07176     assert(false && 
07177            "Legacy implicit interface rewriting not supported in moder abi");
07178   
07179   WriteModernMetadataDeclarations(Context, Result);
07180   SmallVector<ObjCIvarDecl *, 8> IVars;
07181   
07182   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
07183       IVD; IVD = IVD->getNextIvar()) {
07184     // Ignore unnamed bit-fields.
07185     if (!IVD->getDeclName())
07186       continue;
07187     IVars.push_back(IVD);
07188   }
07189   
07190   Write__ivar_list_t_initializer(*this, Context, Result, IVars, 
07191                                  "_OBJC_$_INSTANCE_VARIABLES_",
07192                                  CDecl);
07193   
07194   // Build _objc_method_list for class's instance methods if needed
07195   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
07196   
07197   // If any of our property implementations have associated getters or
07198   // setters, produce metadata for them as well.
07199   for (const auto *Prop : IDecl->property_impls()) {
07200     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
07201       continue;
07202     if (!Prop->getPropertyIvarDecl())
07203       continue;
07204     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
07205     if (!PD)
07206       continue;
07207     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
07208       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
07209         InstanceMethods.push_back(Getter);
07210     if (PD->isReadOnly())
07211       continue;
07212     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
07213       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
07214         InstanceMethods.push_back(Setter);
07215   }
07216   
07217   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
07218                                   "_OBJC_$_INSTANCE_METHODS_",
07219                                   IDecl->getNameAsString(), true);
07220   
07221   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
07222   
07223   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
07224                                   "_OBJC_$_CLASS_METHODS_",
07225                                   IDecl->getNameAsString(), true);
07226   
07227   // Protocols referenced in class declaration?
07228   // Protocol's super protocol list
07229   std::vector<ObjCProtocolDecl *> RefedProtocols;
07230   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
07231   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
07232        E = Protocols.end();
07233        I != E; ++I) {
07234     RefedProtocols.push_back(*I);
07235     // Must write out all protocol definitions in current qualifier list,
07236     // and in their nested qualifiers before writing out current definition.
07237     RewriteObjCProtocolMetaData(*I, Result);
07238   }
07239   
07240   Write_protocol_list_initializer(Context, Result, 
07241                                   RefedProtocols,
07242                                   "_OBJC_CLASS_PROTOCOLS_$_",
07243                                   IDecl->getNameAsString());
07244   
07245   // Protocol's property metadata.
07246   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
07247   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
07248                                  /* Container */IDecl,
07249                                  "_OBJC_$_PROP_LIST_",
07250                                  CDecl->getNameAsString());
07251 
07252   
07253   // Data for initializing _class_ro_t  metaclass meta-data
07254   uint32_t flags = CLS_META;
07255   std::string InstanceSize;
07256   std::string InstanceStart;
07257   
07258   
07259   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
07260   if (classIsHidden)
07261     flags |= OBJC2_CLS_HIDDEN;
07262   
07263   if (!CDecl->getSuperClass())
07264     // class is root
07265     flags |= CLS_ROOT;
07266   InstanceSize = "sizeof(struct _class_t)";
07267   InstanceStart = InstanceSize;
07268   Write__class_ro_t_initializer(Context, Result, flags, 
07269                                 InstanceStart, InstanceSize,
07270                                 ClassMethods,
07271                                 nullptr,
07272                                 nullptr,
07273                                 nullptr,
07274                                 "_OBJC_METACLASS_RO_$_",
07275                                 CDecl->getNameAsString());
07276 
07277   // Data for initializing _class_ro_t meta-data
07278   flags = CLS;
07279   if (classIsHidden)
07280     flags |= OBJC2_CLS_HIDDEN;
07281   
07282   if (hasObjCExceptionAttribute(*Context, CDecl))
07283     flags |= CLS_EXCEPTION;
07284 
07285   if (!CDecl->getSuperClass())
07286     // class is root
07287     flags |= CLS_ROOT;
07288   
07289   InstanceSize.clear();
07290   InstanceStart.clear();
07291   if (!ObjCSynthesizedStructs.count(CDecl)) {
07292     InstanceSize = "0";
07293     InstanceStart = "0";
07294   }
07295   else {
07296     InstanceSize = "sizeof(struct ";
07297     InstanceSize += CDecl->getNameAsString();
07298     InstanceSize += "_IMPL)";
07299     
07300     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
07301     if (IVD) {
07302       RewriteIvarOffsetComputation(IVD, InstanceStart);
07303     }
07304     else 
07305       InstanceStart = InstanceSize;
07306   }
07307   Write__class_ro_t_initializer(Context, Result, flags, 
07308                                 InstanceStart, InstanceSize,
07309                                 InstanceMethods,
07310                                 RefedProtocols,
07311                                 IVars,
07312                                 ClassProperties,
07313                                 "_OBJC_CLASS_RO_$_",
07314                                 CDecl->getNameAsString());
07315   
07316   Write_class_t(Context, Result,
07317                 "OBJC_METACLASS_$_",
07318                 CDecl, /*metaclass*/true);
07319   
07320   Write_class_t(Context, Result,
07321                 "OBJC_CLASS_$_",
07322                 CDecl, /*metaclass*/false);
07323   
07324   if (ImplementationIsNonLazy(IDecl))
07325     DefinedNonLazyClasses.push_back(CDecl);
07326                 
07327 }
07328 
07329 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
07330   int ClsDefCount = ClassImplementation.size();
07331   if (!ClsDefCount)
07332     return;
07333   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
07334   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
07335   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
07336   for (int i = 0; i < ClsDefCount; i++) {
07337     ObjCImplementationDecl *IDecl = ClassImplementation[i];
07338     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
07339     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
07340     Result  += CDecl->getName(); Result += ",\n";
07341   }
07342   Result += "};\n";
07343 }
07344 
07345 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
07346   int ClsDefCount = ClassImplementation.size();
07347   int CatDefCount = CategoryImplementation.size();
07348   
07349   // For each implemented class, write out all its meta data.
07350   for (int i = 0; i < ClsDefCount; i++)
07351     RewriteObjCClassMetaData(ClassImplementation[i], Result);
07352   
07353   RewriteClassSetupInitHook(Result);
07354   
07355   // For each implemented category, write out all its meta data.
07356   for (int i = 0; i < CatDefCount; i++)
07357     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
07358   
07359   RewriteCategorySetupInitHook(Result);
07360   
07361   if (ClsDefCount > 0) {
07362     if (LangOpts.MicrosoftExt)
07363       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
07364     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
07365     Result += llvm::utostr(ClsDefCount); Result += "]";
07366     Result += 
07367       " __attribute__((used, section (\"__DATA, __objc_classlist,"
07368       "regular,no_dead_strip\")))= {\n";
07369     for (int i = 0; i < ClsDefCount; i++) {
07370       Result += "\t&OBJC_CLASS_$_";
07371       Result += ClassImplementation[i]->getNameAsString();
07372       Result += ",\n";
07373     }
07374     Result += "};\n";
07375     
07376     if (!DefinedNonLazyClasses.empty()) {
07377       if (LangOpts.MicrosoftExt)
07378         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
07379       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
07380       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
07381         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
07382         Result += ",\n";
07383       }
07384       Result += "};\n";
07385     }
07386   }
07387   
07388   if (CatDefCount > 0) {
07389     if (LangOpts.MicrosoftExt)
07390       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
07391     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
07392     Result += llvm::utostr(CatDefCount); Result += "]";
07393     Result += 
07394     " __attribute__((used, section (\"__DATA, __objc_catlist,"
07395     "regular,no_dead_strip\")))= {\n";
07396     for (int i = 0; i < CatDefCount; i++) {
07397       Result += "\t&_OBJC_$_CATEGORY_";
07398       Result += 
07399         CategoryImplementation[i]->getClassInterface()->getNameAsString(); 
07400       Result += "_$_";
07401       Result += CategoryImplementation[i]->getNameAsString();
07402       Result += ",\n";
07403     }
07404     Result += "};\n";
07405   }
07406   
07407   if (!DefinedNonLazyCategories.empty()) {
07408     if (LangOpts.MicrosoftExt)
07409       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
07410     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
07411     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
07412       Result += "\t&_OBJC_$_CATEGORY_";
07413       Result += 
07414         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); 
07415       Result += "_$_";
07416       Result += DefinedNonLazyCategories[i]->getNameAsString();
07417       Result += ",\n";
07418     }
07419     Result += "};\n";
07420   }
07421 }
07422 
07423 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
07424   if (LangOpts.MicrosoftExt)
07425     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
07426   
07427   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
07428   // version 0, ObjCABI is 2
07429   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
07430 }
07431 
07432 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
07433 /// implementation.
07434 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
07435                                               std::string &Result) {
07436   WriteModernMetadataDeclarations(Context, Result);
07437   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
07438   // Find category declaration for this implementation.
07439   ObjCCategoryDecl *CDecl
07440     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
07441   
07442   std::string FullCategoryName = ClassDecl->getNameAsString();
07443   FullCategoryName += "_$_";
07444   FullCategoryName += CDecl->getNameAsString();
07445   
07446   // Build _objc_method_list for class's instance methods if needed
07447   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
07448   
07449   // If any of our property implementations have associated getters or
07450   // setters, produce metadata for them as well.
07451   for (const auto *Prop : IDecl->property_impls()) {
07452     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
07453       continue;
07454     if (!Prop->getPropertyIvarDecl())
07455       continue;
07456     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
07457     if (!PD)
07458       continue;
07459     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
07460       InstanceMethods.push_back(Getter);
07461     if (PD->isReadOnly())
07462       continue;
07463     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
07464       InstanceMethods.push_back(Setter);
07465   }
07466   
07467   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
07468                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
07469                                   FullCategoryName, true);
07470   
07471   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
07472   
07473   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
07474                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
07475                                   FullCategoryName, true);
07476   
07477   // Protocols referenced in class declaration?
07478   // Protocol's super protocol list
07479   SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
07480   for (auto *I : CDecl->protocols())
07481     // Must write out all protocol definitions in current qualifier list,
07482     // and in their nested qualifiers before writing out current definition.
07483     RewriteObjCProtocolMetaData(I, Result);
07484   
07485   Write_protocol_list_initializer(Context, Result, 
07486                                   RefedProtocols,
07487                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
07488                                   FullCategoryName);
07489   
07490   // Protocol's property metadata.
07491   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
07492   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
07493                                 /* Container */IDecl,
07494                                 "_OBJC_$_PROP_LIST_",
07495                                 FullCategoryName);
07496   
07497   Write_category_t(*this, Context, Result,
07498                    CDecl,
07499                    ClassDecl,
07500                    InstanceMethods,
07501                    ClassMethods,
07502                    RefedProtocols,
07503                    ClassProperties);
07504   
07505   // Determine if this category is also "non-lazy".
07506   if (ImplementationIsNonLazy(IDecl))
07507     DefinedNonLazyCategories.push_back(CDecl);
07508     
07509 }
07510 
07511 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
07512   int CatDefCount = CategoryImplementation.size();
07513   if (!CatDefCount)
07514     return;
07515   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
07516   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
07517   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
07518   for (int i = 0; i < CatDefCount; i++) {
07519     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
07520     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
07521     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
07522     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
07523     Result += ClassDecl->getName();
07524     Result += "_$_";
07525     Result += CatDecl->getName();
07526     Result += ",\n";
07527   }
07528   Result += "};\n";
07529 }
07530 
07531 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
07532 /// class methods.
07533 template<typename MethodIterator>
07534 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
07535                                              MethodIterator MethodEnd,
07536                                              bool IsInstanceMethod,
07537                                              StringRef prefix,
07538                                              StringRef ClassName,
07539                                              std::string &Result) {
07540   if (MethodBegin == MethodEnd) return;
07541   
07542   if (!objc_impl_method) {
07543     /* struct _objc_method {
07544      SEL _cmd;
07545      char *method_types;
07546      void *_imp;
07547      }
07548      */
07549     Result += "\nstruct _objc_method {\n";
07550     Result += "\tSEL _cmd;\n";
07551     Result += "\tchar *method_types;\n";
07552     Result += "\tvoid *_imp;\n";
07553     Result += "};\n";
07554     
07555     objc_impl_method = true;
07556   }
07557   
07558   // Build _objc_method_list for class's methods if needed
07559   
07560   /* struct  {
07561    struct _objc_method_list *next_method;
07562    int method_count;
07563    struct _objc_method method_list[];
07564    }
07565    */
07566   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
07567   Result += "\n";
07568   if (LangOpts.MicrosoftExt) {
07569     if (IsInstanceMethod)
07570       Result += "__declspec(allocate(\".inst_meth$B\")) ";
07571     else
07572       Result += "__declspec(allocate(\".cls_meth$B\")) ";
07573   }
07574   Result += "static struct {\n";
07575   Result += "\tstruct _objc_method_list *next_method;\n";
07576   Result += "\tint method_count;\n";
07577   Result += "\tstruct _objc_method method_list[";
07578   Result += utostr(NumMethods);
07579   Result += "];\n} _OBJC_";
07580   Result += prefix;
07581   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
07582   Result += "_METHODS_";
07583   Result += ClassName;
07584   Result += " __attribute__ ((used, section (\"__OBJC, __";
07585   Result += IsInstanceMethod ? "inst" : "cls";
07586   Result += "_meth\")))= ";
07587   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
07588   
07589   Result += "\t,{{(SEL)\"";
07590   Result += (*MethodBegin)->getSelector().getAsString().c_str();
07591   std::string MethodTypeString;
07592   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
07593   Result += "\", \"";
07594   Result += MethodTypeString;
07595   Result += "\", (void *)";
07596   Result += MethodInternalNames[*MethodBegin];
07597   Result += "}\n";
07598   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
07599     Result += "\t  ,{(SEL)\"";
07600     Result += (*MethodBegin)->getSelector().getAsString().c_str();
07601     std::string MethodTypeString;
07602     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
07603     Result += "\", \"";
07604     Result += MethodTypeString;
07605     Result += "\", (void *)";
07606     Result += MethodInternalNames[*MethodBegin];
07607     Result += "}\n";
07608   }
07609   Result += "\t }\n};\n";
07610 }
07611 
07612 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
07613   SourceRange OldRange = IV->getSourceRange();
07614   Expr *BaseExpr = IV->getBase();
07615   
07616   // Rewrite the base, but without actually doing replaces.
07617   {
07618     DisableReplaceStmtScope S(*this);
07619     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
07620     IV->setBase(BaseExpr);
07621   }
07622   
07623   ObjCIvarDecl *D = IV->getDecl();
07624   
07625   Expr *Replacement = IV;
07626   
07627     if (BaseExpr->getType()->isObjCObjectPointerType()) {
07628       const ObjCInterfaceType *iFaceDecl =
07629         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
07630       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
07631       // lookup which class implements the instance variable.
07632       ObjCInterfaceDecl *clsDeclared = nullptr;
07633       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
07634                                                    clsDeclared);
07635       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
07636       
07637       // Build name of symbol holding ivar offset.
07638       std::string IvarOffsetName;
07639       if (D->isBitField())
07640         ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
07641       else
07642         WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
07643       
07644       ReferencedIvars[clsDeclared].insert(D);
07645       
07646       // cast offset to "char *".
07647       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, 
07648                                                     Context->getPointerType(Context->CharTy),
07649                                                     CK_BitCast,
07650                                                     BaseExpr);
07651       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
07652                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
07653                                        Context->UnsignedLongTy, nullptr,
07654                                        SC_Extern);
07655       DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
07656                                                    Context->UnsignedLongTy, VK_LValue,
07657                                                    SourceLocation());
07658       BinaryOperator *addExpr = 
07659         new (Context) BinaryOperator(castExpr, DRE, BO_Add, 
07660                                      Context->getPointerType(Context->CharTy),
07661                                      VK_RValue, OK_Ordinary, SourceLocation(), false);
07662       // Don't forget the parens to enforce the proper binding.
07663       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
07664                                               SourceLocation(),
07665                                               addExpr);
07666       QualType IvarT = D->getType();
07667       if (D->isBitField())
07668         IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
07669 
07670       if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
07671         RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
07672         RD = RD->getDefinition();
07673         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
07674           // decltype(((Foo_IMPL*)0)->bar) *
07675           ObjCContainerDecl *CDecl = 
07676             dyn_cast<ObjCContainerDecl>(D->getDeclContext());
07677           // ivar in class extensions requires special treatment.
07678           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
07679             CDecl = CatDecl->getClassInterface();
07680           std::string RecName = CDecl->getName();
07681           RecName += "_IMPL";
07682           RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
07683                                               SourceLocation(), SourceLocation(),
07684                                               &Context->Idents.get(RecName.c_str()));
07685           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
07686           unsigned UnsignedIntSize = 
07687             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
07688           Expr *Zero = IntegerLiteral::Create(*Context,
07689                                               llvm::APInt(UnsignedIntSize, 0),
07690                                               Context->UnsignedIntTy, SourceLocation());
07691           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
07692           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
07693                                                   Zero);
07694           FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
07695                                             SourceLocation(),
07696                                             &Context->Idents.get(D->getNameAsString()),
07697                                             IvarT, nullptr,
07698                                             /*BitWidth=*/nullptr,
07699                                             /*Mutable=*/true, ICIS_NoInit);
07700           MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
07701                                                     FD->getType(), VK_LValue,
07702                                                     OK_Ordinary);
07703           IvarT = Context->getDecltypeType(ME, ME->getType());
07704         }
07705       }
07706       convertObjCTypeToCStyleType(IvarT);
07707       QualType castT = Context->getPointerType(IvarT);
07708           
07709       castExpr = NoTypeInfoCStyleCastExpr(Context, 
07710                                           castT,
07711                                           CK_BitCast,
07712                                           PE);
07713       
07714       
07715       Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
07716                                               VK_LValue, OK_Ordinary,
07717                                               SourceLocation());
07718       PE = new (Context) ParenExpr(OldRange.getBegin(),
07719                                    OldRange.getEnd(),
07720                                    Exp);
07721       
07722       if (D->isBitField()) {
07723         FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
07724                                           SourceLocation(),
07725                                           &Context->Idents.get(D->getNameAsString()),
07726                                           D->getType(), nullptr,
07727                                           /*BitWidth=*/D->getBitWidth(),
07728                                           /*Mutable=*/true, ICIS_NoInit);
07729         MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
07730                                                   FD->getType(), VK_LValue,
07731                                                   OK_Ordinary);
07732         Replacement = ME;
07733 
07734       }
07735       else
07736         Replacement = PE;
07737     }
07738   
07739     ReplaceStmtWithRange(IV, Replacement, OldRange);
07740     return Replacement;  
07741 }
07742 
07743 #endif