RewriteObjC.cpp revision 42f1e658765b0b3e069f52726da23517a466c582
1b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroff//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
277cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//
377cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//                     The LLVM Compiler Infrastructure
477cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
777cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//
877cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//===----------------------------------------------------------------------===//
977cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//
1077cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner// Hacks and fun related to the code rewriter.
1177cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//
1277cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner//===----------------------------------------------------------------------===//
1377cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner
149b414d3e2d0cb84512b55a3275a98490b090162aDaniel Dunbar#include "clang/Rewrite/ASTConsumers.h"
158a12c2777cccdf629b89745b6ecc89a8c1641e4eChris Lattner#include "clang/Rewrite/Rewriter.h"
1677cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner#include "clang/AST/AST.h"
1777cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner#include "clang/AST/ASTConsumer.h"
188599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff#include "clang/AST/ParentMap.h"
198a12c2777cccdf629b89745b6ecc89a8c1641e4eChris Lattner#include "clang/Basic/SourceManager.h"
20ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff#include "clang/Basic/IdentifierTable.h"
210750618b0beacdc9b0a9e210a661e4746823ced7Chris Lattner#include "clang/Basic/Diagnostic.h"
2226de4655a38b899e0f0dcef4175032175854d1cfChris Lattner#include "clang/Lex/Lexer.h"
236cb7c1a43b0c8f739d1f54b7fdae5ede86033496Benjamin Kramer#include "llvm/Support/MemoryBuffer.h"
246cb7c1a43b0c8f739d1f54b7fdae5ede86033496Benjamin Kramer#include "llvm/Support/raw_ostream.h"
25158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner#include "llvm/ADT/StringExtras.h"
2626e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian#include "llvm/ADT/SmallPtrSet.h"
27a95d3750441ac8ad03e36af8e6e74039c9a3109dTed Kremenek#include "llvm/ADT/OwningPtr.h"
28ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian#include "llvm/ADT/DenseSet.h"
2972952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian
3077cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattnerusing namespace clang;
31158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattnerusing llvm::utostr;
3277cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner
3377cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattnernamespace {
34b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroff  class RewriteObjC : public ASTConsumer {
3573e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian    enum {
3659b173d81b05b7d10cec8b06b3fd843230ef628cNico Weber      BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
3773e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian                                        block, ... */
3873e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
3973e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
4073e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian                                        __block variable */
4159b173d81b05b7d10cec8b06b3fd843230ef628cNico Weber      BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
4273e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian                                        helpers */
4359b173d81b05b7d10cec8b06b3fd843230ef628cNico Weber      BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
4473e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian                                        support routines */
4573e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_BYREF_CURRENT_MAX = 256
4673e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian    };
4773e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian
4873e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian    enum {
4973e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_NEEDS_FREE =        (1 << 24),
5073e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
5173e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_HAS_CXX_OBJ =       (1 << 26),
5273e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_IS_GC =             (1 << 27),
5373e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_IS_GLOBAL =         (1 << 28),
5473e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      BLOCK_HAS_DESCRIPTOR =    (1 << 29)
5573e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian    };
5673e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian
572c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner    Rewriter Rewrite;
58e365c50a21cb02e0219433db0c4461566ad4a597Chris Lattner    Diagnostic &Diags;
594f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff    const LangOptions &LangOpts;
60f69cc5d6606fc65a76e3acd6eb6e13efd0098295Steve Naroff    unsigned RewriteFailedDiag;
618c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff    unsigned TryFinallyContainsReturnDiag;
621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6301c5748c29e75b29cab5fc7d8ad1b173b29c7ecfChris Lattner    ASTContext *Context;
6477cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner    SourceManager *SM;
65ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis    TranslationUnitDecl *TUDecl;
662b2453a7d8fe732561795431f39ceb2b2a832d84Chris Lattner    FileID MainFileID;
6726de4655a38b899e0f0dcef4175032175854d1cfChris Lattner    const char *MainFileStart, *MainFileEnd;
682c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner    SourceLocation LastIncLoc;
691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
70a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
73fbfe82527dadb09c95609a742744d75a2322850cSteve Naroff    llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
74a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
76e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian    llvm::SmallVector<Stmt *, 32> Stmts;
77e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian    llvm::SmallVector<int, 8> ObjCBcLabelNo;
78621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    // Remember all the @protocol(<expr>) expressions.
79621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
80ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian
81ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    llvm::DenseSet<uint64_t> CopyDestroyCache;
82ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian
83d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    unsigned NumObjCStringLiterals;
841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
85ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff    FunctionDecl *MsgSendFunctionDecl;
86874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    FunctionDecl *MsgSendSuperFunctionDecl;
8780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    FunctionDecl *MsgSendStretFunctionDecl;
8880a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    FunctionDecl *MsgSendSuperStretFunctionDecl;
89acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian    FunctionDecl *MsgSendFpretFunctionDecl;
90ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff    FunctionDecl *GetClassFunctionDecl;
919bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff    FunctionDecl *GetMetaClassFunctionDecl;
92d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian    FunctionDecl *GetSuperClassFunctionDecl;
93934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff    FunctionDecl *SelGetUidFunctionDecl;
949698464266660346fa2da1bddc3e6404a9819b25Steve Naroff    FunctionDecl *CFStringFunctionDecl;
95c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff    FunctionDecl *SuperContructorFunctionDecl;
961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
97beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff    // ObjC string constant support.
98248a753f6b670692523c99afaeb8fe98f7ae3ca7Steve Naroff    VarDecl *ConstantStringClassReference;
99beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff    RecordDecl *NSStringRecord;
1001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
101b586cce95c69161c771f7a966383beb4fc5dd394Fariborz Jahanian    // ObjC foreach break/continue generation support.
102e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian    int BcLabelCount;
1031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
104874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    // Needed for super.
10554055232a5ddb9529726e934301b125cb720a273Steve Naroff    ObjCMethodDecl *CurMethodDef;
106874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    RecordDecl *SuperStructDecl;
107d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    RecordDecl *ConstantStringDecl;
1081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
109621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    TypeDecl *ProtocolTypeDecl;
110621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    QualType getProtocolType();
1111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
112b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian    // Needed for header files being rewritten
113b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian    bool IsHeader;
1141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
115a7b402dc258bf38ab5e206dbf4916a69d3ee3cc8Steve Naroff    std::string InFileName;
11666d6f048471aad6daf67b3ea804b54fbea72a076Eli Friedman    llvm::raw_ostream* OutFile;
117c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman
118c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman    bool SilenceRewriteMacroWarning;
119f292fcf6bd5118499a830e0950429effeb373c28Fariborz Jahanian    bool objc_impl_method;
120c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman
121ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff    std::string Preamble;
12254055232a5ddb9529726e934301b125cb720a273Steve Naroff
12354055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Block expressions.
12454055232a5ddb9529726e934301b125cb720a273Steve Naroff    llvm::SmallVector<BlockExpr *, 32> Blocks;
1255e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    llvm::SmallVector<int, 32> InnerDeclRefsCount;
1265e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
1275e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
12854055232a5ddb9529726e934301b125cb720a273Steve Naroff    llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
1291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13054055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Block related declarations.
131bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
13654055232a5ddb9529726e934301b125cb720a273Steve Naroff    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
1376cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
1386cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian
13954055232a5ddb9529726e934301b125cb720a273Steve Naroff    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
14054055232a5ddb9529726e934301b125cb720a273Steve Naroff
141c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    // This maps a property to it's assignment statement.
142f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
1438599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    // This maps a property to it's synthesied message expression.
1448599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    // This allows us to rewrite chained getters (e.g. o.a.b.c).
145f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    llvm::DenseMap<Expr *, Stmt *> PropGetters;
1461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1474c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff    // This maps an original source AST to it's rewritten form. This allows
1484c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff    // us to avoid rewriting the same node twice (which is very uncommon).
1494c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff    // This is needed to support some of the exotic property rewriting.
1504c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
15115f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff
15254055232a5ddb9529726e934301b125cb720a273Steve Naroff    FunctionDecl *CurFunctionDef;
153abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    FunctionDecl *CurFunctionDeclToDeclareForBlock;
1548e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    VarDecl *GlobalVarDecl;
1551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
156b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff    bool DisableReplaceStmt;
1571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1587e7492442f32e3abbe246f6bb35568b044c1188bNick Lewycky    static const int OBJC_ABI_VERSION = 7;
15977cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner  public:
160e3a6198400453c0d9623207718e4942f7c111f87Ted Kremenek    virtual void Initialize(ASTContext &context);
161e3a6198400453c0d9623207718e4942f7c111f87Ted Kremenek
162f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner    // Top Level Driver code.
163682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner    virtual void HandleTopLevelDecl(DeclGroupRef D) {
164682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner        HandleTopLevelSingleDecl(*I);
166682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner    }
167682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner    void HandleTopLevelSingleDecl(Decl *D);
1682c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner    void HandleDeclInMainFile(Decl *D);
16966d6f048471aad6daf67b3ea804b54fbea72a076Eli Friedman    RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
170c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                Diagnostic &D, const LangOptions &LOpts,
171c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                bool silenceMacroWarn);
172e452e0ffc81c6c3d79680f552f2623e6cf0956d7Ted Kremenek
173e452e0ffc81c6c3d79680f552f2623e6cf0956d7Ted Kremenek    ~RewriteObjC() {}
1741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
175dacbc5d46aaeea817742b8c76c987b87d2490c85Chris Lattner    virtual void HandleTranslationUnit(ASTContext &C);
1761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17788906cddbb1d5b3a868eeeec6cb170befc829c2fFariborz Jahanian    void ReplaceStmt(Stmt *Old, Stmt *New) {
1784c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      Stmt *ReplacingStmt = ReplacedNodes[Old];
1791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1804c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      if (ReplacingStmt)
1814c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff        return; // We can't rewrite the same node twice.
1824c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff
183b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      if (DisableReplaceStmt)
184b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        return; // Used when rewriting the assignment of a property setter.
185b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff
186f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner      // If replacement succeeded or warning disabled return with no warning.
18788906cddbb1d5b3a868eeeec6cb170befc829c2fFariborz Jahanian      if (!Rewrite.ReplaceStmt(Old, New)) {
1884c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff        ReplacedNodes[Old] = New;
1894c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff        return;
1904c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      }
1914c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      if (SilenceRewriteMacroWarning)
192dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner        return;
1930a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner      Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
1940a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner                   << Old->getSourceRange();
195dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner    }
196b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff
197b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
1987e7492442f32e3abbe246f6bb35568b044c1188bNick Lewycky      // Measure the old text.
199b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      int Size = Rewrite.getRangeSize(SrcRange);
200b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      if (Size == -1) {
201b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff                     << Old->getSourceRange();
203b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        return;
204b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      }
205b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      // Get the new text.
206b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      std::string SStr;
207b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      llvm::raw_string_ostream S(SStr);
208e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner      New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
209b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      const std::string &Str = S.str();
210b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff
211b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      // If replacement succeeded or warning disabled return with no warning.
212d7407dc92c7d19cafce429e7e1cf9819d3fc0b92Daniel Dunbar      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
213b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        ReplacedNodes[Old] = New;
214b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        return;
215b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      }
216b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      if (SilenceRewriteMacroWarning)
217b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff        return;
218b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff                   << Old->getSourceRange();
220b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff    }
221b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff
222d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    void InsertText(SourceLocation Loc, llvm::StringRef Str,
223ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff                    bool InsertAfter = true) {
224aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner      // If insertion succeeded or warning disabled return with no warning.
225d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
226f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner          SilenceRewriteMacroWarning)
227f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner        return;
2281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
229f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner    }
2311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
232aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner    void ReplaceText(SourceLocation Start, unsigned OrigLength,
233d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer                     llvm::StringRef Str) {
234aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner      // If removal succeeded or warning disabled return with no warning.
235d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
236aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner          SilenceRewriteMacroWarning)
237aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner        return;
2381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
239aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240aadaf78d65daef3ac1b45e4ad6136ce859962fe2Chris Lattner    }
2411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
242f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner    // Syntactic Rewriting.
243452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian    void RewriteInclude();
244a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
245a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff                                 ObjCImplementationDecl *IMD,
247a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff                                 ObjCCategoryImplDecl *CID);
248a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
2494afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor    void RewriteImplementationDecl(Decl *Dcl);
2502d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
2512d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian                               ObjCMethodDecl *MDecl, std::string &ResultStr);
2527c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
2537c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian                               const FunctionType *&FPRetType);
254a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
2551e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian                            ValueDecl *VD, bool def=false);
256a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
2606327e0d55c590b3c2766fa76ef1db241a0467df2Steve Naroff    void RewriteProperty(ObjCPropertyDecl *prop);
26109b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    void RewriteFunctionDecl(FunctionDecl *FD);
262fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar    void RewriteBlockPointerType(std::string& Str, QualType Type);
263fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
264abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
265a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
2664c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    void RewriteTypeOfDecl(VarDecl *VD);
2674f95b750534f2111f28434b282bcbd5656002816Steve Naroff    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
268d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    bool needToScanForQualifiers(QualType T);
269874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    QualType getSuperStructType();
270d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    QualType getConstantStringStructType();
2711f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
272baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
2731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
274f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner    // Expression Rewriting.
275f3473a7e48dfaaa88f58dd9304856e16754f9b1cSteve Naroff    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
276c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    void CollectPropertySetters(Stmt *S);
2771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2788599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    Stmt *CurrentBody;
2798599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    ParentMap *PropParentMap; // created lazily.
2801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
281e64b7771dca65d737dfc49b6137bd69fc1ff6bd2Chris Lattner    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
2822b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
2832b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian                                 bool &replaced);
2842b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
285f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
287b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff                                SourceRange SrcRange);
288b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
289e64b7771dca65d737dfc49b6137bd69fc1ff6bd2Chris Lattner    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
290beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
29136ee2cb3247a662b6049f9cc097ba5cf9c0bb2b5Fariborz Jahanian    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
292b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    void WarnAboutReturnGotoStmts(Stmt *S);
293b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    void HasReturnStmts(Stmt *S, bool &hasReturns);
294b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    void RewriteTryReturnStmts(Stmt *S);
295b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    void RewriteSyncReturnStmts(Stmt *S, std::string buf);
296a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
297a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
298a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
299338d1e2ced8037b71d91fb319631846917d0cedaChris Lattner    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300338d1e2ced8037b71d91fb319631846917d0cedaChris Lattner                                       SourceLocation OrigEnd);
30142f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
3021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
3031d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                      Expr **args, unsigned nargs,
3041d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                      SourceLocation StartLoc=SourceLocation(),
3051d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                      SourceLocation EndLoc=SourceLocation());
3061d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
3071d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                           SourceLocation StartLoc=SourceLocation(),
3081d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                           SourceLocation EndLoc=SourceLocation());
309e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian    Stmt *RewriteBreakStmt(BreakStmt *S);
310e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian    Stmt *RewriteContinueStmt(ContinueStmt *S);
31133b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian    void SynthCountByEnumWithState(std::string &buf);
3121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
31309b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    void SynthMsgSendFunctionDecl();
314874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    void SynthMsgSendSuperFunctionDecl();
31580a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    void SynthMsgSendStretFunctionDecl();
316acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian    void SynthMsgSendFpretFunctionDecl();
31780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    void SynthMsgSendSuperStretFunctionDecl();
31809b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    void SynthGetClassFunctionDecl();
3199bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff    void SynthGetMetaClassFunctionDecl();
320d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian    void SynthGetSuperClassFunctionDecl();
321a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian    void SynthSelGetUidFunctionDecl();
322c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff    void SynthSuperContructorFunctionDecl();
3231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
324f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner    // Metadata emission.
325a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
326ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian                                  std::string &Result);
3271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
328a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
329ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian                                     std::string &Result);
3301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
331653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    template<typename MethodIterator>
332653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor                                    MethodIterator MethodEnd,
3348e991ba2e256e56959a65a049e161aa30b3c0decFariborz Jahanian                                    bool IsInstanceMethod,
3354087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                    llvm::StringRef prefix,
3364087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                    llvm::StringRef ClassName,
337158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner                                    std::string &Result);
3381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
339621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
3404087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                     llvm::StringRef prefix,
3414087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                     llvm::StringRef ClassName,
342621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff                                     std::string &Result);
343621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
3444087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                         llvm::StringRef prefix,
3454087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                         llvm::StringRef ClassName,
346621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff                                         std::string &Result);
347a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
34826e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian                                      std::string &Result);
3492d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
35026e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian                                         std::string &Result);
351ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff    void RewriteImplementations();
352ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff    void SynthesizeMetaDataIntoBuffer(std::string &Result);
3531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
35454055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Block rewriting.
3551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
35654055232a5ddb9529726e934301b125cb720a273Steve Naroff    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
3571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
35854055232a5ddb9529726e934301b125cb720a273Steve Naroff    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
35954055232a5ddb9529726e934301b125cb720a273Steve Naroff    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
3601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // Block specific rewrite rules.
36254055232a5ddb9529726e934301b125cb720a273Steve Naroff    void RewriteBlockPointerDecl(NamedDecl *VD);
36352b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian    void RewriteByRefVar(VarDecl *VD);
364ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
365f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    Stmt *RewriteBlockDeclRefExpr(Expr *VD);
3666cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
36754055232a5ddb9529726e934301b125cb720a273Steve Naroff    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
3681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3704087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                      llvm::StringRef funcName, std::string Tag);
3711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
3724087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                      llvm::StringRef funcName, std::string Tag);
37301aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    std::string SynthesizeBlockImpl(BlockExpr *CE,
37401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                    std::string Tag, std::string Desc);
37501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    std::string SynthesizeBlockDescriptor(std::string DescTag,
37601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                          std::string ImplTag,
3774087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                          int i, llvm::StringRef funcName,
37801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                          unsigned hasCopy);
3798a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
38054055232a5ddb9529726e934301b125cb720a273Steve Naroff    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
3814087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                 llvm::StringRef FunName);
3823d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    void RewriteRecordBody(RecordDecl *RD);
3831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
38454055232a5ddb9529726e934301b125cb720a273Steve Naroff    void CollectBlockDeclRefInfo(BlockExpr *Exp);
38554055232a5ddb9529726e934301b125cb720a273Steve Naroff    void GetBlockDeclRefExprs(Stmt *S);
3865e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    void GetInnerBlockDeclRefExprs(Stmt *S,
3875e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian                llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
38872952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian                llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
3891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
39054055232a5ddb9529726e934301b125cb720a273Steve Naroff    // We avoid calling Type::isBlockPointerType(), since it operates on the
39154055232a5ddb9529726e934301b125cb720a273Steve Naroff    // canonical type. We only care if the top-level type is a closure pointer.
3928189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    bool isTopLevelBlockPointerType(QualType T) {
3938189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek      return isa<BlockPointerType>(T);
3948189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    }
3951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3964fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
3974fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    /// to a function pointer type and upon success, returns true; false
3984fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    /// otherwise.
3994fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    bool convertBlockPointerToFunctionPointer(QualType &T) {
4004fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      if (isTopLevelBlockPointerType(T)) {
4014fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian        const BlockPointerType *BPT = T->getAs<BlockPointerType>();
4024fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian        T = Context->getPointerType(BPT->getPointeeType());
4034fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian        return true;
4044fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      }
4054fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      return false;
4064fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    }
4074fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian
4088188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian    void convertToUnqualifiedObjCType(QualType &T) {
4098188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian      if (T->isObjCQualifiedIdType())
4108188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian        T = Context->getObjCIdType();
4118188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian      else if (T->isObjCQualifiedClassType())
4128188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian        T = Context->getObjCClassType();
4138188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian      else if (T->isObjCObjectPointerType() &&
4148188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian               T->getPointeeType()->isObjCQualifiedInterfaceType())
4158188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian        T = Context->getObjCIdType();
4168188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian    }
4178188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian
41854055232a5ddb9529726e934301b125cb720a273Steve Naroff    // FIXME: This predicate seems like it would be useful to add to ASTContext.
41954055232a5ddb9529726e934301b125cb720a273Steve Naroff    bool isObjCType(QualType T) {
42054055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
42154055232a5ddb9529726e934301b125cb720a273Steve Naroff        return false;
4221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
42354055232a5ddb9529726e934301b125cb720a273Steve Naroff      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
4241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
42554055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
42654055232a5ddb9529726e934301b125cb720a273Steve Naroff          OCT == Context->getCanonicalType(Context->getObjCClassType()))
42754055232a5ddb9529726e934301b125cb720a273Steve Naroff        return true;
4281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4296217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek      if (const PointerType *PT = OCT->getAs<PointerType>()) {
4301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
431d1b3c2dd5bc1f3103bee6137957aa7c5f8f2f0bcSteve Naroff            PT->getPointeeType()->isObjCQualifiedIdType())
43254055232a5ddb9529726e934301b125cb720a273Steve Naroff          return true;
43354055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
43454055232a5ddb9529726e934301b125cb720a273Steve Naroff      return false;
43554055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
43654055232a5ddb9529726e934301b125cb720a273Steve Naroff    bool PointerTypeTakesAnyBlockArguments(QualType QT);
437e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
4388189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    void GetExtentOfArgList(const char *Name, const char *&LParen,
4398189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                            const char *&RParen);
440b2f9e516327310d95840d442416084508f80c183Steve Naroff    void RewriteCastExpr(CStyleCastExpr *CE);
4411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4424087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
4435e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
4445e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian            const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
4451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
446621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    void QuoteDoublequotes(std::string &From, std::string &To) {
4471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      for (unsigned i = 0; i < From.length(); i++) {
448621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        if (From[i] == '"')
449621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff          To += "\\\"";
450621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        else
451621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff          To += From[i];
452621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      }
453621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    }
454e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall
455e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    QualType getSimpleFunctionType(QualType result,
456e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                   const QualType *args,
457e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                   unsigned numArgs,
458e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                   bool variadic = false) {
459e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      FunctionProtoType::ExtProtoInfo fpi;
460e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      fpi.Variadic = variadic;
461e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      return Context->getFunctionType(result, args, numArgs, fpi);
462e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    }
46377cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner  };
4649d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall
4659d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  // Helper function: create a CStyleCastExpr with trivial type source info.
4669d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
4672de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall                                           CastKind Kind, Expr *E) {
4689d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall    TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
469f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall    return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
470f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall                                  SourceLocation(), SourceLocation());
4719d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  }
47277cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner}
47377cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner
4741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
4751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                   NamedDecl *D) {
476f4c7371fb1d3cebcfb40abad4537bb82515704eaJohn McCall  if (const FunctionProtoType *fproto
477723df245307a530da5433dfb43accf187dc3e243Abramo Bagnara      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
4781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
47954055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = fproto->arg_type_end(); I && (I != E); ++I)
48001f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      if (isTopLevelBlockPointerType(*I)) {
48154055232a5ddb9529726e934301b125cb720a273Steve Naroff        // All the args are checked/rewritten. Don't call twice!
48254055232a5ddb9529726e934301b125cb720a273Steve Naroff        RewriteBlockPointerDecl(D);
48354055232a5ddb9529726e934301b125cb720a273Steve Naroff        break;
48454055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
48554055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
48654055232a5ddb9529726e934301b125cb720a273Steve Naroff}
48754055232a5ddb9529726e934301b125cb720a273Steve Naroff
48854055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
4896217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek  const PointerType *PT = funcType->getAs<PointerType>();
49054055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
49172564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
49254055232a5ddb9529726e934301b125cb720a273Steve Naroff}
49354055232a5ddb9529726e934301b125cb720a273Steve Naroff
494b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanianstatic bool IsHeaderFile(const std::string &Filename) {
495b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  std::string::size_type DotPos = Filename.rfind('.');
4961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
497b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  if (DotPos == std::string::npos) {
498b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian    // no file extension
4991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return false;
500b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  }
5011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
502b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
503b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  // C header: .h
504b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  // C++ header: .hh or .H;
505b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian  return Ext == "h" || Ext == "hh" || Ext == "H";
5061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
507b4b2f0c9e80c6613c3e9846da121632ea39bcd5dFariborz Jahanian
50866d6f048471aad6daf67b3ea804b54fbea72a076Eli FriedmanRewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
509c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                         Diagnostic &D, const LangOptions &LOpts,
510c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                         bool silenceMacroWarn)
511c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman      : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
512c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman        SilenceRewriteMacroWarning(silenceMacroWarn) {
513a7b402dc258bf38ab5e206dbf4916a69d3ee3cc8Steve Naroff  IsHeader = IsHeaderFile(inFile);
5141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
515a7b402dc258bf38ab5e206dbf4916a69d3ee3cc8Steve Naroff               "rewriting sub-expression within a macro (may not be correct)");
5161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
5178189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek               "rewriter doesn't support user-specified control flow semantics "
5188189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek               "for @try/@finally (code may not execute properly)");
519a7b402dc258bf38ab5e206dbf4916a69d3ee3cc8Steve Naroff}
520a7b402dc258bf38ab5e206dbf4916a69d3ee3cc8Steve Naroff
521bce831b1ecda51cd1abd3c07467294ffd21f5f86Eli FriedmanASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
522bce831b1ecda51cd1abd3c07467294ffd21f5f86Eli Friedman                                       llvm::raw_ostream* OS,
5231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                       Diagnostic &Diags,
524c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                                       const LangOptions &LOpts,
525c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman                                       bool SilenceRewriteMacroWarning) {
526c6d656e2b0491f224ddd48507627b51d630d749aEli Friedman  return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
527e365c50a21cb02e0219433db0c4461566ad4a597Chris Lattner}
52877cd2a0b6eea81cc393b4c9e2941ec31fa09fdbeChris Lattner
529b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::Initialize(ASTContext &context) {
5309e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  Context = &context;
5319e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  SM = &Context->getSourceManager();
532ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  TUDecl = Context->getTranslationUnitDecl();
5339e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MsgSendFunctionDecl = 0;
5349e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MsgSendSuperFunctionDecl = 0;
5359e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MsgSendStretFunctionDecl = 0;
5369e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MsgSendSuperStretFunctionDecl = 0;
5379e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MsgSendFpretFunctionDecl = 0;
5389e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  GetClassFunctionDecl = 0;
5399e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  GetMetaClassFunctionDecl = 0;
540d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  GetSuperClassFunctionDecl = 0;
5419e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  SelGetUidFunctionDecl = 0;
5429e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  CFStringFunctionDecl = 0;
5439e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  ConstantStringClassReference = 0;
5449e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  NSStringRecord = 0;
54554055232a5ddb9529726e934301b125cb720a273Steve Naroff  CurMethodDef = 0;
54654055232a5ddb9529726e934301b125cb720a273Steve Naroff  CurFunctionDef = 0;
547abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  CurFunctionDeclToDeclareForBlock = 0;
548b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff  GlobalVarDecl = 0;
5499e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  SuperStructDecl = 0;
550621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  ProtocolTypeDecl = 0;
5519630ec5b6785e5b6e1c71aeddcad05005beb7483Steve Naroff  ConstantStringDecl = 0;
5529e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  BcLabelCount = 0;
553c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  SuperContructorFunctionDecl = 0;
554d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  NumObjCStringLiterals = 0;
55568272b86b36f89d7ceba1ec9a2826c2126adc72eSteve Naroff  PropParentMap = 0;
55668272b86b36f89d7ceba1ec9a2826c2126adc72eSteve Naroff  CurrentBody = 0;
557b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff  DisableReplaceStmt = false;
558f292fcf6bd5118499a830e0950429effeb373c28Fariborz Jahanian  objc_impl_method = false;
5591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5609e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  // Get the ID and start/end of the main file.
5619e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MainFileID = SM->getMainFileID();
5629e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
5639e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MainFileStart = MainBuf->getBufferStart();
5649e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  MainFileEnd = MainBuf->getBufferEnd();
5651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5662c78b873f4f3823ae859c15674cb3d76c8554113Chris Lattner  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
5671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5689e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  // declaring objc_selector outside the parameter list removes a silly
5699e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner  // scope related warning...
570ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  if (IsHeader)
57162c2632c555bc701d41f0eb1803bbf0660d7f0c0Steve Naroff    Preamble = "#pragma once\n";
572ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "struct objc_selector; struct objc_class;\n";
57346a98a7df016b4a6835a1902c2f8ff2a3a8012baSteve Naroff  Preamble += "struct __rw_objc_super { struct objc_object *object; ";
574ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "struct objc_object *superClass; ";
575c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  if (LangOpts.Microsoft) {
576c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff    // Add a constructor for creating temporary objects.
5778189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5788189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                ": ";
579ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff    Preamble += "object(o), superClass(s) {} ";
580c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  }
581ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "};\n";
582ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
583ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "typedef struct objc_object Protocol;\n";
584ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#define _REWRITER_typedef_Protocol\n";
585ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#endif\n";
5864ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  if (LangOpts.Microsoft) {
5874ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff    Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5884ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff    Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5894ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  } else
5907c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5914ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
592ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5934ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
594ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5954ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
596ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5974ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
598ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5994ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
600ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
6014ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
602ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(const char *);\n";
603d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
604d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  Preamble += "(struct objc_class *);\n";
6054ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
606ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "(const char *);\n";
6074ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
6084ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
6094ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
6104ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
6114ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
612580ca7859330f8c92a66b09c21399ed9efa3991eSteve Naroff  Preamble += "(struct objc_class *, struct objc_object *);\n";
61359f05a48a7b0353090da2b8f878c2d760e55731cSteve Naroff  // @synchronized hooks.
6144ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
6154ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
6164ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
617ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
618ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "struct __objcFastEnumerationState {\n\t";
619ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "unsigned long state;\n\t";
620b10f273eb60db2f2205b955fe4f7a43e09a5e2f2Steve Naroff  Preamble += "void **itemsPtr;\n\t";
621ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "unsigned long *mutationsPtr;\n\t";
622ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "unsigned long extra[5];\n};\n";
6234ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
624ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#define __FASTENUMERATIONSTATE\n";
625ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#endif\n";
626ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
627ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "struct __NSConstantStringImpl {\n";
628ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "  int *isa;\n";
629ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "  int flags;\n";
630ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "  char *str;\n";
631ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "  long length;\n";
632ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "};\n";
63388bee7451399c04b7e1c49cdeb16fadf0dd66f58Steve Naroff  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
63488bee7451399c04b7e1c49cdeb16fadf0dd66f58Steve Naroff  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
63588bee7451399c04b7e1c49cdeb16fadf0dd66f58Steve Naroff  Preamble += "#else\n";
6364ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
63788bee7451399c04b7e1c49cdeb16fadf0dd66f58Steve Naroff  Preamble += "#endif\n";
638ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
639ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "#endif\n";
64054055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Blocks preamble.
64154055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "#ifndef BLOCK_IMPL\n";
64254055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "#define BLOCK_IMPL\n";
64354055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "struct __block_impl {\n";
64454055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "  void *isa;\n";
64554055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "  int Flags;\n";
64601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  Preamble += "  int Reserved;\n";
64754055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "  void *FuncPtr;\n";
64854055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "};\n";
6495bc60d0c324a1b3984cd4a32acb587c8f873ab5fSteve Naroff  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
650c9c1e9c4b513e83146eff1728142683980df26a7Steve Naroff  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6517c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  Preamble += "extern \"C\" __declspec(dllexport) "
6527c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian              "void _Block_object_assign(void *, const void *, const int);\n";
653a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
654a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
655a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
656a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "#else\n";
657cd826370bb146a25bddea48399953dd3077710cfSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
658cd826370bb146a25bddea48399953dd3077710cfSteve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
659a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
660a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
661a851e60b7eb1d51549222ac838b8b602f23ec701Steve Naroff  Preamble += "#endif\n";
66254055232a5ddb9529726e934301b125cb720a273Steve Naroff  Preamble += "#endif\n";
663a48396e10f75966ed5ca974dcc73907ce8c80deeSteve Naroff  if (LangOpts.Microsoft) {
6644ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff    Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6654ebd716f260584663297bdb820714788f2a1e4cbSteve Naroff    Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
666553e583e1d30fe30ac2de3526536bbebee6da1ceChris Lattner    Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
667a48396e10f75966ed5ca974dcc73907ce8c80deeSteve Naroff    Preamble += "#define __attribute__(X)\n";
668553e583e1d30fe30ac2de3526536bbebee6da1ceChris Lattner    Preamble += "#endif\n";
66934204195de802e9d3cc8d54355b2ad4b3c27f188Fariborz Jahanian    Preamble += "#define __weak\n";
670a48396e10f75966ed5ca974dcc73907ce8c80deeSteve Naroff  }
6712086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  else {
67252b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian    Preamble += "#define __block\n";
6732086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    Preamble += "#define __weak\n";
6742086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  }
675df496529b7009d6e58f335926884200b38d27687Fariborz Jahanian  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
676df496529b7009d6e58f335926884200b38d27687Fariborz Jahanian  // as this avoids warning in any 64bit/32bit compilation model.
677df496529b7009d6e58f335926884200b38d27687Fariborz Jahanian  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6789e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner}
6799e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner
6809e13c2eb681b5d8e14f930b14300caaae22fdb92Chris Lattner
681f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner//===----------------------------------------------------------------------===//
682f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner// Top Level Driver Code
683f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner//===----------------------------------------------------------------------===//
684f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner
685682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattnervoid RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
686e50187a987dadb6a3b6f673125617c8f42ff3560Ted Kremenek  if (Diags.hasErrorOccurred())
687e50187a987dadb6a3b6f673125617c8f42ff3560Ted Kremenek    return;
688e50187a987dadb6a3b6f673125617c8f42ff3560Ted Kremenek
6892c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  // Two cases: either the decl could be in the main file, or it could be in a
6902c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  // #included file.  If the former, rewrite it now.  If the later, check to see
6912c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  // if we rewrote the #include/#import.
6922c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  SourceLocation Loc = D->getLocation();
693f7cf85b330bedd2877e1371fb0a83e99751ae162Chris Lattner  Loc = SM->getInstantiationLoc(Loc);
6941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6952c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  // If this is for a builtin, ignore it.
6962c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner  if (Loc.isInvalid()) return;
6972c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner
698ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  // Look for built-in declarations that we need to refer during the rewrite.
699ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
70009b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    RewriteFunctionDecl(FD);
701248a753f6b670692523c99afaeb8fe98f7ae3ca7Steve Naroff  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
702beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff    // declared in <Foundation/NSString.h>
7034087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    if (FVD->getName() == "_NSConstantStringClassReference") {
704beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff      ConstantStringClassReference = FVD;
705beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff      return;
706beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff    }
707a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
708bef1185418705e16012b3dd50cd7c260c8d6b79cSteve Naroff    RewriteInterfaceDecl(MD);
709a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
710423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff    RewriteCategoryDecl(CD);
711a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
712752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff    RewriteProtocolDecl(PD);
7131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (ObjCForwardProtocolDecl *FP =
714a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek             dyn_cast<ObjCForwardProtocolDecl>(D)){
715d175ddfdbefff8646982dfd4afc5bdf6edbc9e67Fariborz Jahanian    RewriteForwardProtocolDecl(FP);
716d04341000d35c8808a72838b057eed7bf13b7661Douglas Gregor  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
717d04341000d35c8808a72838b057eed7bf13b7661Douglas Gregor    // Recurse into linkage specifications
71817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
71917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis                                 DIEnd = LSD->decls_end();
720d04341000d35c8808a72838b057eed7bf13b7661Douglas Gregor         DI != DIEnd; ++DI)
721682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner      HandleTopLevelSingleDecl(*DI);
722ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  }
723f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  // If we have a decl in the main file, see if we should rewrite it.
724cf7e958483735935de6e0a64aa1e55a967116303Ted Kremenek  if (SM->isFromMainFile(Loc))
7252c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner    return HandleDeclInMainFile(D);
7262c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner}
7272c64b7b9381be4ff62fbdc404ed3f14c8086898dChris Lattner
728f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner//===----------------------------------------------------------------------===//
729f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner// Syntactic (non-AST) Rewriting Code
730f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner//===----------------------------------------------------------------------===//
731f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner
732b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteInclude() {
7332b2453a7d8fe732561795431f39ceb2b2a832d84Chris Lattner  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
734f6ac97b101c8840efa92bf29166077ce4049e293Benjamin Kramer  llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
735f6ac97b101c8840efa92bf29166077ce4049e293Benjamin Kramer  const char *MainBufStart = MainBuf.begin();
736f6ac97b101c8840efa92bf29166077ce4049e293Benjamin Kramer  const char *MainBufEnd = MainBuf.end();
737452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian  size_t ImportLen = strlen("import");
7381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
739af57b46f12e9dd48485fa27f2088f85466ee9292Fariborz Jahanian  // Loop over the whole file, looking for includes.
740452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian    if (*BufPtr == '#') {
742452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian      if (++BufPtr == MainBufEnd)
743452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian        return;
744452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian      while (*BufPtr == ' ' || *BufPtr == '\t')
745452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian        if (++BufPtr == MainBufEnd)
746452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian          return;
747452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian      if (!strncmp(BufPtr, "import", ImportLen)) {
748452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian        // replace import with include
7491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        SourceLocation ImportLoc =
750452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian          LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
751d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        ReplaceText(ImportLoc, ImportLen, "include");
752452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian        BufPtr += ImportLen;
753452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian      }
754452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian    }
755452b899c9f5fbcb8ddd130375b7982bed6b4d93fFariborz Jahanian  }
7568a12c2777cccdf629b89745b6ecc89a8c1641e4eChris Lattner}
7578a12c2777cccdf629b89745b6ecc89a8c1641e4eChris Lattner
7582d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanianstatic std::string getIvarAccessString(ObjCIvarDecl *OID) {
7592d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian  const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
760eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  std::string S;
761eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  S = "((struct ";
762eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  S += ClassDecl->getIdentifier()->getName();
763eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  S += "_IMPL *)self)->";
7645ffe14ca96bd662de7820f6875d3f04789a640c1Daniel Dunbar  S += OID->getName();
765eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  return S;
766eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff}
767eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff
768a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroffvoid RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff                                          ObjCImplementationDecl *IMD,
770a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff                                          ObjCCategoryImplDecl *CID) {
7717c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  static bool objcGetPropertyDefined = false;
7727c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  static bool objcSetPropertyDefined = false;
773d40910b581b09c937a8c1fdcde9b8ec724398fb9Steve Naroff  SourceLocation startLoc = PID->getLocStart();
774d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(startLoc, "// ");
775eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  const char *startBuf = SM->getCharacterData(startLoc);
776eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  assert((*startBuf == '@') && "bogus @synthesize location");
777eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  const char *semiBuf = strchr(startBuf, ';');
778eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  assert((*semiBuf == ';') && "@synthesize: can't find ';'");
7798189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  SourceLocation onePastSemiLoc =
7808189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
781eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff
782eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff    return; // FIXME: is this correct?
7841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
785eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  // Generate the 'getter' function.
786eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  ObjCPropertyDecl *PD = PID->getPropertyDecl();
787eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
7881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
789dd2fdf13f11f93a8bd271807db25c71191914807Steve Naroff  if (!OID)
790dd2fdf13f11f93a8bd271807db25c71191914807Steve Naroff    return;
7917c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  unsigned Attributes = PD->getPropertyAttributes();
792ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian  if (!PD->getGetterMethodDecl()->isDefined()) {
793ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian                          (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
795ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian                                         ObjCPropertyDecl::OBJC_PR_copy));
796ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    std::string Getr;
797ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    if (GenGetProperty && !objcGetPropertyDefined) {
798ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      objcGetPropertyDefined = true;
799ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      // FIXME. Is this attribute correct in all cases?
800ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr = "\nextern \"C\" __declspec(dllimport) "
801ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            "id objc_getProperty(id, SEL, long, bool);\n";
802ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    }
803ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    RewriteObjCMethodDecl(OID->getContainingInterface(),
804ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian                          PD->getGetterMethodDecl(), Getr);
805ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    Getr += "{ ";
806ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    // Synthesize an explicit cast to gain access to the ivar.
807ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    // See objc-act.c:objc_synthesize_new_getter() for details.
808ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    if (GenGetProperty) {
809ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += "typedef ";
811ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      const FunctionType *FPRetType = 0;
812ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian                            FPRetType);
814ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += " _TYPE";
815ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      if (FPRetType) {
816ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        Getr += ")"; // close the precedence "scope" for "*".
8177c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian
818ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        // Now, emit the argument types (if any).
819ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          Getr += "(";
821ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            if (i) Getr += ", ";
823ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            std::string ParamStr = FT->getArgType(i).getAsString(
824ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian                                                          Context->PrintingPolicy);
825ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            Getr += ParamStr;
826ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          }
827ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          if (FT->isVariadic()) {
828ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            if (FT->getNumArgs()) Getr += ", ";
829ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian            Getr += "...";
830ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          }
831ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          Getr += ")";
832ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        } else
833ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian          Getr += "()";
834ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      }
835ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += ";\n";
836ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += "return (_TYPE)";
837ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += "objc_getProperty(self, _cmd, ";
838ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      SynthesizeIvarOffsetComputation(OID, Getr);
839ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += ", 1)";
8407c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    }
841ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    else
842ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      Getr += "return " + getIvarAccessString(OID);
843ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    Getr += "; }";
844ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian    InsertText(onePastSemiLoc, Getr);
8457c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  }
846ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian
847ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian  if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
848eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff    return;
8491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
850eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  // Generate the 'setter' function.
851eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  std::string Setr;
8527c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
8537c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian                                      ObjCPropertyDecl::OBJC_PR_copy);
8547c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  if (GenSetProperty && !objcSetPropertyDefined) {
8557c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    objcSetPropertyDefined = true;
8567c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    // FIXME. Is this attribute correct in all cases?
8577c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    Setr = "\nextern \"C\" __declspec(dllimport) "
8587c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
8597c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  }
8607c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian
8612d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian  RewriteObjCMethodDecl(OID->getContainingInterface(),
8622d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian                        PD->getSetterMethodDecl(), Setr);
863eb0646c8df1c5c8de62b622d13d0c9f19aa29277Steve Naroff  Setr += "{ ";
864dd2fdf13f11f93a8bd271807db25c71191914807Steve Naroff  // Synthesize an explicit cast to initialize the ivar.
86515f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff  // See objc-act.c:objc_synthesize_new_setter() for details.
8667c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  if (GenSetProperty) {
8677c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    Setr += "objc_setProperty (self, _cmd, ";
8682d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    SynthesizeIvarOffsetComputation(OID, Setr);
8697c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    Setr += ", (id)";
8704087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    Setr += PD->getName();
8717c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    Setr += ", ";
8727c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
8737c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian      Setr += "0, ";
8747c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    else
8757c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian      Setr += "1, ";
8767c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
8777c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian      Setr += "1)";
8787c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    else
8797c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian      Setr += "0)";
8807c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  }
8817c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  else {
8822d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    Setr += getIvarAccessString(OID) + " = ";
8834087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    Setr += PD->getName();
8847c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  }
885dd2fdf13f11f93a8bd271807db25c71191914807Steve Naroff  Setr += "; }";
886d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(onePastSemiLoc, Setr);
887d40910b581b09c937a8c1fdcde9b8ec724398fb9Steve Naroff}
8888a12c2777cccdf629b89745b6ecc89a8c1641e4eChris Lattner
889b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
890f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  // Get the start location and compute the semi location.
891f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  SourceLocation startLoc = ClassDecl->getLocation();
892f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  const char *startBuf = SM->getCharacterData(startLoc);
893f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  const char *semiPtr = strchr(startBuf, ';');
8941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
895f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  // Translate to typedef's that forward reference structs with the same name
896f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  // as the class. As a convenience, we include the original declaration
897f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  // as a comment.
898f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  std::string typedefString;
89991fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian  typedefString += "// @class ";
90091fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian  for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
90191fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian       I != E; ++I) {
90291fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian    ObjCInterfaceDecl *ForwardDecl = I->getInterface();
90391fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian    typedefString += ForwardDecl->getNameAsString();
90491fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian    if (I+1 != E)
90591fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian      typedefString += ", ";
90691fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian    else
90791fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian      typedefString += ";\n";
90891fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian  }
90991fbd12d8b6e60b72883ff4c42e2a0993087f876Fariborz Jahanian
91067956052ea5fb0cd7f443de96a11f9a0176dc681Chris Lattner  for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
91167956052ea5fb0cd7f443de96a11f9a0176dc681Chris Lattner       I != E; ++I) {
912321c22f1c4271c3d9a3d4d3fc18847f948ab595bTed Kremenek    ObjCInterfaceDecl *ForwardDecl = I->getInterface();
91332174826f58d38c20f376fe64ceac4a278133883Steve Naroff    typedefString += "#ifndef _REWRITER_typedef_";
914d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    typedefString += ForwardDecl->getNameAsString();
91532174826f58d38c20f376fe64ceac4a278133883Steve Naroff    typedefString += "\n";
91632174826f58d38c20f376fe64ceac4a278133883Steve Naroff    typedefString += "#define _REWRITER_typedef_";
917d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    typedefString += ForwardDecl->getNameAsString();
91832174826f58d38c20f376fe64ceac4a278133883Steve Naroff    typedefString += "\n";
919352336bb0a480b044eb03e7359e73d3b173d9cddSteve Naroff    typedefString += "typedef struct objc_object ";
920d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    typedefString += ForwardDecl->getNameAsString();
92132174826f58d38c20f376fe64ceac4a278133883Steve Naroff    typedefString += ";\n#endif\n";
922934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  }
9231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
924934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  // Replace the @class with typedefs corresponding to the classes.
925d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
926f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner}
927f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner
928b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
929d0502407c1b41b2ace326f355d7b7a6876246223Fariborz Jahanian  // When method is a synthesized one, such as a getter/setter there is
930d0502407c1b41b2ace326f355d7b7a6876246223Fariborz Jahanian  // nothing to rewrite.
931d0502407c1b41b2ace326f355d7b7a6876246223Fariborz Jahanian  if (Method->isSynthesized())
932d0502407c1b41b2ace326f355d7b7a6876246223Fariborz Jahanian    return;
93358dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff  SourceLocation LocStart = Method->getLocStart();
93458dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff  SourceLocation LocEnd = Method->getLocEnd();
9351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
93630fc933e5fbbb5f0ea60c47976d435254e378536Chris Lattner  if (SM->getInstantiationLineNumber(LocEnd) >
93730fc933e5fbbb5f0ea60c47976d435254e378536Chris Lattner      SM->getInstantiationLineNumber(LocStart)) {
938d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(LocStart, "#if 0\n");
939d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocEnd, 1, ";\n#endif\n");
94058dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff  } else {
941d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(LocStart, "// ");
942423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff  }
943423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff}
944423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff
9451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
946d0502407c1b41b2ace326f355d7b7a6876246223Fariborz Jahanian  SourceLocation Loc = prop->getAtLoc();
9471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
948d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(Loc, 0, "// ");
9496327e0d55c590b3c2766fa76ef1db241a0467df2Steve Naroff  // FIXME: handle properties that are declared across multiple lines.
950957cf65bf32fe7c84886a2296d0b4ede40029850Fariborz Jahanian}
951957cf65bf32fe7c84886a2296d0b4ede40029850Fariborz Jahanian
952b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
953423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff  SourceLocation LocStart = CatDecl->getLocStart();
9541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
955423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff  // FIXME: handle category headers that are declared across multiple lines.
956d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(LocStart, 0, "// ");
9571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
95813751e3edc7fe50b0ab4e0f5fe7501e81c83c795Fariborz Jahanian  for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
95913751e3edc7fe50b0ab4e0f5fe7501e81c83c795Fariborz Jahanian       E = CatDecl->prop_end(); I != E; ++I)
96013751e3edc7fe50b0ab4e0f5fe7501e81c83c795Fariborz Jahanian    RewriteProperty(*I);
96113751e3edc7fe50b0ab4e0f5fe7501e81c83c795Fariborz Jahanian
9621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCCategoryDecl::instmeth_iterator
9631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump         I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
9646ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
96558dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
9661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCCategoryDecl::classmeth_iterator
96717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
9686ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
96958dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
97058dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff
971423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff  // Lastly, comment out the @end.
97273d1eb064350d5310f0475366cbe54d2d1da27bbFariborz Jahanian  ReplaceText(CatDecl->getAtEndRange().getBegin(),
97373d1eb064350d5310f0475366cbe54d2d1da27bbFariborz Jahanian              strlen("@end"), "/* @end */");
974423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff}
975423cb565abc681b770fb4b9b4bc24d398c98157bSteve Naroff
976b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
977752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff  SourceLocation LocStart = PDecl->getLocStart();
9781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
979752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff  // FIXME: handle protocol headers that are declared across multiple lines.
980d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(LocStart, 0, "// ");
9811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCProtocolDecl::instmeth_iterator
9831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump         I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
9846ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
98558dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
9866ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor  for (ObjCProtocolDecl::classmeth_iterator
98717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
9886ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
98958dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
99058dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff
99107acdf4c776fd98e315bc1de380af8ba3c25559eFariborz Jahanian  for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
99207acdf4c776fd98e315bc1de380af8ba3c25559eFariborz Jahanian       E = PDecl->prop_end(); I != E; ++I)
99307acdf4c776fd98e315bc1de380af8ba3c25559eFariborz Jahanian    RewriteProperty(*I);
99407acdf4c776fd98e315bc1de380af8ba3c25559eFariborz Jahanian
995752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff  // Lastly, comment out the @end.
996782f2f52b78d8ca785110398a7f7b56b830b9ac7Ted Kremenek  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
99773d1eb064350d5310f0475366cbe54d2d1da27bbFariborz Jahanian  ReplaceText(LocEnd, strlen("@end"), "/* @end */");
9988cc764c67afc249628ba4f65b8e2d2ad461112ffSteve Naroff
999b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian  // Must comment out @optional/@required
1000b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian  const char *startBuf = SM->getCharacterData(LocStart);
1001b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian  const char *endBuf = SM->getCharacterData(LocEnd);
1002b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian  for (const char *p = startBuf; p < endBuf; p++) {
1003b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian    if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
10048cc764c67afc249628ba4f65b8e2d2ad461112ffSteve Naroff      SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
1005d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
10061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1007b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian    }
1008b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian    else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
10098cc764c67afc249628ba4f65b8e2d2ad461112ffSteve Naroff      SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
1010d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
10111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1012b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian    }
1013b82b3ea8a12e4bc5960f59c1c2b9f483af5471e8Fariborz Jahanian  }
1014752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff}
1015752d6ef8c886b4de3365efef15449cd6f939baf1Steve Naroff
1016b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
1017d175ddfdbefff8646982dfd4afc5bdf6edbc9e67Fariborz Jahanian  SourceLocation LocStart = PDecl->getLocation();
1018b7fa992be16668b61f722e6e125137216860469eSteve Naroff  if (LocStart.isInvalid())
1019b7fa992be16668b61f722e6e125137216860469eSteve Naroff    assert(false && "Invalid SourceLocation");
1020d175ddfdbefff8646982dfd4afc5bdf6edbc9e67Fariborz Jahanian  // FIXME: handle forward protocol that are declared across multiple lines.
1021d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(LocStart, 0, "// ");
1022d175ddfdbefff8646982dfd4afc5bdf6edbc9e67Fariborz Jahanian}
1023d175ddfdbefff8646982dfd4afc5bdf6edbc9e67Fariborz Jahanian
10247c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanianvoid RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
10257c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian                                        const FunctionType *&FPRetType) {
10267c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  if (T->isObjCQualifiedIdType())
1027c569249ca0ab755ac79d8cbbfcb2bcae19743624Fariborz Jahanian    ResultStr += "id";
10287c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  else if (T->isFunctionPointerType() ||
10297c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian           T->isBlockPointerType()) {
103076e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    // needs special handling, since pointer-to-functions have special
103176e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    // syntax (where a decaration models use).
10327c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian    QualType retType = T;
1033f4312dc9b690fc79039560c125e9e3f8ea8a478eSteve Naroff    QualType PointeeTy;
10346217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    if (const PointerType* PT = retType->getAs<PointerType>())
1035f4312dc9b690fc79039560c125e9e3f8ea8a478eSteve Naroff      PointeeTy = PT->getPointeeType();
10366217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1037f4312dc9b690fc79039560c125e9e3f8ea8a478eSteve Naroff      PointeeTy = BPT->getPointeeType();
1038183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1039fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar      ResultStr += FPRetType->getResultType().getAsString(
1040fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar        Context->PrintingPolicy);
1041f4312dc9b690fc79039560c125e9e3f8ea8a478eSteve Naroff      ResultStr += "(*";
104276e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    }
104376e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff  } else
1044fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar    ResultStr += T.getAsString(Context->PrintingPolicy);
10457c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian}
10467c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian
10472d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanianvoid RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
10482d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian                                        ObjCMethodDecl *OMD,
10497c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian                                        std::string &ResultStr) {
10507c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
10517c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  const FunctionType *FPRetType = 0;
10527c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  ResultStr += "\nstatic ";
10537c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian  RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1054531a1ea2f4c88817f3dc0f4628dfc34536f54c5eFariborz Jahanian  ResultStr += " ";
10551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
105648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  // Unique method name
1057b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian  std::string NameStr;
10581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1059f8d49f64ef6ab7e632717a31631fc289aab69428Douglas Gregor  if (OMD->isInstanceMethod())
1060b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian    NameStr += "_I_";
106148a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  else
1062b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian    NameStr += "_C_";
10631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10642d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian  NameStr += IDecl->getNameAsString();
1065b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian  NameStr += "_";
10661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (ObjCCategoryImplDecl *CID =
10683e0a540b6d846178857289ec0eb8470a278d11a3Steve Naroff      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1069d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    NameStr += CID->getNameAsString();
1070b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian    NameStr += "_";
107148a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
10721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Append selector names, replacing ':' with '_'
1073077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner  {
1074077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner    std::string selString = OMD->getSelector().getAsString();
107548a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    int len = selString.size();
107648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    for (int i = 0; i < len; i++)
107748a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian      if (selString[i] == ':')
107848a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian        selString[i] = '_';
1079b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian    NameStr += selString;
108048a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
1081b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian  // Remember this name for metadata emission
1082b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian  MethodInternalNames[OMD] = NameStr;
1083b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian  ResultStr += NameStr;
10841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
108548a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  // Rewrite arguments
108648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  ResultStr += "(";
10871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
108848a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  // invisible arguments
1089f8d49f64ef6ab7e632717a31631fc289aab69428Douglas Gregor  if (OMD->isInstanceMethod()) {
10902d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    QualType selfTy = Context->getObjCInterfaceType(IDecl);
109148a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    selfTy = Context->getPointerType(selfTy);
109205b8c782669d07a71d4889bcacfd53a29cd16fcbSteve Naroff    if (!LangOpts.Microsoft) {
10932d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
109405b8c782669d07a71d4889bcacfd53a29cd16fcbSteve Naroff        ResultStr += "struct ";
109505b8c782669d07a71d4889bcacfd53a29cd16fcbSteve Naroff    }
109605b8c782669d07a71d4889bcacfd53a29cd16fcbSteve Naroff    // When rewriting for Microsoft, explicitly omit the structure name.
10972d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    ResultStr += IDecl->getNameAsString();
109861ed9caca5dd6a9b9ccee7fb51296234e6cc68adSteve Naroff    ResultStr += " *";
109948a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
110048a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  else
1101fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar    ResultStr += Context->getObjCClassType().getAsString(
1102fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar      Context->PrintingPolicy);
11031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
110448a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  ResultStr += " self, ";
1105fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
110648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  ResultStr += " _cmd";
11071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
110848a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  // Method arguments.
110989951a86b594513c2a013532ed45d197413b1087Chris Lattner  for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
111089951a86b594513c2a013532ed45d197413b1087Chris Lattner       E = OMD->param_end(); PI != E; ++PI) {
111189951a86b594513c2a013532ed45d197413b1087Chris Lattner    ParmVarDecl *PDecl = *PI;
111248a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    ResultStr += ", ";
1113543409e200234a1c97ea38b9d52bce22ff807080Steve Naroff    if (PDecl->getType()->isObjCQualifiedIdType()) {
1114543409e200234a1c97ea38b9d52bce22ff807080Steve Naroff      ResultStr += "id ";
1115d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      ResultStr += PDecl->getNameAsString();
1116543409e200234a1c97ea38b9d52bce22ff807080Steve Naroff    } else {
1117d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      std::string Name = PDecl->getNameAsString();
11184fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      QualType QT = PDecl->getType();
11194fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      // Make sure we convert "t (^)(...)" to "t (*)(...)".
11204fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      if (convertBlockPointerToFunctionPointer(QT))
11214fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian        QT.getAsStringInternal(Name, Context->PrintingPolicy);
11224fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      else
1123d249e1d1f1498b81314459ceda19d6ff25c278adDouglas Gregor        PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
1124543409e200234a1c97ea38b9d52bce22ff807080Steve Naroff      ResultStr += Name;
1125543409e200234a1c97ea38b9d52bce22ff807080Steve Naroff    }
112648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
11277c39ff7eb3dd7ae9b2b81cb66a139c9b52f47f1dFariborz Jahanian  if (OMD->isVariadic())
11287c39ff7eb3dd7ae9b2b81cb66a139c9b52f47f1dFariborz Jahanian    ResultStr += ", ...";
1129531a1ea2f4c88817f3dc0f4628dfc34536f54c5eFariborz Jahanian  ResultStr += ") ";
11301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
113176e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff  if (FPRetType) {
113276e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    ResultStr += ")"; // close the precedence "scope" for "*".
11331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
113476e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    // Now, emit the argument types (if any).
113572564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
113676e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      ResultStr += "(";
113776e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
113876e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff        if (i) ResultStr += ", ";
1139fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar        std::string ParamStr = FT->getArgType(i).getAsString(
1140fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar          Context->PrintingPolicy);
114176e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff        ResultStr += ParamStr;
114276e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      }
114376e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      if (FT->isVariadic()) {
114476e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff        if (FT->getNumArgs()) ResultStr += ", ";
114576e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff        ResultStr += "...";
114676e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      }
114776e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      ResultStr += ")";
114876e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    } else {
114976e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff      ResultStr += "()";
115076e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff    }
115176e429d781a8871afb5050f39ab8e00e72bdf2f8Steve Naroff  }
115248a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian}
11534afa39deaa245592977136d367251ee2c173dd8dDouglas Gregorvoid RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1154a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1155a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
11561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1157a135216595c00ddb5ce5f5b853a3d1f4037a13b7Fariborz Jahanian  InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
11581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1159a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  for (ObjCCategoryImplDecl::instmeth_iterator
116017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis       I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
116117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis       E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1162653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor       I != E; ++I) {
116348a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    std::string ResultStr;
1164a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    ObjCMethodDecl *OMD = *I;
11652d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
116648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    SourceLocation LocStart = OMD->getLocStart();
11676fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1168d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl
116948a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    const char *startBuf = SM->getCharacterData(LocStart);
117048a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    const char *endBuf = SM->getCharacterData(LocEnd);
1171d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
117248a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
11731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1174a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  for (ObjCCategoryImplDecl::classmeth_iterator
117517945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis       I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
117617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis       E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1177653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor       I != E; ++I) {
117848a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    std::string ResultStr;
1179a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    ObjCMethodDecl *OMD = *I;
11802d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
118148a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    SourceLocation LocStart = OMD->getLocStart();
11826fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
11831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
118448a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    const char *startBuf = SM->getCharacterData(LocStart);
118548a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian    const char *endBuf = SM->getCharacterData(LocEnd);
1186d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
118748a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian  }
1188d40910b581b09c937a8c1fdcde9b8ec724398fb9Steve Naroff  for (ObjCCategoryImplDecl::propimpl_iterator
118917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis       I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
11901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump       E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1191653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor       I != E; ++I) {
1192a0876e88aff05e8fc0492d216c17bff16de31a37Steve Naroff    RewritePropertyImplDecl(*I, IMD, CID);
1193d40910b581b09c937a8c1fdcde9b8ec724398fb9Steve Naroff  }
1194d40910b581b09c937a8c1fdcde9b8ec724398fb9Steve Naroff
1195d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
119648a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian}
119748a0b6aa9d23bba2bd4ad943ad59106a91f8b3f7Fariborz Jahanian
1198b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1199f908a87299d278164540f90b5b6e6cab7b14fb41Steve Naroff  std::string ResultStr;
1200a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  if (!ObjCForwardDecls.count(ClassDecl)) {
12016c6a2dbb4db96a69d6f1c2e3d322e4c3abd43814Steve Naroff    // we haven't seen a forward decl - generate a typedef.
12025086a8df9a269acc2e4f0deb1895d4a9e9d13f4dSteve Naroff    ResultStr = "#ifndef _REWRITER_typedef_";
1203d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    ResultStr += ClassDecl->getNameAsString();
120432174826f58d38c20f376fe64ceac4a278133883Steve Naroff    ResultStr += "\n";
120532174826f58d38c20f376fe64ceac4a278133883Steve Naroff    ResultStr += "#define _REWRITER_typedef_";
1206d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    ResultStr += ClassDecl->getNameAsString();
120732174826f58d38c20f376fe64ceac4a278133883Steve Naroff    ResultStr += "\n";
120861ed9caca5dd6a9b9ccee7fb51296234e6cc68adSteve Naroff    ResultStr += "typedef struct objc_object ";
1209d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    ResultStr += ClassDecl->getNameAsString();
121032174826f58d38c20f376fe64ceac4a278133883Steve Naroff    ResultStr += ";\n#endif\n";
12116c6a2dbb4db96a69d6f1c2e3d322e4c3abd43814Steve Naroff    // Mark this typedef as having been generated.
1212a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    ObjCForwardDecls.insert(ClassDecl);
12136c6a2dbb4db96a69d6f1c2e3d322e4c3abd43814Steve Naroff  }
1214a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
12151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
121717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         E = ClassDecl->prop_end(); I != E; ++I)
12186327e0d55c590b3c2766fa76ef1db241a0467df2Steve Naroff    RewriteProperty(*I);
12191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCInterfaceDecl::instmeth_iterator
122017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
12216ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
122258dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
12231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCInterfaceDecl::classmeth_iterator
12241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump         I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
12256ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor       I != E; ++I)
122658dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff    RewriteMethodDeclaration(*I);
122758dbdeb69c063f82d644504fc638120198f7fad2Steve Naroff
12282feac5e559ca5c9693a3a19905ab106b9c52e193Steve Naroff  // Lastly, comment out the @end.
122973d1eb064350d5310f0475366cbe54d2d1da27bbFariborz Jahanian  ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
123073d1eb064350d5310f0475366cbe54d2d1da27bbFariborz Jahanian              "/* @end */");
1231bef1185418705e16012b3dd50cd7c260c8d6b79cSteve Naroff}
1232bef1185418705e16012b3dd50cd7c260c8d6b79cSteve Naroff
1233f2ad2c92720f0e25c032188783a1d6374155f03aFariborz JahanianStmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
1234b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff                                         SourceRange SrcRange) {
1235f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  ObjCMethodDecl *OMD = 0;
1236f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  QualType Ty;
1237f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  Selector Sel;
123854bd4577762228fdca4367dbc3af5e13e7f21389Duncan Sands  Stmt *Receiver = 0;
12398ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  bool Super = false;
12408ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  QualType SuperTy;
12418ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  SourceLocation SuperLocation;
1242f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis  SourceLocation SelectorLoc;
1243f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
1244c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  // This allows us to reuse all the fun and games in SynthMessageExpr().
124512f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall  if (ObjCPropertyRefExpr *PropRefExpr =
124612f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall        dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1247f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis    SelectorLoc = PropRefExpr->getLocation();
124812f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    if (PropRefExpr->isExplicitProperty()) {
124912f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
125012f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      OMD = PDecl->getSetterMethodDecl();
125112f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Ty = PDecl->getType();
125212f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Sel = PDecl->getSetterName();
125312f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    } else {
125412f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      OMD = PropRefExpr->getImplicitPropertySetter();
125512f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Sel = OMD->getSelector();
125612f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Ty = PropRefExpr->getType();
125712f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    }
12588ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    Super = PropRefExpr->isSuperReceiver();
125912f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    if (!Super) {
12608ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian      Receiver = PropRefExpr->getBase();
126112f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    } else {
126212f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      SuperTy = PropRefExpr->getSuperReceiverType();
126312f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      SuperLocation = PropRefExpr->getReceiverLocation();
12648ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    }
1265f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  }
1266f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian
1267f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
1268c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  llvm::SmallVector<Expr *, 1> ExprVec;
1269c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  ExprVec.push_back(newStmt);
12701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1271f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  ObjCMessageExpr *MsgExpr;
12728ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  if (Super)
127304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExpr = ObjCMessageExpr::Create(*Context,
1274f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian                                      Ty.getNonReferenceType(),
1275f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                      Expr::getValueKindForType(Ty),
127604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME?*/SourceLocation(),
12778ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian                                      SuperLocation,
127804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*IsInstanceSuper=*/true,
12798ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian                                      SuperTy,
1280f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis                                      Sel, SelectorLoc, OMD,
128104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      &ExprVec[0], 1,
128204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME:*/SourceLocation());
1283e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian  else {
1284e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    // FIXME. Refactor this into common code with that in
1285e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    // RewritePropertyOrImplicitGetter
1286e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1287e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    if (Expr *Exp = dyn_cast<Expr>(Receiver))
1288e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian      if (PropGetters[Exp])
1289e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian        // This allows us to handle chain/nested property/implicit getters.
1290e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian        Receiver = PropGetters[Exp];
1291e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian
129204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExpr = ObjCMessageExpr::Create(*Context,
1293f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian                                      Ty.getNonReferenceType(),
1294f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                      Expr::getValueKindForType(Ty),
129504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME: */SourceLocation(),
129604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      cast<Expr>(Receiver),
1297f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis                                      Sel, SelectorLoc, OMD,
129804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      &ExprVec[0], 1,
129904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME:*/SourceLocation());
1300e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian  }
1301c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
13021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1303c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  // Now do the actual rewrite.
1304b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff  ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
1305e58ee0ca7cfad6ee75a088e7a6a090526e18da50Steve Naroff  //delete BinOp;
13068189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
13078189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  // to things that stay around.
13088189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  Context->Deallocate(MsgExpr);
1309c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  return ReplacingStmt;
131015f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff}
131115f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff
1312f2ad2c92720f0e25c032188783a1d6374155f03aFariborz JahanianStmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1313f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
131415f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff  // This allows us to reuse all the fun and games in SynthMessageExpr().
13153b562af1b3675d22e8ad0cef6f48343b3c2ee02dTed Kremenek  Stmt *Receiver = 0;
1316f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  ObjCMethodDecl *OMD = 0;
1317f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  QualType Ty;
1318f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  Selector Sel;
13198ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  bool Super = false;
13208ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  QualType SuperTy;
13218ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  SourceLocation SuperLocation;
1322f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis  SourceLocation SelectorLoc;
1323f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  if (ObjCPropertyRefExpr *PropRefExpr =
1324f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian        dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1325f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis    SelectorLoc = PropRefExpr->getLocation();
132612f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    if (PropRefExpr->isExplicitProperty()) {
132712f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
132812f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      OMD = PDecl->getGetterMethodDecl();
132912f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Ty = PDecl->getType();
133012f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Sel = PDecl->getGetterName();
133112f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    } else {
133212f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      OMD = PropRefExpr->getImplicitPropertyGetter();
133312f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Sel = OMD->getSelector();
133412f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      Ty = PropRefExpr->getType();
133512f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall    }
13368ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    Super = PropRefExpr->isSuperReceiver();
13378ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    if (!Super)
13388ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian      Receiver = PropRefExpr->getBase();
13398ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    else {
134012f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      SuperTy = PropRefExpr->getSuperReceiverType();
134112f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      SuperLocation = PropRefExpr->getReceiverLocation();
13428ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian    }
13438599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff  }
1344f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian
1345f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1346f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian
1347f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  ObjCMessageExpr *MsgExpr;
13488ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian  if (Super)
134904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExpr = ObjCMessageExpr::Create(*Context,
1350f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian                                      Ty.getNonReferenceType(),
1351f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                      Expr::getValueKindForType(Ty),
13528ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian                                      /*FIXME?*/SourceLocation(),
13538ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian                                      SuperLocation,
135404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*IsInstanceSuper=*/true,
13558ac2d449820fd0df00fcbde5bf82165c1f49854dFariborz Jahanian                                      SuperTy,
1356f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis                                      Sel, SelectorLoc, OMD,
135704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      0, 0,
135804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME:*/SourceLocation());
1359e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian  else {
1360e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1361e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian    if (Expr *Exp = dyn_cast<Expr>(Receiver))
1362e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian      if (PropGetters[Exp])
1363e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian        // This allows us to handle chain/nested property/implicit getters.
1364e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian        Receiver = PropGetters[Exp];
136504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExpr = ObjCMessageExpr::Create(*Context,
1366f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian                                      Ty.getNonReferenceType(),
1367f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                      Expr::getValueKindForType(Ty),
136804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME:*/SourceLocation(),
136904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      cast<Expr>(Receiver),
1370f40f0d5a382395e0301d7dcbeaa2b8e90b8973b1Argyrios Kyrtzidis                                      Sel, SelectorLoc, OMD,
137104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      0, 0,
137204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                      /*FIXME:*/SourceLocation());
1373e0f83863595f5725791d88a799d20dbae38bed4aFariborz Jahanian  }
137415f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff
13754c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff  Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
13768599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff
13778599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff  if (!PropParentMap)
13788599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    PropParentMap = new ParentMap(CurrentBody);
13793cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian  bool NestedPropertyRef = false;
1380f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
13813cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian  ImplicitCastExpr*ICE=0;
13823cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian  if (Parent)
13833cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian    if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
13843cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian      assert((ICE->getCastKind() == CK_GetObjCProperty)
13853cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian             && "RewritePropertyOrImplicitGetter");
13863cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian      Parent = PropParentMap->getParent(Parent);
13873cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian      NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
13883cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian    }
13893cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian  if (NestedPropertyRef) {
13908599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    // We stash away the ReplacingStmt since actually doing the
13918599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
13923cd1ea32c312dee47432dbb982f83bccff7356acFariborz Jahanian    PropGetters[ICE] = ReplacingStmt;
13938189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
13948189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    // to things that stay around.
13958189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    Context->Deallocate(MsgExpr);
1396f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    return PropOrGetterRefExpr; // return the original...
13978599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff  } else {
1398f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
13991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // delete PropRefExpr; elsewhere...
14008189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
14018189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    // to things that stay around.
14028189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    Context->Deallocate(MsgExpr);
14038599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff    return ReplacingStmt;
14048599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff  }
140515f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff}
140615f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff
14071eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpStmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
14082b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian                                          SourceLocation OrigStart,
14092b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian                                          bool &replaced) {
1410a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCIvarDecl *D = IV->getDecl();
141184ed600154d48d75f204795410aae808d7e4b7bdFariborz Jahanian  const Expr *BaseExpr = IV->getBase();
141254055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (CurMethodDef) {
14138f0954309eb885891908ecdfbb06d720c63128edFariborz Jahanian    if (BaseExpr->getType()->isObjCObjectPointerType()) {
1414f4c7371fb1d3cebcfb40abad4537bb82515704eaJohn McCall      const ObjCInterfaceType *iFaceDecl =
141584ed600154d48d75f204795410aae808d7e4b7bdFariborz Jahanian        dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
1416ffbdead156eb0bc94d1cc7e28eadcca52dfb8194Fariborz Jahanian      assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
1417f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      // lookup which class implements the instance variable.
1418f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      ObjCInterfaceDecl *clsDeclared = 0;
14191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
14206ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor                                                   clsDeclared);
1421f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
14221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1423f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      // Synthesize an explicit cast to gain access to the ivar.
1424f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      std::string RecName = clsDeclared->getIdentifier()->getName();
1425f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      RecName += "_IMPL";
1426d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      IdentifierInfo *II = &Context->Idents.get(RecName);
1427465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
1428df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                                          SourceLocation(), II);
1429f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1430f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
14319d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall      CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1432a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                    CK_BitCast,
14339d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                                    IV->getBase());
1434f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff      // Don't forget the parens to enforce the proper binding.
14358189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek      ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1436f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                              IV->getBase()->getLocEnd(),
1437f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                              castExpr);
14382b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      replaced = true;
14391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      if (IV->isFreeIvar() &&
144054055232a5ddb9529726e934301b125cb720a273Steve Naroff          CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
14418189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek        MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1442f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                  IV->getLocation(),
1443f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                  D->getType(),
1444f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                  VK_LValue, OK_Ordinary);
1445f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian        // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1446f07576130b93ba7150e04b8bc38aad96a283d074Steve Naroff        return ME;
1447c2a689b0bd0cda7bc1522dc0057f01f0897e6d3dSteve Naroff      }
14487e20ffe322866f6a2e820e054da9bd0f6e9b0af4Fariborz Jahanian      // Get the new text
14493b2c58ce3b1eadc5901efff30cf8bf1885936fe7Chris Lattner      // Cannot delete IV->getBase(), since PE points to it.
14503b2c58ce3b1eadc5901efff30cf8bf1885936fe7Chris Lattner      // Replace the old base with the cast. This is important when doing
14513b2c58ce3b1eadc5901efff30cf8bf1885936fe7Chris Lattner      // embedded rewrites. For example, [newInv->_container addObject:0].
14521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      IV->setBase(PE);
14533b2c58ce3b1eadc5901efff30cf8bf1885936fe7Chris Lattner      return IV;
1454c2a689b0bd0cda7bc1522dc0057f01f0897e6d3dSteve Naroff    }
145584472a897a99db80d49eb5ac1ac85d54b1cc6554Steve Naroff  } else { // we are outside a method.
14569f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff    assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
14571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14589f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff    // Explicit ivar refs need to have a cast inserted.
14599f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff    // FIXME: consider sharing some of this code with the code above.
146026337b2f6d4b8dc7458a6e24dca05cb021a21861Fariborz Jahanian    if (BaseExpr->getType()->isObjCObjectPointerType()) {
1461f4c7371fb1d3cebcfb40abad4537bb82515704eaJohn McCall      const ObjCInterfaceType *iFaceDecl =
1462c374cd978abdeb289d360426129886f6e354a459Fariborz Jahanian        dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
14639f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // lookup which class implements the instance variable.
14649f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      ObjCInterfaceDecl *clsDeclared = 0;
14651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
14666ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor                                                   clsDeclared);
14679f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
14681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14699f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // Synthesize an explicit cast to gain access to the ivar.
14709f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      std::string RecName = clsDeclared->getIdentifier()->getName();
14719f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      RecName += "_IMPL";
1472d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      IdentifierInfo *II = &Context->Idents.get(RecName);
1473465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
1474df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                                          SourceLocation(), II);
14759f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
14769f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
14779d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall      CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1478a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                    CK_BitCast,
14799d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                                    IV->getBase());
14809f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // Don't forget the parens to enforce the proper binding.
14818189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek      ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
14828d36616a093f65f667d22bc1136a4c2be0bae7dfChris Lattner                                    IV->getBase()->getLocEnd(), castExpr);
14832b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      replaced = true;
14849f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // Cannot delete IV->getBase(), since PE points to it.
14859f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // Replace the old base with the cast. This is important when doing
14869f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      // embedded rewrites. For example, [newInv->_container addObject:0].
14871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      IV->setBase(PE);
14889f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff      return IV;
14899f525970bec0e29f32cec6141aa3baa245c5ae82Steve Naroff    }
1490c2a689b0bd0cda7bc1522dc0057f01f0897e6d3dSteve Naroff  }
149184472a897a99db80d49eb5ac1ac85d54b1cc6554Steve Naroff  return IV;
14927e3411b23eb3724da5461dc6d6f97d14b3b0a52fSteve Naroff}
14937e3411b23eb3724da5461dc6d6f97d14b3b0a52fSteve Naroff
14942b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz JahanianStmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
14957502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI) {
14962b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    if (*CI) {
14972b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
14982b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      if (newStmt)
14992b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        *CI = newStmt;
15002b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    }
15012b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian  }
15022b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian  if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
15032b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    SourceRange OrigStmtRange = S->getSourceRange();
15042b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
15052b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian                                           replaced);
15062b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian    return newStmt;
1507376338a68d467f076c2ae5fa614ec0286ea74d7cFariborz Jahanian  }
1508376338a68d467f076c2ae5fa614ec0286ea74d7cFariborz Jahanian  if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1509376338a68d467f076c2ae5fa614ec0286ea74d7cFariborz Jahanian    Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1510376338a68d467f076c2ae5fa614ec0286ea74d7cFariborz Jahanian    return newStmt;
1511376338a68d467f076c2ae5fa614ec0286ea74d7cFariborz Jahanian  }
15122b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian  return S;
15132b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian}
15142b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian
1515fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// SynthCountByEnumWithState - To print:
1516fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// ((unsigned int (*)
1517fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
15181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///  (void *)objc_msgSend)((id)l_collection,
1519fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///                        sel_registerName(
15201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///                          "countByEnumeratingWithState:objects:count:"),
15211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///                        &enumState,
1522fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///                        (id *)items, (unsigned int)16)
1523fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///
1524fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroffvoid RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1525fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1526fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  "id *, unsigned int))(void *)objc_msgSend)";
1527fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "\n\t\t";
1528fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "((id)l_collection,\n\t\t";
1529fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1530fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "\n\t\t";
1531fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += "&enumState, "
1532fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff         "(id *)items, (unsigned int)16)";
1533fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
1534b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff
1535fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1536fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// statement to exit to its outer synthesized loop.
1537fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///
1538fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve NaroffStmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1539fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return S;
1541fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // replace break with goto __break_label
1542fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string buf;
15431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1544fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  SourceLocation startLoc = S->getLocStart();
1545fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf = "goto __break_label_";
1546fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += utostr(ObjCBcLabelNo.back());
1547d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, strlen("break"), buf);
15482bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff
1549fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  return 0;
1550fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
1551a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian
1552fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1553fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// statement to continue with its inner synthesized loop.
1554fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff///
1555fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve NaroffStmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1556fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1557fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return S;
1558fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // replace continue with goto __continue_label
1559fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string buf;
15601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1561fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  SourceLocation startLoc = S->getLocStart();
1562fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf = "goto __continue_label_";
1563fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  buf += utostr(ObjCBcLabelNo.back());
1564d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, strlen("continue"), buf);
15651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1566e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  return 0;
1567e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian}
1568e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian
1569a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
157010d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///  It rewrites:
157110d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian/// for ( type elem in collection) { stmts; }
15721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
157310d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian/// Into:
157410d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian/// {
15751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///   type elem;
157633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///   struct __objcFastEnumerationState enumState = { 0 };
157710d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///   id items[16];
157833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///   id l_collection = (id)collection;
15791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
158033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///                                       objects:items count:16];
158110d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian/// if (limit) {
158210d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///   unsigned long startMutations = *enumState.mutationsPtr;
158310d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///   do {
158410d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///        unsigned long counter = 0;
158510d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///        do {
15861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///             if (startMutations != *enumState.mutationsPtr)
158733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///               objc_enumerationMutation(l_collection);
158888f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian///             elem = (type)enumState.itemsPtr[counter++];
158910d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///             stmts;
1590e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian///             __continue_label: ;
159110d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///        } while (counter < limit);
15921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
159333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///                                  objects:items count:16]);
159433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian///   elem = nil;
1595e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian///   __break_label: ;
159610d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///  }
159710d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///  else
159810d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///       elem = nil;
159910d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///  }
160010d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian///
1601b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1602338d1e2ced8037b71d91fb319631846917d0cedaChris Lattner                                                SourceLocation OrigEnd) {
1603e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
16041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1605e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian         "ObjCForCollectionStmt Statement stack mismatch");
16061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!ObjCBcLabelNo.empty() &&
1607e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian         "ObjCForCollectionStmt - Label No stack empty");
16081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
160933b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  SourceLocation startLoc = S->getLocStart();
161033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  const char *startBuf = SM->getCharacterData(startLoc);
16114087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  llvm::StringRef elementName;
161288f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  std::string elementTypeAsString;
161333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  std::string buf;
161433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf = "\n{\n\t";
161533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
161633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian    // type elem;
16177e24e82a70a2c681f4291a3397bcd1e1005f251aChris Lattner    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
16181ed8e2a39456d064a346a6a5c2f6bd53e6d57345Ted Kremenek    QualType ElementType = cast<ValueDecl>(D)->getType();
1619e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff    if (ElementType->isObjCQualifiedIdType() ||
1620e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff        ElementType->isObjCQualifiedInterfaceType())
1621e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff      // Simply use 'id' for all qualified types.
1622e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff      elementTypeAsString = "id";
1623e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff    else
1624fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar      elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
162588f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian    buf += elementTypeAsString;
162633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian    buf += " ";
16274087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    elementName = D->getName();
162833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian    buf += elementName;
162933b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian    buf += ";\n\t";
163033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  }
163106767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner  else {
163206767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
16334087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    elementName = DR->getDecl()->getName();
1634e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff    ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1635e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff    if (VD->getType()->isObjCQualifiedIdType() ||
1636e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff        VD->getType()->isObjCQualifiedInterfaceType())
1637e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff      // Simply use 'id' for all qualified types.
1638e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff      elementTypeAsString = "id";
1639e89b8e7946155db1a3bbb1e22addd5d9d2a904dfSteve Naroff    else
1640fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar      elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
164188f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  }
16421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
164333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // struct __objcFastEnumerationState enumState = { 0 };
164433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
164533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // id items[16];
164633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "id items[16];\n\t";
164733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // id l_collection = (id)
164833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "id l_collection = (id)";
16497571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  // Find start location of 'collection' the hard way!
16507571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  const char *startCollectionBuf = startBuf;
16517571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  startCollectionBuf += 3;  // skip 'for'
16527571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  startCollectionBuf = strchr(startCollectionBuf, '(');
16537571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  startCollectionBuf++; // skip '('
16547571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  // find 'in' and skip it.
16557571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  while (*startCollectionBuf != ' ' ||
16567571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian         *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
16577571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian         (*(startCollectionBuf+3) != ' ' &&
16587571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian          *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
16597571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian    startCollectionBuf++;
16607571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  startCollectionBuf += 3;
16611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Replace: "for (type element in" with string constructed thus far.
1663d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
166433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // Replace ')' in for '(' type elem in collection ')' with ';'
16657571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  SourceLocation rightParenLoc = S->getRParenLoc();
16667571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
16677571228ec9b31de7733ae96352ee4eaa8afcf2b5Fariborz Jahanian  SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
166833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf = ";\n\t";
16691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
167033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
167133b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  //                                   objects:items count:16];
167233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // which is synthesized into:
16731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // unsigned int limit =
167433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // ((unsigned int (*)
167533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
16761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  //  (void *)objc_msgSend)((id)l_collection,
167733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  //                        sel_registerName(
16781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  //                          "countByEnumeratingWithState:objects:count:"),
16791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  //                        (struct __objcFastEnumerationState *)&state,
168033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  //                        (id *)items, (unsigned int)16);
168133b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "unsigned long limit =\n\t\t";
168233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  SynthCountByEnumWithState(buf);
168333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += ";\n\t";
168433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  /// if (limit) {
168533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///   unsigned long startMutations = *enumState.mutationsPtr;
168633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///   do {
168733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///        unsigned long counter = 0;
168833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///        do {
16891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  ///             if (startMutations != *enumState.mutationsPtr)
169033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///               objc_enumerationMutation(l_collection);
169188f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  ///             elem = (type)enumState.itemsPtr[counter++];
169233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "if (limit) {\n\t";
169333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
169433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "do {\n\t\t";
169533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "unsigned long counter = 0;\n\t\t";
169633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "do {\n\t\t\t";
169733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
169833b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
169933b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += elementName;
170088f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  buf += " = (";
170188f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  buf += elementTypeAsString;
170288f50f31d84185827a8f765dd611134bcaface7bFariborz Jahanian  buf += ")enumState.itemsPtr[counter++];";
170333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // Replace ')' in for '(' type elem in collection ')' with all of these.
1704d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(lparenLoc, 1, buf);
17051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1706e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  ///            __continue_label: ;
170733b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///        } while (counter < limit);
17081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
170933b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///                                  objects:items count:16]);
171033b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///   elem = nil;
1711e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  ///   __break_label: ;
171233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///  }
171333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///  else
171433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///       elem = nil;
171533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  ///  }
17161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  ///
1717e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf = ";\n\t";
1718e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += "__continue_label_";
1719e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += utostr(ObjCBcLabelNo.back());
1720e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += ": ;";
1721e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += "\n\t\t";
172233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "} while (counter < limit);\n\t";
172333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "} while (limit = ";
172433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  SynthCountByEnumWithState(buf);
172533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += ");\n\t";
172633b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += elementName;
172765b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += " = ((";
172865b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += elementTypeAsString;
172965b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += ")0);\n\t";
1730e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += "__break_label_";
1731e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += utostr(ObjCBcLabelNo.back());
1732e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  buf += ": ;\n\t";
173333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "}\n\t";
173433b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "else\n\t\t";
173533b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += elementName;
173665b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += " = ((";
173765b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += elementTypeAsString;
173865b0aa5d3973e07c8c4449ef2b81c389fd48229aFariborz Jahanian  buf += ")0);\n\t";
173933b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  buf += "}\n";
17401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
174133b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  // Insert all these *after* the statement body.
1742d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl  // FIXME: If this should support Obj-C++, support CXXTryStmt
1743600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff  if (isa<CompoundStmt>(S->getBody())) {
1744600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1745d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(endBodyLoc, buf);
1746600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff  } else {
1747600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    /* Need to treat single statements specially. For example:
1748600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     *
1749600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     *     for (A *a in b) if (stuff()) break;
1750600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     *     for (A *a in b) xxxyy;
1751600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     *
1752600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     * The following code simply scans ahead to the semi to find the actual end.
1753600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff     */
1754600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1755600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    const char *semiBuf = strchr(stmtBuf, ';');
1756600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    assert(semiBuf && "Can't find ';'");
1757600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff    SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1758d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(endBodyLoc, buf);
1759600e4e8c358fd39e70f3313b7f1bfa0848957597Steve Naroff  }
1760e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  Stmts.pop_back();
1761e8d1c0579404442a87818506bb0e742d0f52d5bfFariborz Jahanian  ObjCBcLabelNo.pop_back();
176233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  return 0;
176310d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian}
176410d24f062ee8c83823199191ccdba452c7f9ac24Fariborz Jahanian
17651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// RewriteObjCSynchronizedStmt -
1766a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian/// This routine rewrites @synchronized(expr) stmt;
1767a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian/// into:
1768a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian/// objc_sync_enter(expr);
1769a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian/// @try stmt @finally { objc_sync_exit(expr); }
1770a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian///
1771b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1772a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  // Get the start location and compute the semi location.
1773a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  SourceLocation startLoc = S->getLocStart();
1774a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  const char *startBuf = SM->getCharacterData(startLoc);
17751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1776a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  assert((*startBuf == '@') && "bogus @synchronized location");
17771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  std::string buf;
17793498cc9793487a5ad51a5a050be85bd550775eccSteve Naroff  buf = "objc_sync_enter((id)";
17803498cc9793487a5ad51a5a050be85bd550775eccSteve Naroff  const char *lparenBuf = startBuf;
17813498cc9793487a5ad51a5a050be85bd550775eccSteve Naroff  while (*lparenBuf != '(') lparenBuf++;
1782d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
17831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
17841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // the sync expression is typically a message expression that's already
1785c7089f1be946f3ca6e59596f0e0f92d96136e4c8Steve Naroff  // been rewritten! (which implies the SourceLocation's are invalid).
1786c7089f1be946f3ca6e59596f0e0f92d96136e4c8Steve Naroff  SourceLocation endLoc = S->getSynchBody()->getLocStart();
1787a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  const char *endBuf = SM->getCharacterData(endLoc);
1788c7089f1be946f3ca6e59596f0e0f92d96136e4c8Steve Naroff  while (*endBuf != ')') endBuf--;
1789c7089f1be946f3ca6e59596f0e0f92d96136e4c8Steve Naroff  SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
1790a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf = ");\n";
1791a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  // declare a new scope with two variables, _stack and _rethrow.
1792a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1793a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "int buf[18/*32-bit i386*/];\n";
1794a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "char *pointers[4];} _stack;\n";
1795a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "id volatile _rethrow = 0;\n";
1796a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "objc_exception_try_enter(&_stack);\n";
1797a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1798d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(rparenLoc, 1, buf);
1799a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  startLoc = S->getSynchBody()->getLocEnd();
1800a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  startBuf = SM->getCharacterData(startLoc);
18011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1802c7089f1be946f3ca6e59596f0e0f92d96136e4c8Steve Naroff  assert((*startBuf == '}') && "bogus @synchronized block");
1803a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  SourceLocation lastCurlyLoc = startLoc;
1804a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf = "}\nelse {\n";
1805a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1806621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  buf += "}\n";
1807621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  buf += "{ /* implicit finally clause */\n";
1808a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1809b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1810b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  std::string syncBuf;
1811b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  syncBuf += " objc_sync_exit(";
18129d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1813a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                            CK_BitCast,
18149d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                            S->getSynchExpr());
1815a95d3750441ac8ad03e36af8e6e74039c9a3109dTed Kremenek  std::string syncExprBufS;
1816a95d3750441ac8ad03e36af8e6e74039c9a3109dTed Kremenek  llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1817e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  syncExpr->printPretty(syncExprBuf, *Context, 0,
1818e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner                        PrintingPolicy(LangOpts));
1819b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  syncBuf += syncExprBuf.str();
1820b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  syncBuf += ");";
1821b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1822b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  buf += syncBuf;
1823b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1824a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "}\n";
1825a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  buf += "}";
18261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1827d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(lastCurlyLoc, 1, buf);
1828b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1829b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  bool hasReturns = false;
1830b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  HasReturnStmts(S->getSynchBody(), hasReturns);
1831b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  if (hasReturns)
1832b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1833b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1834a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian  return 0;
1835a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian}
1836a0f55792409289d1d343023fa8292cff6355e538Fariborz Jahanian
1837b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroffvoid RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1838b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff{
18398c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff  // Perform a bottom up traversal of all children.
18407502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
18418c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff    if (*CI)
1842b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff      WarnAboutReturnGotoStmts(*CI);
18438c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff
1844b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
18451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Diags.Report(Context->getFullLoc(S->getLocStart()),
18468c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff                 TryFinallyContainsReturnDiag);
18478c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff  }
18488c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff  return;
18498c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff}
18508c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff
1851b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroffvoid RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1852b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff{
1853b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  // Perform a bottom up traversal of all children.
18547502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
1855b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   if (*CI)
1856b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff     HasReturnStmts(*CI, hasReturns);
1857b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1858b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff if (isa<ReturnStmt>(S))
1859b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   hasReturns = true;
1860b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff return;
1861b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff}
1862b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1863b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroffvoid RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1864b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff // Perform a bottom up traversal of all children.
18657502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall for (Stmt::child_range CI = S->children(); CI; ++CI)
1866b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   if (*CI) {
1867b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff     RewriteTryReturnStmts(*CI);
1868b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   }
1869b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff if (isa<ReturnStmt>(S)) {
1870b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   SourceLocation startLoc = S->getLocStart();
1871b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   const char *startBuf = SM->getCharacterData(startLoc);
1872b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1873b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   const char *semiBuf = strchr(startBuf, ';');
1874b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1875b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1876b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1877b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   std::string buf;
1878b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff   buf = "{ objc_exception_try_exit(&_stack); return";
1879b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1880d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer   ReplaceText(startLoc, 6, buf);
1881d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer   InsertText(onePastSemiLoc, "}");
1882b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff }
1883b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff return;
1884b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff}
1885b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1886b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroffvoid RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1887b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  // Perform a bottom up traversal of all children.
18887502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
1889b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    if (*CI) {
1890b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff      RewriteSyncReturnStmts(*CI, syncExitBuf);
1891b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    }
1892b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  if (isa<ReturnStmt>(S)) {
1893b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    SourceLocation startLoc = S->getLocStart();
1894b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    const char *startBuf = SM->getCharacterData(startLoc);
1895b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1896b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    const char *semiBuf = strchr(startBuf, ';');
1897b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1898b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1899b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1900b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    std::string buf;
1901b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    buf = "{ objc_exception_try_exit(&_stack);";
1902b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    buf += syncExitBuf;
1903b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    buf += " return";
1904b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1905d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(startLoc, 6, buf);
1906d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(onePastSemiLoc, "}");
1907b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  }
1908b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff  return;
1909b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff}
1910b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
1911b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
19127573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  // Get the start location and compute the semi location.
19137573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  SourceLocation startLoc = S->getLocStart();
19147573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  const char *startBuf = SM->getCharacterData(startLoc);
19151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19167573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  assert((*startBuf == '@') && "bogus @try location");
19177573098b83e780d1c5bea13b384b610d8f155676Steve Naroff
19187573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  std::string buf;
19197573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  // declare a new scope with two variables, _stack and _rethrow.
19207573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
19217573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  buf += "int buf[18/*32-bit i386*/];\n";
19227573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  buf += "char *pointers[4];} _stack;\n";
19237573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  buf += "id volatile _rethrow = 0;\n";
19247573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  buf += "objc_exception_try_enter(&_stack);\n";
192521867b1188ae19b2834c155b21e97c39ed1b9770Steve Naroff  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
19267573098b83e780d1c5bea13b384b610d8f155676Steve Naroff
1927d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, 4, buf);
19281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19297573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  startLoc = S->getTryBody()->getLocEnd();
19307573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  startBuf = SM->getCharacterData(startLoc);
19317573098b83e780d1c5bea13b384b610d8f155676Steve Naroff
19327573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  assert((*startBuf == '}') && "bogus @try block");
19331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1934c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff  SourceLocation lastCurlyLoc = startLoc;
19358f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor  if (S->getNumCatchStmts()) {
1936c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    startLoc = startLoc.getFileLocWithOffset(1);
1937c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf = " /* @catch begin */ else {\n";
1938c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf += " id _caught = objc_exception_extract(&_stack);\n";
1939c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf += " objc_exception_try_enter (&_stack);\n";
1940c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf += " if (_setjmp(_stack.buf))\n";
1941c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1942c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff    buf += " else { /* @catch continue */";
19431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1944d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(startLoc, buf);
19458bd3dc64d28bdb3b263838a12aca25587bce661bSteve Naroff  } else { /* no catch list */
19468bd3dc64d28bdb3b263838a12aca25587bce661bSteve Naroff    buf = "}\nelse {\n";
19478bd3dc64d28bdb3b263838a12aca25587bce661bSteve Naroff    buf += "  _rethrow = objc_exception_extract(&_stack);\n";
19488bd3dc64d28bdb3b263838a12aca25587bce661bSteve Naroff    buf += "}";
1949d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(lastCurlyLoc, 1, buf);
1950c9ba172447f2e2fe938ae03c3b16b91bda5b4dc3Steve Naroff  }
19517573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  Stmt *lastCatchBody = 0;
19528f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
19538f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1954c00d8e18ad3d903acfeb5d05163ce90713066a3fDouglas Gregor    VarDecl *catchDecl = Catch->getCatchParamDecl();
19557573098b83e780d1c5bea13b384b610d8f155676Steve Naroff
19568f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor    if (I == 0)
19577573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      buf = "if ("; // we are generating code for the first catch clause
19587573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    else
19597573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      buf = "else if (";
19608f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor    startLoc = Catch->getLocStart();
19617573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    startBuf = SM->getCharacterData(startLoc);
19621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19637573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    assert((*startBuf == '@') && "bogus @catch location");
19641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19657573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    const char *lParenLoc = strchr(startBuf, '(');
19667573098b83e780d1c5bea13b384b610d8f155676Steve Naroff
19678f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor    if (Catch->hasEllipsis()) {
1968e12e69223ec279e89ac681023d42184b115e0068Steve Naroff      // Now rewrite the body...
19698f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor      lastCatchBody = Catch->getCatchBody();
1970e12e69223ec279e89ac681023d42184b115e0068Steve Naroff      SourceLocation bodyLoc = lastCatchBody->getLocStart();
1971e12e69223ec279e89ac681023d42184b115e0068Steve Naroff      const char *bodyBuf = SM->getCharacterData(bodyLoc);
19728f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor      assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
197306767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner             "bogus @catch paren location");
1974e12e69223ec279e89ac681023d42184b115e0068Steve Naroff      assert((*bodyBuf == '{') && "bogus @catch body location");
19751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1976e12e69223ec279e89ac681023d42184b115e0068Steve Naroff      buf += "1) { id _tmp = _caught;";
1977d7407dc92c7d19cafce429e7e1cf9819d3fc0b92Daniel Dunbar      Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
19787ba138abd329e591a8f6d5001f60dd7082f71b3bSteve Naroff    } else if (catchDecl) {
19797ba138abd329e591a8f6d5001f60dd7082f71b3bSteve Naroff      QualType t = catchDecl->getType();
1980a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek      if (t == Context->getObjCIdType()) {
19817573098b83e780d1c5bea13b384b610d8f155676Steve Naroff        buf += "1) { ";
1982d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1983506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall      } else if (const ObjCObjectPointerType *Ptr =
1984506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall                   t->getAs<ObjCObjectPointerType>()) {
1985506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall        // Should be a pointer to a class.
1986506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1987506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall        if (IDecl) {
198821867b1188ae19b2834c155b21e97c39ed1b9770Steve Naroff          buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1989506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall          buf += IDecl->getNameAsString();
199021867b1188ae19b2834c155b21e97c39ed1b9770Steve Naroff          buf += "\"), (struct objc_object *)_caught)) { ";
1991d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer          ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
19927573098b83e780d1c5bea13b384b610d8f155676Steve Naroff        }
19937573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      }
19947573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      // Now rewrite the body...
19958f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor      lastCatchBody = Catch->getCatchBody();
19968f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor      SourceLocation rParenLoc = Catch->getRParenLoc();
19977573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      SourceLocation bodyLoc = lastCatchBody->getLocStart();
19987573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      const char *bodyBuf = SM->getCharacterData(bodyLoc);
19997573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      const char *rParenBuf = SM->getCharacterData(rParenLoc);
20007573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      assert((*rParenBuf == ')') && "bogus @catch paren location");
20017573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      assert((*bodyBuf == '{') && "bogus @catch body location");
20021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // Here we replace ") {" with "= _caught;" (which initializes and
20047573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      // declares the @catch parameter).
2005d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
20067ba138abd329e591a8f6d5001f60dd7082f71b3bSteve Naroff    } else {
20077573098b83e780d1c5bea13b384b610d8f155676Steve Naroff      assert(false && "@catch rewrite bug");
20082bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff    }
20097573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  }
20107573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  // Complete the catch list...
20117573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  if (lastCatchBody) {
20127573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    SourceLocation bodyLoc = lastCatchBody->getLocEnd();
201306767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner    assert(*SM->getCharacterData(bodyLoc) == '}' &&
201406767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner           "bogus @catch body location");
20151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2016378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    // Insert the last (implicit) else clause *before* the right curly brace.
2017378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2018378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf = "} /* last catch end */\n";
2019378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += "else {\n";
2020378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += " _rethrow = _caught;\n";
2021378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += " objc_exception_try_exit(&_stack);\n";
2022378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += "} } /* @catch end */\n";
2023378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    if (!S->getFinallyStmt())
2024378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff      buf += "}\n";
2025d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(bodyLoc, buf);
20261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20277573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    // Set lastCurlyLoc
20287573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    lastCurlyLoc = lastCatchBody->getLocEnd();
20297573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  }
2030a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
20317573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    startLoc = finalStmt->getLocStart();
20327573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    startBuf = SM->getCharacterData(startLoc);
20337573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    assert((*startBuf == '@') && "bogus @finally start");
20341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2035d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(startLoc, 8, "/* @finally */");
20361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20377573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    Stmt *body = finalStmt->getFinallyBody();
20387573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    SourceLocation startLoc = body->getLocStart();
20397573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    SourceLocation endLoc = body->getLocEnd();
204006767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner    assert(*SM->getCharacterData(startLoc) == '{' &&
204106767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner           "bogus @finally body location");
20421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    assert(*SM->getCharacterData(endLoc) == '}' &&
204306767518f56cc7ed2a1ae4a37434ad9bdd7890beChris Lattner           "bogus @finally body location");
20441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20457573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    startLoc = startLoc.getFileLocWithOffset(1);
2046d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
20477573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    endLoc = endLoc.getFileLocWithOffset(-1);
2048d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
20491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20507573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    // Set lastCurlyLoc
20517573098b83e780d1c5bea13b384b610d8f155676Steve Naroff    lastCurlyLoc = body->getLocEnd();
20521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20538c56515a0c61b73fc2f02cc96dc3e37650d89d45Steve Naroff    // Now check for any return/continue/go statements within the @try.
2054b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    WarnAboutReturnGotoStmts(S->getTryBody());
2055378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff  } else { /* no finally clause - make sure we synthesize an implicit one */
2056378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf = "{ /* implicit finally clause */\n";
2057378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2058378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2059378f47afeebe3fde2c17e78ae1cf42d2e3beeacfSteve Naroff    buf += "}";
2060d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(lastCurlyLoc, 1, buf);
2061b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff
2062b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    // Now check for any return/continue/go statements within the @try.
2063b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    // The implicit finally clause won't called if the @try contains any
2064b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    // jump statements.
2065b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    bool hasReturns = false;
2066b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    HasReturnStmts(S->getTryBody(), hasReturns);
2067b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff    if (hasReturns)
2068b85e77af052ea495aa47edcce3b1ec8887e53873Steve Naroff      RewriteTryReturnStmts(S->getTryBody());
20697573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  }
20707573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  // Now emit the final closing curly brace...
20717573098b83e780d1c5bea13b384b610d8f155676Steve Naroff  lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
2072d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(lastCurlyLoc, " } /* @try scope end */\n");
2073909f02a69786e94d34d34fc8d4ea3e160bcff775Fariborz Jahanian  return 0;
2074909f02a69786e94d34d34fc8d4ea3e160bcff775Fariborz Jahanian}
2075909f02a69786e94d34d34fc8d4ea3e160bcff775Fariborz Jahanian
20761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump// This can't be done with ReplaceStmt(S, ThrowExpr), since
20771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump// the throw expression is typically a message expression that's already
20782bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff// been rewritten! (which implies the SourceLocation's are invalid).
2079b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
20802bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  // Get the start location and compute the semi location.
20812bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  SourceLocation startLoc = S->getLocStart();
20822bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  const char *startBuf = SM->getCharacterData(startLoc);
20831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20842bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  assert((*startBuf == '@') && "bogus @throw location");
20852bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff
20862bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  std::string buf;
20872bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  /* void objc_exception_throw(id) __attribute__((noreturn)); */
208820ebf8f15df48f27ce2bf7c1b3ae87565235600fSteve Naroff  if (S->getThrowExpr())
208920ebf8f15df48f27ce2bf7c1b3ae87565235600fSteve Naroff    buf = "objc_exception_throw(";
209020ebf8f15df48f27ce2bf7c1b3ae87565235600fSteve Naroff  else // add an implicit argument
209120ebf8f15df48f27ce2bf7c1b3ae87565235600fSteve Naroff    buf = "objc_exception_throw(_caught";
20921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20934ba0acbe835b12b3755d138f364cd67044d7322fSteve Naroff  // handle "@  throw" correctly.
20944ba0acbe835b12b3755d138f364cd67044d7322fSteve Naroff  const char *wBuf = strchr(startBuf, 'w');
20954ba0acbe835b12b3755d138f364cd67044d7322fSteve Naroff  assert((*wBuf == 'w') && "@throw: can't find 'w'");
2096d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(startLoc, wBuf-startBuf+1, buf);
20971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20982bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  const char *semiBuf = strchr(startBuf, ';');
20992bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  assert((*semiBuf == ';') && "@throw: can't find ';'");
21002bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
2101d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  ReplaceText(semiLoc, 1, ");");
21022bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff  return 0;
21032bd03923398add1bcb10d40c283cb0eb8ade74daSteve Naroff}
2104909f02a69786e94d34d34fc8d4ea3e160bcff775Fariborz Jahanian
2105b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
210601c5748c29e75b29cab5fc7d8ad1b173b29c7ecfChris Lattner  // Create a new string expression.
210701c5748c29e75b29cab5fc7d8ad1b173b29c7ecfChris Lattner  QualType StrType = Context->getPointerType(Context->CharTy);
210885f9bceab1542aafff012d4d28e998f4ba16e362Anders Carlsson  std::string StrEncoding;
21090d504c1da852e58ff802545c823ecff3b6c654b8Daniel Dunbar  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
21102085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner  Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
21112085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner                                            StrEncoding.length(), false,StrType,
21122085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner                                            SourceLocation());
2113dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner  ReplaceStmt(Exp, Replacement);
21141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21150750618b0beacdc9b0a9e210a661e4746823ced7Chris Lattner  // Replace this subexpr in the parent.
2116f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2117e64b7771dca65d737dfc49b6137bd69fc1ff6bd2Chris Lattner  return Replacement;
2118311ff02fae0392bee6abe7723cdf5a69b2899a47Chris Lattner}
2119311ff02fae0392bee6abe7723cdf5a69b2899a47Chris Lattner
2120b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
21211a9376408941d65c285ddad8a0f1a2ac518df344Steve Naroff  if (!SelGetUidFunctionDecl)
21221a9376408941d65c285ddad8a0f1a2ac518df344Steve Naroff    SynthSelGetUidFunctionDecl();
2123b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2124b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  // Create a call to sel_registerName("selName").
2125b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  llvm::SmallVector<Expr*, 8> SelExprs;
2126b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  QualType argType = Context->getPointerType(Context->CharTy);
21271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  SelExprs.push_back(StringLiteral::Create(*Context,
21286e94ef5696cfb005d3fc7bbac8dcf7690b64f0a5Ted Kremenek                                       Exp->getSelector().getAsString().c_str(),
2129077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner                                       Exp->getSelector().getAsString().size(),
2130726e168dc09fb23f53c7b004f8e919421ee91806Chris Lattner                                       false, argType, SourceLocation()));
2131b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2132b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff                                                 &SelExprs[0], SelExprs.size());
2133dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner  ReplaceStmt(Exp, SelExp);
2134f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2135b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff  return SelExp;
2136b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff}
2137b42f8415bcfb84c208fd577458ce1bbc2cd800feSteve Naroff
2138b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffCallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
21391d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian  FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
21401d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                                    SourceLocation EndLoc) {
2141ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  // Get the type, we will need to reference it in a couple spots.
2142934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  QualType msgSendType = FD->getType();
21431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2144ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  // Create a reference to the objc_msgSend() declaration.
2145f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  DeclRefExpr *DRE =
2146f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall    new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
21471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2148ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff  // Now, we cast the reference to a pointer to the objc_msgSend type.
2149f04da137288c48879a86e9e1d4014db8e28dbae1Chris Lattner  QualType pToFunc = Context->getPointerType(msgSendType);
215088465d3e996e627bbaa11099b039ddab66d5af2cAnders Carlsson  ImplicitCastExpr *ICE =
2151a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
21525baba9d98364a3525d6afa15a04cdad82fd6dd30John McCall                             DRE, 0, VK_RValue);
21531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2154183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall  const FunctionType *FT = msgSendType->getAs<FunctionType>();
21551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21561d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian  CallExpr *Exp =
21575291c3cec0dbe8ad1d8e7e67e93af2b1586d5400Douglas Gregor    new (Context) CallExpr(*Context, ICE, args, nargs,
2158f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                           FT->getCallResultType(*Context),
2159f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                           VK_RValue, EndLoc);
21601d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian  return Exp;
2161934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff}
2162934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff
2163d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroffstatic bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2164d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff                                const char *&startRef, const char *&endRef) {
2165d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff  while (startBuf < endBuf) {
2166d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    if (*startBuf == '<')
2167d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      startRef = startBuf; // mark the start.
2168d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    if (*startBuf == '>') {
216932174826f58d38c20f376fe64ceac4a278133883Steve Naroff      if (startRef && *startRef == '<') {
217032174826f58d38c20f376fe64ceac4a278133883Steve Naroff        endRef = startBuf; // mark the end.
217132174826f58d38c20f376fe64ceac4a278133883Steve Naroff        return true;
217232174826f58d38c20f376fe64ceac4a278133883Steve Naroff      }
217332174826f58d38c20f376fe64ceac4a278133883Steve Naroff      return false;
2174d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    }
2175d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    startBuf++;
2176d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff  }
2177d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff  return false;
2178d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff}
2179d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff
218061477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanianstatic void scanToNextArgument(const char *&argRef) {
218161477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  int angle = 0;
218261477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
218361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    if (*argRef == '<')
218461477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      angle++;
218561477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    else if (*argRef == '>')
218661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      angle--;
218761477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    argRef++;
218861477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  }
218961477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
219061477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian}
2191291e04b29669d6576e19e35555bbc3cadd2f6649Fariborz Jahanian
2192b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffbool RewriteObjC::needToScanForQualifiers(QualType T) {
219332132a08c0aecc316728d81e1d93726707fde14bFariborz Jahanian  if (T->isObjCQualifiedIdType())
219432132a08c0aecc316728d81e1d93726707fde14bFariborz Jahanian    return true;
219584aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian  if (const PointerType *PT = T->getAs<PointerType>()) {
219684aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian    if (PT->getPointeeType()->isObjCQualifiedIdType())
219784aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian      return true;
219884aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian  }
219984aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian  if (T->isObjCObjectPointerType()) {
220084aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian    T = T->getPointeeType();
220184aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian    return T->isObjCQualifiedInterfaceType();
220284aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian  }
220324f9cab9288368171caaef4bb18b95e4f6083f22Fariborz Jahanian  if (T->isArrayType()) {
220424f9cab9288368171caaef4bb18b95e4f6083f22Fariborz Jahanian    QualType ElemTy = Context->getBaseElementType(T);
220524f9cab9288368171caaef4bb18b95e4f6083f22Fariborz Jahanian    return needToScanForQualifiers(ElemTy);
220624f9cab9288368171caaef4bb18b95e4f6083f22Fariborz Jahanian  }
220784aa9464a4542b7b63d3b1f9953f9169ce536527Fariborz Jahanian  return false;
2208d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff}
2209d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff
22104f95b750534f2111f28434b282bcbd5656002816Steve Naroffvoid RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
22114f95b750534f2111f28434b282bcbd5656002816Steve Naroff  QualType Type = E->getType();
22124f95b750534f2111f28434b282bcbd5656002816Steve Naroff  if (needToScanForQualifiers(Type)) {
2213cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    SourceLocation Loc, EndLoc;
22141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2215cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2216cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff      Loc = ECE->getLParenLoc();
2217cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff      EndLoc = ECE->getRParenLoc();
2218cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    } else {
2219cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff      Loc = E->getLocStart();
2220cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff      EndLoc = E->getLocEnd();
2221cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    }
2222cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    // This will defend against trying to rewrite synthesized expressions.
2223cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    if (Loc.isInvalid() || EndLoc.isInvalid())
2224cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff      return;
2225cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff
22264f95b750534f2111f28434b282bcbd5656002816Steve Naroff    const char *startBuf = SM->getCharacterData(Loc);
2227cda658e90d7ffe0ece23d741ff82cf764108f66cSteve Naroff    const char *endBuf = SM->getCharacterData(EndLoc);
22284f95b750534f2111f28434b282bcbd5656002816Steve Naroff    const char *startRef = 0, *endRef = 0;
22294f95b750534f2111f28434b282bcbd5656002816Steve Naroff    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
22304f95b750534f2111f28434b282bcbd5656002816Steve Naroff      // Get the locations of the startRef, endRef.
22314f95b750534f2111f28434b282bcbd5656002816Steve Naroff      SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
22324f95b750534f2111f28434b282bcbd5656002816Steve Naroff      SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
22334f95b750534f2111f28434b282bcbd5656002816Steve Naroff      // Comment out the protocol references.
2234d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(LessLoc, "/*");
2235d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(GreaterLoc, "*/");
22364f95b750534f2111f28434b282bcbd5656002816Steve Naroff    }
22374f95b750534f2111f28434b282bcbd5656002816Steve Naroff  }
22384f95b750534f2111f28434b282bcbd5656002816Steve Naroff}
22394f95b750534f2111f28434b282bcbd5656002816Steve Naroff
2240b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
224161477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  SourceLocation Loc;
224261477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  QualType Type;
224372564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor  const FunctionProtoType *proto = 0;
224461477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
224561477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    Loc = VD->getLocation();
224661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    Type = VD->getType();
224761477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  }
224861477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
224961477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    Loc = FD->getLocation();
225061477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    // Check for ObjC 'id' and class types that have been adorned with protocol
225161477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2252183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
225361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    assert(funcType && "missing function type");
225472564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    proto = dyn_cast<FunctionProtoType>(funcType);
225561477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    if (!proto)
225661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      return;
225761477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    Type = proto->getResultType();
225861477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  }
22593d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
22603d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    Loc = FD->getLocation();
22613d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    Type = FD->getType();
22623d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff  }
226361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  else
2264e66894c3dea9aeab4403e67bf5baabc20da61cb3Fariborz Jahanian    return;
22651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
226661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  if (needToScanForQualifiers(Type)) {
2267d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    // Since types are unique, we need to scan the buffer.
22681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2269d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    const char *endBuf = SM->getCharacterData(Loc);
2270d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    const char *startBuf = endBuf;
22716cafbf2a678c95d4cdc09ecaa782319bbcf56944Steve Naroff    while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2272d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      startBuf--; // scan backward (from the decl location) for return type.
2273d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    const char *startRef = 0, *endRef = 0;
2274d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2275d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      // Get the locations of the startRef, endRef.
2276d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2277d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2278d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      // Comment out the protocol references.
2279d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(LessLoc, "/*");
2280d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(GreaterLoc, "*/");
2281d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    }
2282d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff  }
228361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  if (!proto)
228461477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      return; // most likely, was a variable
22859165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff  // Now check arguments.
228661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  const char *startBuf = SM->getCharacterData(Loc);
228761477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian  const char *startFuncBuf = startBuf;
22889165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff  for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2289d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff    if (needToScanForQualifiers(proto->getArgType(i))) {
2290d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      // Since types are unique, we need to scan the buffer.
22911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2292d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      const char *endBuf = startBuf;
229361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      // scan forward (from the decl location) for argument types.
229461477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      scanToNextArgument(endBuf);
2295d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      const char *startRef = 0, *endRef = 0;
2296d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2297d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff        // Get the locations of the startRef, endRef.
22981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        SourceLocation LessLoc =
2299291e04b29669d6576e19e35555bbc3cadd2f6649Fariborz Jahanian          Loc.getFileLocWithOffset(startRef-startFuncBuf);
23001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        SourceLocation GreaterLoc =
2301291e04b29669d6576e19e35555bbc3cadd2f6649Fariborz Jahanian          Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
2302d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff        // Comment out the protocol references.
2303d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        InsertText(LessLoc, "/*");
2304d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        InsertText(GreaterLoc, "*/");
2305d5255f55ebe8803ee10b01589a64156e5e9cde5eSteve Naroff      }
230661477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      startBuf = ++endBuf;
230761477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    }
230861477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    else {
2309aba49d10daaedbc9e8bf6f4c6bfbfa6ea668baa6Steve Naroff      // If the function name is derived from a macro expansion, then the
2310aba49d10daaedbc9e8bf6f4c6bfbfa6ea668baa6Steve Naroff      // argument buffer will not follow the name. Need to speak with Chris.
2311aba49d10daaedbc9e8bf6f4c6bfbfa6ea668baa6Steve Naroff      while (*startBuf && *startBuf != ')' && *startBuf != ',')
231261477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian        startBuf++; // scan forward (from the decl location) for argument types.
231361477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian      startBuf++;
231461477f7a4ccd3ac785afd9708d77a53869a53a76Fariborz Jahanian    }
23159165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff  }
23169165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff}
23179165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff
23184c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanianvoid RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
23194c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  QualType QT = ND->getType();
23204c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  const Type* TypePtr = QT->getAs<Type>();
23214c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  if (!isa<TypeOfExprType>(TypePtr))
23224c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    return;
23234c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  while (isa<TypeOfExprType>(TypePtr)) {
23244c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
23254c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
23264c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    TypePtr = QT->getAs<Type>();
23274c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  }
23284c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  // FIXME. This will not work for multiple declarators; as in:
23294c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  // __typeof__(a) b,c,d;
2330fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
23314c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
23324c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  const char *startBuf = SM->getCharacterData(DeclLoc);
23334c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  if (ND->getInit()) {
23344c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    std::string Name(ND->getNameAsString());
23354c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    TypeAsString += " " + Name + " = ";
23364c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    Expr *E = ND->getInit();
23374c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    SourceLocation startLoc;
23384c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
23394c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian      startLoc = ECE->getLParenLoc();
23404c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    else
23414c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian      startLoc = E->getLocStart();
23424c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    startLoc = SM->getInstantiationLoc(startLoc);
23434c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    const char *endBuf = SM->getCharacterData(startLoc);
2344d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
23454c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  }
23464c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  else {
23474c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    SourceLocation X = ND->getLocEnd();
23484c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    X = SM->getInstantiationLoc(X);
23494c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian    const char *endBuf = SM->getCharacterData(X);
2350d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
23514c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian  }
23524c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian}
23534c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian
2354a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2355b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthSelGetUidFunctionDecl() {
2356a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2357a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian  llvm::SmallVector<QualType, 16> ArgTys;
23580953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2359e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType getFuncType =
2360e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2361ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
23621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                           SourceLocation(),
2363a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                           SelGetUidIdent, getFuncType, 0,
2364d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                           SC_Extern,
2365d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                           SC_None, false);
2366a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian}
2367a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian
2368b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
236909b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  // declared in <objc/objc.h>
237051efe56116a6283ba707cfb8bf8b4e0b13cb41acDouglas Gregor  if (FD->getIdentifier() &&
23714087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar      FD->getName() == "sel_registerName") {
237209b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    SelGetUidFunctionDecl = FD;
23739165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff    return;
23749165ad378f8d25eb5c378a8e9540089afce421ffSteve Naroff  }
2375a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  RewriteObjCQualifiedInterfaceTypes(FD);
237609b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff}
237709b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff
2378fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbarvoid RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2379fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  std::string TypeString(Type.getAsString(Context->PrintingPolicy));
238052b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian  const char *argPtr = TypeString.c_str();
238152b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian  if (!strchr(argPtr, '^')) {
238252b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian    Str += TypeString;
238352b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian    return;
238452b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian  }
238552b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian  while (*argPtr) {
238652b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian    Str += (*argPtr == '^' ? '*' : *argPtr);
238752b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian    argPtr++;
238852b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian  }
238952b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian}
239052b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian
2391e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian// FIXME. Consolidate this routine with RewriteBlockPointerType.
2392fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbarvoid RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2393fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar                                                  ValueDecl *VD) {
2394e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian  QualType Type = VD->getType();
2395fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  std::string TypeString(Type.getAsString(Context->PrintingPolicy));
2396e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian  const char *argPtr = TypeString.c_str();
2397e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian  int paren = 0;
2398e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian  while (*argPtr) {
2399e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    switch (*argPtr) {
2400e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      case '(':
2401e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        Str += *argPtr;
2402e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        paren++;
2403e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        break;
2404e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      case ')':
2405e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        Str += *argPtr;
2406e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        paren--;
2407e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        break;
2408e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      case '^':
2409e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        Str += '*';
2410e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        if (paren == 1)
2411e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian          Str += VD->getNameAsString();
2412e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        break;
2413e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      default:
2414e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        Str += *argPtr;
2415e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian        break;
2416e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    }
2417e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    argPtr++;
2418e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian  }
2419e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian}
2420e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian
2421e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian
2422abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanianvoid RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2423abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2424abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2425abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2426abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  if (!proto)
2427abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    return;
2428abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  QualType Type = proto->getResultType();
2429fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  std::string FdStr = Type.getAsString(Context->PrintingPolicy);
2430abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  FdStr += " ";
24314087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  FdStr += FD->getName();
2432abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  FdStr +=  "(";
2433abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  unsigned numArgs = proto->getNumArgs();
2434abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  for (unsigned i = 0; i < numArgs; i++) {
2435abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    QualType ArgType = proto->getArgType(i);
243652b2e1e0775a7a50616b02be4af92295c61e37f5Fariborz Jahanian    RewriteBlockPointerType(FdStr, ArgType);
2437abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    if (i+1 < numArgs)
2438abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian      FdStr += ", ";
2439abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  }
2440abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  FdStr +=  ");\n";
2441d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(FunLocStart, FdStr);
2442abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  CurFunctionDeclToDeclareForBlock = 0;
2443abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian}
2444abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian
2445c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2446b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthSuperContructorFunctionDecl() {
2447c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  if (SuperContructorFunctionDecl)
2448c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff    return;
244946a98a7df016b4a6835a1902c2f8ff2a3a8012baSteve Naroff  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2450c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  llvm::SmallVector<QualType, 16> ArgTys;
2451c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  QualType argT = Context->getObjCIdType();
2452c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  assert(!argT.isNull() && "Can't find 'id' type");
2453c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  ArgTys.push_back(argT);
2454c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff  ArgTys.push_back(argT);
2455e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2456e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size());
2457ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                         SourceLocation(),
2459a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                         msgSendIdent, msgSendType, 0,
2460d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_Extern,
2461d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_None, false);
2462c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff}
2463c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff
246409b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2465b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthMsgSendFunctionDecl() {
246609b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
246709b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  llvm::SmallVector<QualType, 16> ArgTys;
2468a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  QualType argT = Context->getObjCIdType();
246909b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  assert(!argT.isNull() && "Can't find 'id' type");
247009b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  ArgTys.push_back(argT);
2471a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  argT = Context->getObjCSelType();
247209b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  assert(!argT.isNull() && "Can't find 'SEL' type");
247309b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  ArgTys.push_back(argT);
2474e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2475e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size(),
2476e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               true /*isVariadic*/);
2477ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
24780ed844b04ea4387caa4e1cf3dc375d269657536bChris Lattner                                         SourceLocation(),
2479a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                         msgSendIdent, msgSendType, 0,
2480d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_Extern,
2481d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_None, false);
248209b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff}
248309b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff
2484874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2485b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2486874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2487874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  llvm::SmallVector<QualType, 16> ArgTys;
2488465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
24890ed844b04ea4387caa4e1cf3dc375d269657536bChris Lattner                                      SourceLocation(),
2490df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                                      &Context->Idents.get("objc_super"));
2491874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2492874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2493874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  ArgTys.push_back(argT);
2494a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  argT = Context->getObjCSelType();
2495874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  assert(!argT.isNull() && "Can't find 'SEL' type");
2496874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  ArgTys.push_back(argT);
2497e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2498e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size(),
2499e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               true /*isVariadic*/);
2500ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
25011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              SourceLocation(),
2502a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                              msgSendIdent, msgSendType, 0,
2503d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_Extern,
2504d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_None, false);
2505874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff}
2506874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff
250780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2508b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthMsgSendStretFunctionDecl() {
250980a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
251080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  llvm::SmallVector<QualType, 16> ArgTys;
2511a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  QualType argT = Context->getObjCIdType();
251280a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  assert(!argT.isNull() && "Can't find 'id' type");
251380a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  ArgTys.push_back(argT);
2514a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  argT = Context->getObjCSelType();
251580a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  assert(!argT.isNull() && "Can't find 'SEL' type");
251680a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  ArgTys.push_back(argT);
2517e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2518e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size(),
2519e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               true /*isVariadic*/);
2520ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
25211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                         SourceLocation(),
2522a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                         msgSendIdent, msgSendType, 0,
2523d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_Extern,
2524d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                         SC_None, false);
252580a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian}
252680a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian
25271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump// SynthMsgSendSuperStretFunctionDecl -
252880a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2529b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
25301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  IdentifierInfo *msgSendIdent =
253180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    &Context->Idents.get("objc_msgSendSuper_stret");
253280a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  llvm::SmallVector<QualType, 16> ArgTys;
2533465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
25340ed844b04ea4387caa4e1cf3dc375d269657536bChris Lattner                                      SourceLocation(),
2535df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                                      &Context->Idents.get("objc_super"));
253680a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
253780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
253880a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  ArgTys.push_back(argT);
2539a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  argT = Context->getObjCSelType();
254080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  assert(!argT.isNull() && "Can't find 'SEL' type");
254180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  ArgTys.push_back(argT);
2542e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2543e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size(),
2544e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               true /*isVariadic*/);
2545ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
25461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                       SourceLocation(),
2547a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                              msgSendIdent, msgSendType, 0,
2548d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_Extern,
2549d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_None, false);
255080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian}
255180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian
25521284db8d85782c4eb1d41eb02358613c8681f07fSteve Naroff// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2553b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2554acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2555acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  llvm::SmallVector<QualType, 16> ArgTys;
2556a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  QualType argT = Context->getObjCIdType();
2557acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  assert(!argT.isNull() && "Can't find 'id' type");
2558acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  ArgTys.push_back(argT);
2559a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  argT = Context->getObjCSelType();
2560acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  assert(!argT.isNull() && "Can't find 'SEL' type");
2561acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  ArgTys.push_back(argT);
2562e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2563e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               &ArgTys[0], ArgTys.size(),
2564e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                               true /*isVariadic*/);
2565ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
25661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              SourceLocation(),
2567a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                              msgSendIdent, msgSendType, 0,
2568d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_Extern,
2569d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_None, false);
2570acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian}
2571acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian
257209b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2573b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthGetClassFunctionDecl() {
257409b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
257509b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  llvm::SmallVector<QualType, 16> ArgTys;
25760953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2577e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2578e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                                &ArgTys[0], ArgTys.size());
2579ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
25801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                          SourceLocation(),
2581a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                          getClassIdent, getClassType, 0,
2582d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_Extern,
2583d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                          SC_None, false);
258409b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff}
258509b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff
2586d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2587d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanianvoid RewriteObjC::SynthGetSuperClassFunctionDecl() {
2588d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  IdentifierInfo *getSuperClassIdent =
2589d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian    &Context->Idents.get("class_getSuperclass");
2590d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  llvm::SmallVector<QualType, 16> ArgTys;
2591d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  ArgTys.push_back(Context->getObjCClassType());
2592e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2593e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                                &ArgTys[0], ArgTys.size());
2594d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
259516573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                                   SourceLocation(),
259616573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                                   getSuperClassIdent,
259716573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                                   getClassType, 0,
2598d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                                   SC_Extern,
2599d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                                   SC_None,
260016573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                                   false);
2601d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian}
2602d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian
26039bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
2604b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthGetMetaClassFunctionDecl() {
26059bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
26069bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff  llvm::SmallVector<QualType, 16> ArgTys;
26070953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2608e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2609e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall                                                &ArgTys[0], ArgTys.size());
2610ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
26111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              SourceLocation(),
2612a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                              getClassIdent, getClassType, 0,
2613d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_Extern,
2614d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                              SC_None, false);
26159bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff}
26169bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff
2617b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2618d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  QualType strType = getConstantStringStructType();
2619d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff
2620d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  std::string S = "__NSConstantStringImpl_";
26217691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff
26227691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  std::string tmpName = InFileName;
26237691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  unsigned i;
26247691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  for (i=0; i < tmpName.length(); i++) {
26257691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff    char c = tmpName.at(i);
26267691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff    // replace any non alphanumeric characters with '_'.
26277691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff    if (!isalpha(c) && (c < '0' || c > '9'))
26287691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff      tmpName[i] = '_';
26297691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  }
26307691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  S += tmpName;
26317691d9b77b01bf9df6c51e7cb8b43ec150f50b7bSteve Naroff  S += "_";
2632d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  S += utostr(NumObjCStringLiterals++);
2633d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff
2634ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "static __NSConstantStringImpl " + S;
2635ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2636ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += "0x000007c8,"; // utf8_str
2637d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  // The pretty printer for StringLiteral handles escape characters properly.
2638a95d3750441ac8ad03e36af8e6e74039c9a3109dTed Kremenek  std::string prettyBufS;
2639a95d3750441ac8ad03e36af8e6e74039c9a3109dTed Kremenek  llvm::raw_string_ostream prettyBuf(prettyBufS);
2640e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  Exp->getString()->printPretty(prettyBuf, *Context, 0,
2641e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner                                PrintingPolicy(LangOpts));
2642ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += prettyBuf.str();
2643ba92b2ed976e29ea05f0f5afabaf9488c1096bebSteve Naroff  Preamble += ",";
2644fd5b76fe99a123630321b45667a78f1a15be7241Steve Naroff  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
26451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
26461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2647d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer                                    &Context->Idents.get(S), strType, 0,
2648d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                    SC_Static, SC_None);
2649f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2650f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                               SourceLocation());
26512de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall  Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
26521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                 Context->getPointerType(DRE->getType()),
2653f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                           VK_RValue, OK_Ordinary,
2654f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                           SourceLocation());
26559698464266660346fa2da1bddc3e6404a9819b25Steve Naroff  // cast to NSConstantString *
26569d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2657a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                            CK_BitCast, Unop);
2658dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner  ReplaceStmt(Exp, cast);
2659f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
26609698464266660346fa2da1bddc3e6404a9819b25Steve Naroff  return cast;
2661beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff}
2662beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff
2663874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2664b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffQualType RewriteObjC::getSuperStructType() {
2665874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  if (!SuperStructDecl) {
2666465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
26671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                         SourceLocation(),
2668df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                                         &Context->Idents.get("objc_super"));
2669874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    QualType FieldTypes[2];
26701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2671874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    // struct objc_object *receiver;
26721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[0] = Context->getObjCIdType();
2673874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    // struct objc_class *super;
26741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[1] = Context->getObjCClassType();
267544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
2676874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    // Create fields
267744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    for (unsigned i = 0; i < 2; ++i) {
26781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
26791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                 SourceLocation(), 0,
2680a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                                 FieldTypes[i], 0,
2681a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                                 /*BitWidth=*/0,
26824afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor                                                 /*Mutable=*/false));
268344b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    }
26841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2685838db383b69b9fb55f55c8e9546477df198a4faaDouglas Gregor    SuperStructDecl->completeDefinition();
2686874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  }
2687874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  return Context->getTagDeclType(SuperStructDecl);
2688874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff}
2689874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff
2690b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffQualType RewriteObjC::getConstantStringStructType() {
2691d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  if (!ConstantStringDecl) {
2692465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
26931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                            SourceLocation(),
2694df042e6c2bf06b2d9ed53c52469599ac1bd93a3fTed Kremenek                         &Context->Idents.get("__NSConstantStringImpl"));
2695d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    QualType FieldTypes[4];
26961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2697d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    // struct objc_object *receiver;
26981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[0] = Context->getObjCIdType();
2699d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    // int flags;
27001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[1] = Context->IntTy;
2701d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    // char *str;
27021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[2] = Context->getPointerType(Context->CharTy);
2703d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    // long length;
27041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FieldTypes[3] = Context->LongTy;
270544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
2706d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff    // Create fields
270744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    for (unsigned i = 0; i < 4; ++i) {
27081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
27091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                    ConstantStringDecl,
271044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                                    SourceLocation(), 0,
2711a1d5662d96465f0fddf8819d245da4d19b892effArgyrios Kyrtzidis                                                    FieldTypes[i], 0,
271244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                                    /*BitWidth=*/0,
27134afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor                                                    /*Mutable=*/true));
271444b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    }
271544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
2716838db383b69b9fb55f55c8e9546477df198a4faaDouglas Gregor    ConstantStringDecl->completeDefinition();
2717d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  }
2718d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff  return Context->getTagDeclType(ConstantStringDecl);
2719d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff}
2720d82a9ab4540899e24c96a389c5488381c5551c78Steve Naroff
27211d35b168348a308696d1fce29a18c14143f61d6aFariborz JahanianStmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
27221d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                    SourceLocation StartLoc,
27231d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                    SourceLocation EndLoc) {
2724a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian  if (!SelGetUidFunctionDecl)
2725a70711b296953bfe2fc17351f3908dcc417c404aFariborz Jahanian    SynthSelGetUidFunctionDecl();
272609b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  if (!MsgSendFunctionDecl)
272709b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    SynthMsgSendFunctionDecl();
2728874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  if (!MsgSendSuperFunctionDecl)
2729874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    SynthMsgSendSuperFunctionDecl();
273080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  if (!MsgSendStretFunctionDecl)
273180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    SynthMsgSendStretFunctionDecl();
273280a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  if (!MsgSendSuperStretFunctionDecl)
273380a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    SynthMsgSendSuperStretFunctionDecl();
2734acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian  if (!MsgSendFpretFunctionDecl)
2735acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian    SynthMsgSendFpretFunctionDecl();
273609b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff  if (!GetClassFunctionDecl)
273709b266eb2a014b7af4dc06126c47b7629030ce09Steve Naroff    SynthGetClassFunctionDecl();
2738d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian  if (!GetSuperClassFunctionDecl)
2739d314e9e12326c2fd8f140adc4c769d13b483b3f6Fariborz Jahanian    SynthGetSuperClassFunctionDecl();
27409bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff  if (!GetMetaClassFunctionDecl)
27419bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff    SynthGetMetaClassFunctionDecl();
27421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2743874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  // default to objc_msgSend().
274480a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
274580a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  // May need to use objc_msgSend_stret() as well.
274680a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  FunctionDecl *MsgSendStretFlavor = 0;
2747621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2748621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    QualType resultType = mDecl->getResultType();
2749fb87b89fc9eb103e19fb8e4b925c23f0bd091b99Douglas Gregor    if (resultType->isRecordType())
275080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian      MsgSendStretFlavor = MsgSendStretFunctionDecl;
27518b51fd76319d8b71f401cc6ad56e6f4f7be77958Chris Lattner    else if (resultType->isRealFloatingType())
2752acb4977dd3b6a678bfbdb80781bfe3c617be3f24Fariborz Jahanian      MsgSendFlavor = MsgSendFpretFunctionDecl;
275380a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  }
27541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2755934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  // Synthesize a call to objc_msgSend().
2756934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  llvm::SmallVector<Expr*, 8> MsgExprs;
275704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  switch (Exp->getReceiverKind()) {
275804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  case ObjCMessageExpr::SuperClass: {
275904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgSendFlavor = MsgSendSuperFunctionDecl;
276004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    if (MsgSendStretFlavor)
276104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
276204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
276304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
276404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
276504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
276604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    llvm::SmallVector<Expr*, 4> InitExprs;
276704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
276804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // set the receiver to self, the first argument to all methods.
276904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    InitExprs.push_back(
277004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2771a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                               CK_BitCast,
277204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2773f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             Context->getObjCIdType(),
2774f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             VK_RValue,
2775f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             SourceLocation()))
277604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                        ); // set the 'receiver'.
277704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
277804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
277904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    llvm::SmallVector<Expr*, 8> ClsExprs;
278004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    QualType argType = Context->getPointerType(Context->CharTy);
278104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.push_back(StringLiteral::Create(*Context,
278204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   ClassDecl->getIdentifier()->getNameStart(),
278304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   ClassDecl->getIdentifier()->getLength(),
278404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   false, argType, SourceLocation()));
278504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
278604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 &ClsExprs[0],
278704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 ClsExprs.size(),
278804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 StartLoc,
278904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 EndLoc);
279004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (Class)objc_getClass("CurrentClass")
279104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
279204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                             Context->getObjCClassType(),
2793a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                             CK_BitCast, Cls);
279404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.clear();
279504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.push_back(ArgExpr);
279604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
279704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                       &ClsExprs[0], ClsExprs.size(),
279804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                       StartLoc, EndLoc);
279904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
280004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
280104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // To turn off a warning, type-cast to 'id'
280204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    InitExprs.push_back( // set 'super class', using class_getSuperclass().
280304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                        NoTypeInfoCStyleCastExpr(Context,
280404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 Context->getObjCIdType(),
2805a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                 CK_BitCast, Cls));
280604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // struct objc_super
280704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    QualType superType = getSuperStructType();
280804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    Expr *SuperRep;
280904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
281004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    if (LangOpts.Microsoft) {
281104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SynthSuperContructorFunctionDecl();
281204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // Simulate a contructor call...
281304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2814f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   superType, VK_LValue,
2815f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   SourceLocation());
281604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
281704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                        InitExprs.size(),
2818f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        superType, VK_LValue,
2819f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        SourceLocation());
282004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // The code for super is a little tricky to prevent collision with
282104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // the structure definition in the header. The rewriter has it's own
282204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // internal definition (__rw_objc_super) that is uses. This is why
282304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // we need the cast below. For example:
282404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
282504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      //
28262de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
282704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                               Context->getPointerType(SuperRep->getType()),
2828f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             VK_RValue, OK_Ordinary,
2829f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             SourceLocation());
283004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = NoTypeInfoCStyleCastExpr(Context,
283104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                          Context->getPointerType(superType),
2832a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                          CK_BitCast, SuperRep);
28339bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff    } else {
283404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // (struct objc_super) { <exprs from above> }
283504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      InitListExpr *ILE =
283604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor        new (Context) InitListExpr(*Context, SourceLocation(),
283704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   &InitExprs[0], InitExprs.size(),
283804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   SourceLocation());
283904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      TypeSourceInfo *superTInfo
284004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor        = Context->getTrivialTypeSourceInfo(superType);
284104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2842f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   superType, VK_LValue,
2843f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   ILE, false);
284404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // struct objc_super *
28452de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
284604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                               Context->getPointerType(SuperRep->getType()),
2847f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             VK_RValue, OK_Ordinary,
2848f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             SourceLocation());
28499bcb5fc1fd48c1f40c6a3b5a59130ebc313b4957Steve Naroff    }
285004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExprs.push_back(SuperRep);
285104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    break;
285204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  }
285304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
285404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  case ObjCMessageExpr::Class: {
285504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    llvm::SmallVector<Expr*, 8> ClsExprs;
285604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    QualType argType = Context->getPointerType(Context->CharTy);
285704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ObjCInterfaceDecl *Class
2858506b57e8b79d7dc2c367bf2ee7ec95420ad3fc8fJohn McCall      = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
285904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    IdentifierInfo *clsName = Class->getIdentifier();
286004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.push_back(StringLiteral::Create(*Context,
286104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                             clsName->getNameStart(),
286204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                             clsName->getLength(),
286304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                             false, argType,
286404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                             SourceLocation()));
286504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
286604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 &ClsExprs[0],
286704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 ClsExprs.size(),
286804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 StartLoc, EndLoc);
286904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExprs.push_back(Cls);
287004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    break;
287104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  }
287204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
287304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  case ObjCMessageExpr::SuperInstance:{
287404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgSendFlavor = MsgSendSuperFunctionDecl;
287504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    if (MsgSendStretFlavor)
287604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
287704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
287804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
287904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    llvm::SmallVector<Expr*, 4> InitExprs;
288004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
288104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    InitExprs.push_back(
288204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2883a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                               CK_BitCast,
288404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2885f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             Context->getObjCIdType(),
2886f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                             VK_RValue, SourceLocation()))
288704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                        ); // set the 'receiver'.
288804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
288904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
289004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    llvm::SmallVector<Expr*, 8> ClsExprs;
289104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    QualType argType = Context->getPointerType(Context->CharTy);
289204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.push_back(StringLiteral::Create(*Context,
289304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   ClassDecl->getIdentifier()->getNameStart(),
289404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   ClassDecl->getIdentifier()->getLength(),
289504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   false, argType, SourceLocation()));
289604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
289704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 &ClsExprs[0],
289804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 ClsExprs.size(),
289904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 StartLoc, EndLoc);
290004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (Class)objc_getClass("CurrentClass")
290104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
290204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                                 Context->getObjCClassType(),
2903a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                 CK_BitCast, Cls);
290404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.clear();
290504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    ClsExprs.push_back(ArgExpr);
290604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
290704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                       &ClsExprs[0], ClsExprs.size(),
290804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                       StartLoc, EndLoc);
290904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
291004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
291104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // To turn off a warning, type-cast to 'id'
291204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    InitExprs.push_back(
291304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // set 'super class', using class_getSuperclass().
291404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2915a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                               CK_BitCast, Cls));
291604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // struct objc_super
291704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    QualType superType = getSuperStructType();
291804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    Expr *SuperRep;
291904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
292004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    if (LangOpts.Microsoft) {
292104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SynthSuperContructorFunctionDecl();
292204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // Simulate a contructor call...
292304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2924f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   superType, VK_LValue,
2925f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   SourceLocation());
292604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
292704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                        InitExprs.size(),
2928f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        superType, VK_LValue, SourceLocation());
292904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // The code for super is a little tricky to prevent collision with
293004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // the structure definition in the header. The rewriter has it's own
293104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // internal definition (__rw_objc_super) that is uses. This is why
293204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // we need the cast below. For example:
293304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
293404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      //
29352de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
293604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                               Context->getPointerType(SuperRep->getType()),
2937f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                               VK_RValue, OK_Ordinary,
293804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                               SourceLocation());
293904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = NoTypeInfoCStyleCastExpr(Context,
294004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                               Context->getPointerType(superType),
2941a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                               CK_BitCast, SuperRep);
2942874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    } else {
294304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      // (struct objc_super) { <exprs from above> }
294404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      InitListExpr *ILE =
294504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor        new (Context) InitListExpr(*Context, SourceLocation(),
294604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   &InitExprs[0], InitExprs.size(),
294704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor                                   SourceLocation());
294804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      TypeSourceInfo *superTInfo
294904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor        = Context->getTrivialTypeSourceInfo(superType);
295004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2951f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   superType, VK_RValue, ILE,
2952f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   false);
2953874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff    }
295404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExprs.push_back(SuperRep);
295504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    break;
29566568d4dd760f37a945f7c9a249b1500de0777a2dSteve Naroff  }
295704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
295804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  case ObjCMessageExpr::Instance: {
295904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // Remove all type-casts because it may contain objc-style types; e.g.
296004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    // Foo<Proto> *.
296104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    Expr *recExpr = Exp->getInstanceReceiver();
296204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
296304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor      recExpr = CE->getSubExpr();
296404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2965a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                       CK_BitCast, recExpr);
296604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    MsgExprs.push_back(recExpr);
296704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor    break;
296804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  }
296904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor  }
297004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor
2971beaf299a2701c5559a4e5d76b0c40f805afb8e6aSteve Naroff  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2972934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  llvm::SmallVector<Expr*, 8> SelExprs;
2973934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  QualType argType = Context->getPointerType(Context->CharTy);
29741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  SelExprs.push_back(StringLiteral::Create(*Context,
29756e94ef5696cfb005d3fc7bbac8dcf7690b64f0a5Ted Kremenek                                       Exp->getSelector().getAsString().c_str(),
2976077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner                                       Exp->getSelector().getAsString().size(),
2977726e168dc09fb23f53c7b004f8e919421ee91806Chris Lattner                                       false, argType, SourceLocation()));
2978934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
29791d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                                 &SelExprs[0], SelExprs.size(),
29801d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                                  StartLoc,
29811d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                                  EndLoc);
2982934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  MsgExprs.push_back(SelExp);
29831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2984934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  // Now push any user supplied arguments.
2985934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
29866568d4dd760f37a945f7c9a249b1500de0777a2dSteve Naroff    Expr *userExpr = Exp->getArg(i);
29877e3411b23eb3724da5461dc6d6f97d14b3b0a52fSteve Naroff    // Make all implicit casts explicit...ICE comes in handy:-)
29887e3411b23eb3724da5461dc6d6f97d14b3b0a52fSteve Naroff    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
29897e3411b23eb3724da5461dc6d6f97d14b3b0a52fSteve Naroff      // Reuse the ICE type, it is exactly what the doctor ordered.
299049badde06e066d058d6c7fcf4e628a72999b65a9Douglas Gregor      QualType type = ICE->getType()->isObjCQualifiedIdType()
2991a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek                                ? Context->getObjCIdType()
299249badde06e066d058d6c7fcf4e628a72999b65a9Douglas Gregor                                : ICE->getType();
29931f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      // Make sure we convert "type (^)(...)" to "type (*)(...)".
29944fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      (void)convertBlockPointerToFunctionPointer(type);
2995a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
29969d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                          userExpr);
2997d58fabf7ed279be18a5e82617f809c9deff9be67Fariborz Jahanian    }
2998d58fabf7ed279be18a5e82617f809c9deff9be67Fariborz Jahanian    // Make id<P...> cast into an 'id' cast.
29996eec8e883de118b431e3ead5b1e604a6ac68ff6bDouglas Gregor    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3000a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek      if (CE->getType()->isObjCQualifiedIdType()) {
30016eec8e883de118b431e3ead5b1e604a6ac68ff6bDouglas Gregor        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3002d58fabf7ed279be18a5e82617f809c9deff9be67Fariborz Jahanian          userExpr = CE->getSubExpr();
30039d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3004a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                            CK_BitCast, userExpr);
3005d58fabf7ed279be18a5e82617f809c9deff9be67Fariborz Jahanian      }
30061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
30076568d4dd760f37a945f7c9a249b1500de0777a2dSteve Naroff    MsgExprs.push_back(userExpr);
3008621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    // We've transferred the ownership to MsgExprs. For now, we *don't* null
3009621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    // out the argument in the original expression (since we aren't deleting
3010f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3011621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    //Exp->setArg(i, 0);
3012934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  }
3013ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Generate the funky cast.
3014ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  CastExpr *cast;
3015ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  llvm::SmallVector<QualType, 8> ArgTypes;
3016ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  QualType returnType;
30171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3018ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Push 'id' and 'SEL', the 2 implicit arguments.
3019c3a438c39ca6061965007c273727f27dfaa4a694Steve Naroff  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3020c3a438c39ca6061965007c273727f27dfaa4a694Steve Naroff    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3021c3a438c39ca6061965007c273727f27dfaa4a694Steve Naroff  else
3022a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    ArgTypes.push_back(Context->getObjCIdType());
3023a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ArgTypes.push_back(Context->getObjCSelType());
302489951a86b594513c2a013532ed45d197413b1087Chris Lattner  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3025ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff    // Push any user argument types.
302689951a86b594513c2a013532ed45d197413b1087Chris Lattner    for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
302789951a86b594513c2a013532ed45d197413b1087Chris Lattner         E = OMD->param_end(); PI != E; ++PI) {
302889951a86b594513c2a013532ed45d197413b1087Chris Lattner      QualType t = (*PI)->getType()->isObjCQualifiedIdType()
30291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                     ? Context->getObjCIdType()
303089951a86b594513c2a013532ed45d197413b1087Chris Lattner                     : (*PI)->getType();
3031a206b0614a392cfef19aaaa894f9d3c756006421Steve Naroff      // Make sure we convert "t (^)(...)" to "t (*)(...)".
30324fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      (void)convertBlockPointerToFunctionPointer(t);
3033352336bb0a480b044eb03e7359e73d3b173d9cddSteve Naroff      ArgTypes.push_back(t);
3034352336bb0a480b044eb03e7359e73d3b173d9cddSteve Naroff    }
303589951a86b594513c2a013532ed45d197413b1087Chris Lattner    returnType = OMD->getResultType()->isObjCQualifiedIdType()
303689951a86b594513c2a013532ed45d197413b1087Chris Lattner                   ? Context->getObjCIdType() : OMD->getResultType();
30374fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian    (void)convertBlockPointerToFunctionPointer(returnType);
3038ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  } else {
3039a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    returnType = Context->getObjCIdType();
3040ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  }
3041ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Get the type, we will need to reference it in a couple spots.
3042874e232a0d5e179197de860e6dfa3e99cd42ad30Steve Naroff  QualType msgSendType = MsgSendFlavor->getType();
30431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3044ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Create a reference to the objc_msgSend() declaration.
30451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
3046f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                               VK_LValue, SourceLocation());
3047ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff
30481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3049ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // If we don't do this cast, we get the following bizarre warning/note:
3050ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // xx.m:13: warning: function called through a non-compatible type
3051ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // xx.m:13: note: if this code is reached, the program will abort
30529d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  cast = NoTypeInfoCStyleCastExpr(Context,
30539d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                  Context->getPointerType(Context->VoidTy),
3054a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                  CK_BitCast, DRE);
30551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3056ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Now do the "normal" pointer to function cast.
3057e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType castType =
3058e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3059e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      // If we don't have a method decl, force a variadic cast.
3060e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3061ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  castType = Context->getPointerType(castType);
3062a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
30639d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                  cast);
3064ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff
3065ab972d3c4b49fb0b99ae2beee70c1771a05342baSteve Naroff  // Don't forget the parens to enforce the proper binding.
30661d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
30671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3068183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall  const FunctionType *FT = msgSendType->getAs<FunctionType>();
3069668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek  CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
30701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                        MsgExprs.size(),
3071f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        FT->getResultType(), VK_RValue,
3072f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        EndLoc);
307333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  Stmt *ReplacingStmt = CE;
307480a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  if (MsgSendStretFlavor) {
307580a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // We have the method which returns a struct/union. Must also generate
307680a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // call to objc_msgSend_stret and hang both varieties on a conditional
307780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // expression which dictate which one to envoke depending on size of
307880a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // method's return type.
30791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
308080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // Create a reference to the objc_msgSend_stret() declaration.
30811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3082f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                   VK_LValue, SourceLocation());
308380a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // Need to cast objc_msgSend_stret to "void *" (see above comment).
30849d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall    cast = NoTypeInfoCStyleCastExpr(Context,
30859d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                    Context->getPointerType(Context->VoidTy),
3086a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                    CK_BitCast, STDRE);
308780a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // Now do the "normal" pointer to function cast.
3088e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3089e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall      Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
309080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    castType = Context->getPointerType(castType);
3091a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall    cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
30929d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                    cast);
30931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
309480a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // Don't forget the parens to enforce the proper binding.
30958189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek    PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
30961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3097183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall    FT = msgSendType->getAs<FunctionType>();
3098668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek    CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
30991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                            MsgExprs.size(),
3100f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            FT->getResultType(), VK_RValue,
3101f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            SourceLocation());
31021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
310380a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // Build sizeof(returnType)
31041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
3105a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall                            Context->getTrivialTypeSourceInfo(returnType),
31060518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl                                      Context->getSizeType(),
31070518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl                                      SourceLocation(), SourceLocation());
310880a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
310980a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
311080a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // For X86 it is more complicated and some kind of target specific routine
311180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // is needed to decide what to do.
31121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    unsigned IntSize =
311398be4943e8dc4f3905629a7102668960873cf863Chris Lattner      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
31149996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis    IntegerLiteral *limit = IntegerLiteral::Create(*Context,
31159996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis                                                   llvm::APInt(IntSize, 8),
31169996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis                                                   Context->IntTy,
31179996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis                                                   SourceLocation());
3118f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall    BinaryOperator *lessThanExpr =
3119f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall      new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3120f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                   VK_RValue, OK_Ordinary, SourceLocation());
312180a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
31221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    ConditionalOperator *CondExpr =
312347e1f7c68bf375cac470fdb2b599ddbb395aeb52Douglas Gregor      new (Context) ConditionalOperator(lessThanExpr,
312447e1f7c68bf375cac470fdb2b599ddbb395aeb52Douglas Gregor                                        SourceLocation(), CE,
312556ca35d396d8692c384c785f9aeebcf22563fe1eJohn McCall                                        SourceLocation(), STCE,
31260943168ac126b8047f30f6bd215fbe7db14d61baJohn McCall                                        returnType, VK_RValue, OK_Ordinary);
3127f9b949fecf339a2c9bd97dd11a272c4878f85ce4Fariborz Jahanian    ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3128f9b949fecf339a2c9bd97dd11a272c4878f85ce4Fariborz Jahanian                                            CondExpr);
312980a6a5abbbf0b7c45f535d4e0b0d00f4c3f320eaFariborz Jahanian  }
3130f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
313133b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  return ReplacingStmt;
313233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian}
313333b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian
3134b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
31351d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian  Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
31361d35b168348a308696d1fce29a18c14143f61d6aFariborz Jahanian                                         Exp->getLocEnd());
31371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3138934f276cc5b45e19cd12ebb2d04fd7972a23865cSteve Naroff  // Now do the actual rewrite.
3139dcbc5b0b0722282a0fdd829359fe0d7e22adb882Chris Lattner  ReplaceStmt(Exp, ReplacingStmt);
31401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3141f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
314233b9c4e4c6f1b055d94c8b57cd16883125701ac7Fariborz Jahanian  return ReplacingStmt;
3143ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff}
3144ebf2b56bce1ea6b1b8133c1f0e2131503d229d2dSteve Naroff
3145621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff// typedef struct objc_object Protocol;
3146621edce9cd7d4e06979daf911cc306350619f33bSteve NaroffQualType RewriteObjC::getProtocolType() {
3147621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (!ProtocolTypeDecl) {
3148a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall    TypeSourceInfo *TInfo
3149a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3150621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
31511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                           SourceLocation(),
3152621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff                                           &Context->Idents.get("Protocol"),
3153a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall                                           TInfo);
3154621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
3155621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  return Context->getTypeDeclType(ProtocolTypeDecl);
3156621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff}
3157621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
315836ee2cb3247a662b6049f9cc097ba5cf9c0bb2b5Fariborz Jahanian/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3159621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff/// a synthesized/forward data reference (to the protocol's metadata).
3160621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff/// The forward references (and metadata) are generated in
3161621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff/// RewriteObjC::HandleTranslationUnit().
3162b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve NaroffStmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3163621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3164621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  IdentifierInfo *ID = &Context->Idents.get(Name);
31651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
316616573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                ID, getProtocolType(), 0,
3167d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                SC_Extern, SC_None);
3168f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3169f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                               SourceLocation());
31702de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall  Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3171621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff                             Context->getPointerType(DRE->getType()),
3172f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                             VK_RValue, OK_Ordinary, SourceLocation());
31739d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3174a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                CK_BitCast,
31759d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                                DerefExpr);
3176621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  ReplaceStmt(Exp, castExpr);
3177621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  ProtocolExprDecls.insert(Exp->getProtocol());
3178f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3179621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  return castExpr;
31801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
318136ee2cb3247a662b6049f9cc097ba5cf9c0bb2b5Fariborz Jahanian}
318236ee2cb3247a662b6049f9cc097ba5cf9c0bb2b5Fariborz Jahanian
31831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpbool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3184baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff                                             const char *endBuf) {
3185baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff  while (startBuf < endBuf) {
3186baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    if (*startBuf == '#') {
3187baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      // Skip whitespace.
3188baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3189baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff        ;
3190baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      if (!strncmp(startBuf, "if", strlen("if")) ||
3191baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3192baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3193baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "define", strlen("define")) ||
3194baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "undef", strlen("undef")) ||
3195baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "else", strlen("else")) ||
3196baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "elif", strlen("elif")) ||
3197baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "endif", strlen("endif")) ||
3198baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "pragma", strlen("pragma")) ||
3199baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "include", strlen("include")) ||
3200baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "import", strlen("import")) ||
3201baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff          !strncmp(startBuf, "include_next", strlen("include_next")))
3202baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff        return true;
3203baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    }
3204baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    startBuf++;
3205baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff  }
3206baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff  return false;
3207baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff}
3208baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff
3209a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
321026e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian/// an objective-c class with ivars.
3211b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
321226e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian                                               std::string &Result) {
3213a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
32144087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  assert(CDecl->getName() != "" &&
32152e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor         "Name missing in SynthesizeObjCInternalStruct");
3216212b768a4b39479bc8cce1268a95a1adbd825542Fariborz Jahanian  // Do not synthesize more than once.
3217a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  if (ObjCSynthesizedStructs.count(CDecl))
3218212b768a4b39479bc8cce1268a95a1adbd825542Fariborz Jahanian    return;
3219a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3220f3a7af901231535191d14cb524d58f22907ac4d2Chris Lattner  int NumIvars = CDecl->ivar_size();
32212c7038b298c61e531ee4e79b9ff014ffb97b6cccFariborz Jahanian  SourceLocation LocStart = CDecl->getLocStart();
32222c7038b298c61e531ee4e79b9ff014ffb97b6cccFariborz Jahanian  SourceLocation LocEnd = CDecl->getLocEnd();
32231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
32242c7038b298c61e531ee4e79b9ff014ffb97b6cccFariborz Jahanian  const char *startBuf = SM->getCharacterData(LocStart);
32252c7038b298c61e531ee4e79b9ff014ffb97b6cccFariborz Jahanian  const char *endBuf = SM->getCharacterData(LocEnd);
32261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3227aff56d0bffdad7ed75db938d5e61e1ce3d5cd195Fariborz Jahanian  // If no ivars and no root or if its root, directly or indirectly,
3228f1de0ca05e2df6f23bd559028693a12d1ebdaaf6Fariborz Jahanian  // have no ivars (thus not synthesized) then no need to synthesize this class.
3229f3a7af901231535191d14cb524d58f22907ac4d2Chris Lattner  if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3230f3a7af901231535191d14cb524d58f22907ac4d2Chris Lattner      (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
32312c78b873f4f3823ae859c15674cb3d76c8554113Chris Lattner    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3232d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocStart, endBuf-startBuf, Result);
323326e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian    return;
32342c7038b298c61e531ee4e79b9ff014ffb97b6cccFariborz Jahanian  }
32351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
32361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // FIXME: This has potential of causing problem. If
3237a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  // SynthesizeObjCInternalStruct is ever called recursively.
3238fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff  Result += "\nstruct ";
3239d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += CDecl->getNameAsString();
324061ed9caca5dd6a9b9ccee7fb51296234e6cc68adSteve Naroff  if (LangOpts.Microsoft)
324161ed9caca5dd6a9b9ccee7fb51296234e6cc68adSteve Naroff    Result += "_IMPL";
324205b8c782669d07a71d4889bcacfd53a29cd16fcbSteve Naroff
3243fdc08a06822f7c56cef56e1a813f92565ea8f961Fariborz Jahanian  if (NumIvars > 0) {
3244fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    const char *cursor = strchr(startBuf, '{');
32451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    assert((cursor && endBuf)
3246a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek           && "SynthesizeObjCInternalStruct - malformed @interface");
3247baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // If the buffer contains preprocessor directives, we do more fine-grained
3248baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // rewrites. This is intended to fix code that looks like (which occurs in
3249baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // NSURL.h, for example):
3250baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    //
3251baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // #ifdef XYZ
3252baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // @interface Foo : NSObject
3253baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // #else
3254baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // @interface FooBar : NSObject
3255baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // #endif
3256baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // {
3257baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    //    int i;
3258baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // }
3259baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // @end
3260baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    //
3261baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    // This clause is segregated to avoid breaking the common case.
3262baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    if (BufferContainsPPDirectives(startBuf, cursor)) {
32631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3264baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff                                  CDecl->getClassLoc();
3265baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      const char *endHeader = SM->getCharacterData(L);
32662c78b873f4f3823ae859c15674cb3d76c8554113Chris Lattner      endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3267baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff
3268cafeb35117578585dbbfef0bc79d8aa27712bc0eChris Lattner      if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3269baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff        // advance to the end of the referenced protocols.
3270baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff        while (endHeader < cursor && *endHeader != '>') endHeader++;
3271baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff        endHeader++;
3272baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      }
3273baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      // rewrite the original header
3274d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(LocStart, endHeader-startBuf, Result);
3275baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    } else {
3276baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff      // rewrite the original header *without* disturbing the '{'
3277d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(LocStart, cursor-startBuf, Result);
3278baf58c3f1fb13eec46fe339287662f180bb566daSteve Naroff    }
3279a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3280fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff      Result = "\n    struct ";
3281d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      Result += RCDecl->getNameAsString();
328239bbd9f5918950436821585afc6244b1fe2c7295Steve Naroff      Result += "_IMPL ";
3283d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      Result += RCDecl->getNameAsString();
3284819173c41e395744480e8f325dc5c02438420604Steve Naroff      Result += "_IVARS;\n";
32851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3286fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff      // insert the super class structure definition.
3287f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner      SourceLocation OnePastCurly =
3288f3dd57e5378bcf5fc9f05832e92479a535d9cd8aChris Lattner        LocStart.getFileLocWithOffset(cursor-startBuf+1);
3289d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(OnePastCurly, Result);
3290fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    }
3291fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    cursor++; // past '{'
32921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3293fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    // Now comment out any visibility specifiers.
3294fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    while (cursor < endBuf) {
3295fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff      if (*cursor == '@') {
3296fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff        SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3297df6a51b0202d10963ed005c2480e3b4a10d16928Chris Lattner        // Skip whitespace.
3298df6a51b0202d10963ed005c2480e3b4a10d16928Chris Lattner        for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3299df6a51b0202d10963ed005c2480e3b4a10d16928Chris Lattner          /*scan*/;
3300df6a51b0202d10963ed005c2480e3b4a10d16928Chris Lattner
3301fdc08a06822f7c56cef56e1a813f92565ea8f961Fariborz Jahanian        // FIXME: presence of @public, etc. inside comment results in
3302fdc08a06822f7c56cef56e1a813f92565ea8f961Fariborz Jahanian        // this transformation as well, which is still correct c-code.
3303fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff        if (!strncmp(cursor, "public", strlen("public")) ||
3304fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff            !strncmp(cursor, "private", strlen("private")) ||
3305c5e327712499caa2a9f3b6591490de8cb7df0b5bSteve Naroff            !strncmp(cursor, "package", strlen("package")) ||
33069567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian            !strncmp(cursor, "protected", strlen("protected")))
3307d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer          InsertText(atLoc, "// ");
3308fdc08a06822f7c56cef56e1a813f92565ea8f961Fariborz Jahanian      }
33099567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian      // FIXME: If there are cases where '<' is used in ivar declaration part
33109567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian      // of user code, then scan the ivar list and use needToScanForQualifiers
33119567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian      // for type checking.
33129567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian      else if (*cursor == '<') {
33139567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian        SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3314d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        InsertText(atLoc, "/* ");
33159567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian        cursor = strchr(cursor, '>');
33169567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian        cursor++;
33179567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian        atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3318d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        InsertText(atLoc, " */");
3319ced80a848de94ef44b6e7b4ce6f182249b3141a8Steve Naroff      } else if (*cursor == '^') { // rewrite block specifier.
3320ced80a848de94ef44b6e7b4ce6f182249b3141a8Steve Naroff        SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3321d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer        ReplaceText(caretLoc, 1, "*");
33229567392e164128d853f0005014114d1ffc06fa86Fariborz Jahanian      }
3323fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff      cursor++;
3324fdc08a06822f7c56cef56e1a813f92565ea8f961Fariborz Jahanian    }
3325fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    // Don't forget to add a ';'!!
3326d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(LocEnd.getFileLocWithOffset(1), ";");
3327fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff  } else { // we don't have any instance variables - insert super struct.
33282c78b873f4f3823ae859c15674cb3d76c8554113Chris Lattner    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3329fea763e8b02eb907c399883117179e898f2abbf8Steve Naroff    Result += " {\n    struct ";
3330d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += RCDecl->getNameAsString();
333139bbd9f5918950436821585afc6244b1fe2c7295Steve Naroff    Result += "_IMPL ";
3332d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += RCDecl->getNameAsString();
3333819173c41e395744480e8f325dc5c02438420604Steve Naroff    Result += "_IVARS;\n};\n";
3334d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocStart, endBuf-startBuf, Result);
333526e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian  }
333626e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian  // Mark this struct as having been generated.
3337a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  if (!ObjCSynthesizedStructs.insert(CDecl))
3338fbfe82527dadb09c95609a742744d75a2322850cSteve Naroff    assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
333926e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian}
334026e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian
3341a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
33422e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian/// class methods.
3343653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregortemplate<typename MethodIterator>
3344653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregorvoid RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3345653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor                                             MethodIterator MethodEnd,
33468e991ba2e256e56959a65a049e161aa30b3c0decFariborz Jahanian                                             bool IsInstanceMethod,
33474087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                             llvm::StringRef prefix,
33484087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                             llvm::StringRef ClassName,
3349158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner                                             std::string &Result) {
3350ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  if (MethodBegin == MethodEnd) return;
33511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3352ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  if (!objc_impl_method) {
33532e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    /* struct _objc_method {
3354e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian       SEL _cmd;
3355e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian       char *method_types;
3356e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian       void *_imp;
3357e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian       }
33582e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian     */
3359158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner    Result += "\nstruct _objc_method {\n";
3360158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner    Result += "\tSEL _cmd;\n";
3361158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner    Result += "\tchar *method_types;\n";
3362158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner    Result += "\tvoid *_imp;\n";
3363158ecb9767faf87c2a33df3baec1b160dcc0be84Chris Lattner    Result += "};\n";
33641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3365ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    objc_impl_method = true;
3366ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
33671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3368ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  // Build _objc_method_list for class's methods if needed
33691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3370946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  /* struct  {
3371946a693aea83123f4039012c3bca7bc70800018bSteve Naroff   struct _objc_method_list *next_method;
3372946a693aea83123f4039012c3bca7bc70800018bSteve Naroff   int method_count;
3373946a693aea83123f4039012c3bca7bc70800018bSteve Naroff   struct _objc_method method_list[];
3374946a693aea83123f4039012c3bca7bc70800018bSteve Naroff   }
3375946a693aea83123f4039012c3bca7bc70800018bSteve Naroff   */
3376653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
3377946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "\nstatic struct {\n";
3378946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "\tstruct _objc_method_list *next_method;\n";
3379946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "\tint method_count;\n";
3380946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "\tstruct _objc_method method_list[";
3381653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  Result += utostr(NumMethods);
3382946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "];\n} _OBJC_";
3383ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += prefix;
3384ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3385ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "_METHODS_";
3386ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += ClassName;
3387dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff  Result += " __attribute__ ((used, section (\"__OBJC, __";
3388ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += IsInstanceMethod ? "inst" : "cls";
3389ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "_meth\")))= ";
3390653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
3391ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner
3392ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "\t,{{(SEL)\"";
3393077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner  Result += (*MethodBegin)->getSelector().getAsString().c_str();
3394ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  std::string MethodTypeString;
3395a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
3396ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "\", \"";
3397ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += MethodTypeString;
3398946a693aea83123f4039012c3bca7bc70800018bSteve Naroff  Result += "\", (void *)";
3399ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += MethodInternalNames[*MethodBegin];
3400ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "}\n";
3401ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3402ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner    Result += "\t  ,{(SEL)\"";
3403077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner    Result += (*MethodBegin)->getSelector().getAsString().c_str();
340433e1d64ab5cd5d27f8530ccd056191fe2c9f3f2eFariborz Jahanian    std::string MethodTypeString;
3405a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
340633e1d64ab5cd5d27f8530ccd056191fe2c9f3f2eFariborz Jahanian    Result += "\", \"";
340733e1d64ab5cd5d27f8530ccd056191fe2c9f3f2eFariborz Jahanian    Result += MethodTypeString;
3408946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += "\", (void *)";
3409ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner    Result += MethodInternalNames[*MethodBegin];
3410b7908b5c54aeafc1ff98797e304d61c68b1aed25Fariborz Jahanian    Result += "}\n";
3411e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian  }
3412ab4c4d5e5ececa77aae7e291fafcba3049319cdcChris Lattner  Result += "\t }\n};\n";
34132e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian}
34142e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian
3415621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
3416780f329cb011bff0da5763e2e9744eec093d0509Chris Lattnervoid RewriteObjC::
34174087f27e5416c799bcb6be072f905be752acb61cDaniel DunbarRewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
34184087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                            llvm::StringRef ClassName, std::string &Result) {
3419e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian  static bool objc_protocol_methods = false;
3420621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
3421621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Output struct protocol_methods holder of method selector and type.
3422621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3423621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    /* struct protocol_methods {
3424621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     SEL _cmd;
3425621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     char *method_types;
3426621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     }
3427621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     */
3428621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\nstruct _protocol_methods {\n";
3429621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct objc_selector *_cmd;\n";
3430621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tchar *method_types;\n";
3431621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "};\n";
34321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3433621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    objc_protocol_methods = true;
3434621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
3435621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Do not synthesize the protocol more than once.
3436621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (ObjCSynthesizedProtocols.count(PDecl))
3437621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    return;
34381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
343917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
344017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
344117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis                                          PDecl->instmeth_end());
3442621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    /* struct _objc_protocol_method_list {
3443621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     int protocol_method_count;
3444621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     struct protocol_methods protocols[];
3445621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     }
3446621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     */
3447621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\nstatic struct {\n";
3448621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tint protocol_method_count;\n";
3449621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _protocol_methods protocol_methods[";
3450621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += utostr(NumMethods);
3451621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3452621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += PDecl->getNameAsString();
3453621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3454621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      "{\n\t" + utostr(NumMethods) + "\n";
34551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3456621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    // Output instance methods declared in this protocol.
34571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (ObjCProtocolDecl::instmeth_iterator
34581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump           I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
3459621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff         I != E; ++I) {
346017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (I == PDecl->instmeth_begin())
3461621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += "\t  ,{{(struct objc_selector *)\"";
3462621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      else
3463621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += "\t  ,{(struct objc_selector *)\"";
34644087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar      Result += (*I)->getSelector().getAsString();
3465621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      std::string MethodTypeString;
3466621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3467621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "\", \"";
3468621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += MethodTypeString;
3469621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "\"}\n";
34709d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner    }
3471621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\t }\n};\n";
3472621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
34731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3474621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Output class methods declared in this protocol.
347517945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
347617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis                                      PDecl->classmeth_end());
3477621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (NumMethods > 0) {
3478621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    /* struct _objc_protocol_method_list {
3479621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     int protocol_method_count;
3480621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     struct protocol_methods protocols[];
3481621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff     }
34829d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner     */
3483621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\nstatic struct {\n";
3484621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tint protocol_method_count;\n";
3485621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _protocol_methods protocol_methods[";
3486621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += utostr(NumMethods);
3487621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3488d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += PDecl->getNameAsString();
3489621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3490621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff           "{\n\t";
3491621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += utostr(NumMethods);
3492621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\n";
34931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3494621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    // Output instance methods declared in this protocol.
34951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (ObjCProtocolDecl::classmeth_iterator
349617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis           I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
3497621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff         I != E; ++I) {
349817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (I == PDecl->classmeth_begin())
3499621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += "\t  ,{{(struct objc_selector *)\"";
3500621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      else
3501621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += "\t  ,{(struct objc_selector *)\"";
35024087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar      Result += (*I)->getSelector().getAsString();
3503621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      std::string MethodTypeString;
3504621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3505621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "\", \"";
3506621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += MethodTypeString;
3507621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "\"}\n";
3508e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian    }
3509621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\t }\n};\n";
3510621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
3511621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
3512621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Output:
3513621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  /* struct _objc_protocol {
3514621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   // Objective-C 1.0 extensions
3515621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   struct _objc_protocol_extension *isa;
3516621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   char *protocol_name;
3517621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   struct _objc_protocol **protocol_list;
3518621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   struct _objc_protocol_method_list *instance_methods;
3519621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   struct _objc_protocol_method_list *class_methods;
35201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump   };
3521621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff   */
3522621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  static bool objc_protocol = false;
3523621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (!objc_protocol) {
3524621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\nstruct _objc_protocol {\n";
3525621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _objc_protocol_extension *isa;\n";
3526621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tchar *protocol_name;\n";
3527621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _objc_protocol **protocol_list;\n";
3528621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3529621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
35309d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner    Result += "};\n";
35311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3532621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    objc_protocol = true;
3533621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
35341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3535621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3536621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += PDecl->getNameAsString();
3537621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3538621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    "{\n\t0, \"";
3539621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += PDecl->getNameAsString();
3540621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += "\", 0, ";
354117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3542621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3543621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += PDecl->getNameAsString();
3544621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += ", ";
35459d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  }
3546621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  else
3547621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "0, ";
354817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
3549621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3550621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += PDecl->getNameAsString();
3551621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "\n";
3552621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  }
3553621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  else
3554621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Result += "0\n";
3555621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  Result += "};\n";
35561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3557621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Mark this protocol as having been generated.
3558621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (!ObjCSynthesizedProtocols.insert(PDecl))
3559621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    assert(false && "protocol already synthesized");
3560621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
3561621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff}
3562621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
3563621edce9cd7d4e06979daf911cc306350619f33bSteve Naroffvoid RewriteObjC::
3564621edce9cd7d4e06979daf911cc306350619f33bSteve NaroffRewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
35654087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                llvm::StringRef prefix, llvm::StringRef ClassName,
3566621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff                                std::string &Result) {
3567621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (Protocols.empty()) return;
35681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3569621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  for (unsigned i = 0; i != Protocols.size(); i++)
3570621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3571621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
35729d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  // Output the top lovel protocol meta-data for the class.
35739d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  /* struct _objc_protocol_list {
35749d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner   struct _objc_protocol_list *next;
35759d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner   int    protocol_count;
35769d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner   struct _objc_protocol *class_protocols[];
35779d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner   }
35789d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner   */
35799d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\nstatic struct {\n";
35809d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\tstruct _objc_protocol_list *next;\n";
35819d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\tint    protocol_count;\n";
35829d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\tstruct _objc_protocol *class_protocols[";
35839d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += utostr(Protocols.size());
35849d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "];\n} _OBJC_";
35859d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += prefix;
35869d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "_PROTOCOLS_";
35879d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += ClassName;
35889d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
35899d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner    "{\n\t0, ";
35909d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += utostr(Protocols.size());
35919d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\n";
35921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
35939d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\t,{&_OBJC_PROTOCOL_";
3594d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += Protocols[0]->getNameAsString();
35959d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += " \n";
35961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
35979d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  for (unsigned i = 1; i != Protocols.size(); i++) {
35989d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner    Result += "\t ,&_OBJC_PROTOCOL_";
3599d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += Protocols[i]->getNameAsString();
36009d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner    Result += "\n";
36019d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  }
36029d0aaa11cd5e657987bbb2d54b63bb0fd18c5117Chris Lattner  Result += "\t }\n};\n";
36032e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian}
36042e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian
3605621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
36061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
36072e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian/// implementation.
3608b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
3609ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian                                              std::string &Result) {
3610a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
36112e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Find category declaration for this implementation.
3612a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCCategoryDecl *CDecl;
36131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (CDecl = ClassDecl->getCategoryList(); CDecl;
36142e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian       CDecl = CDecl->getNextClassCategory())
36152e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    if (CDecl->getIdentifier() == IDecl->getIdentifier())
36162e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian      break;
36171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3618d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  std::string FullCategoryName = ClassDecl->getNameAsString();
3619eb44eeeff28810266259c125896c717d46a0e3b8Chris Lattner  FullCategoryName += '_';
3620d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  FullCategoryName += IDecl->getNameAsString();
36211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
36222e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Build _objc_method_list for class's instance methods if needed
36231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::SmallVector<ObjCMethodDecl *, 32>
362417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3625653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor
3626653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  // If any of our property implementations have associated getters or
3627653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  // setters, produce metadata for them as well.
362817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
362917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         PropEnd = IDecl->propimpl_end();
3630653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor       Prop != PropEnd; ++Prop) {
3631653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3632653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3633653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (!(*Prop)->getPropertyIvarDecl())
3634653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3635653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3636653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (!PD)
3637653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3638653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3639653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      InstanceMethods.push_back(Getter);
3640653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (PD->isReadOnly())
3641653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3642653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3643653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      InstanceMethods.push_back(Setter);
3644653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  }
3645653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
3646eb44eeeff28810266259c125896c717d46a0e3b8Chris Lattner                             true, "CATEGORY_", FullCategoryName.c_str(),
3647eb44eeeff28810266259c125896c717d46a0e3b8Chris Lattner                             Result);
36481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
36492e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Build _objc_method_list for class's class methods if needed
365017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
3651eb44eeeff28810266259c125896c717d46a0e3b8Chris Lattner                             false, "CATEGORY_", FullCategoryName.c_str(),
3652eb44eeeff28810266259c125896c717d46a0e3b8Chris Lattner                             Result);
36531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
36542e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Protocols referenced in class declaration?
3655bac97d43c9552ac0e084bb81fb7404908f1e9970Fariborz Jahanian  // Null CDecl is case of a category implementation with no category interface
3656bac97d43c9552ac0e084bb81fb7404908f1e9970Fariborz Jahanian  if (CDecl)
3657621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
36584087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                    FullCategoryName, Result);
36592e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  /* struct _objc_category {
36602e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   char *category_name;
36612e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   char *class_name;
36622e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   struct _objc_method_list *instance_methods;
36632e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   struct _objc_method_list *class_methods;
36642e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   struct _objc_protocol_list *protocols;
36652e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   // Objective-C 1.0 extensions
36662e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   uint32_t size;     // sizeof (struct _objc_category)
36671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump   struct _objc_property_list *instance_properties;  // category's own
36682e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian                                                     // @property decl.
36691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump   };
36702e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian   */
36711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
36722e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  static bool objc_category = false;
36732e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  if (!objc_category) {
3674ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\nstruct _objc_category {\n";
3675ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tchar *category_name;\n";
3676ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tchar *class_name;\n";
3677ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_method_list *instance_methods;\n";
3678ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_method_list *class_methods;\n";
3679ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_protocol_list *protocols;\n";
36801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Result += "\tunsigned int size;\n";
3681ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_property_list *instance_properties;\n";
3682ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "};\n";
36832e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    objc_category = true;
3684e887c0939572f063b07b6ac2df16140c40fcb667Fariborz Jahanian  }
3685ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3686ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += FullCategoryName;
3687dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff  Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
3688d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += IDecl->getNameAsString();
3689ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\"\n\t, \"";
3690d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += ClassDecl->getNameAsString();
3691ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\"\n";
36921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
369317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3694ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t, (struct _objc_method_list *)"
3695ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian           "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3696ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += FullCategoryName;
3697ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
3698ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
36992e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  else
3700ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t, 0\n";
370117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
3702ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t, (struct _objc_method_list *)"
3703ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian           "&_OBJC_CATEGORY_CLASS_METHODS_";
3704ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += FullCategoryName;
3705ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
3706ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
37072e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  else
3708ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t, 0\n";
37091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3710cafeb35117578585dbbfef0bc79d8aa27712bc0eChris Lattner  if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
37111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3712ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += FullCategoryName;
3713ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
3714ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
37152e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  else
3716ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t, 0\n";
3717ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\t, sizeof(struct _objc_category), 0\n};\n";
37182e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian}
37192e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian
372026e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
372126e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian/// ivar offset.
37222d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanianvoid RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
372326e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian                                                  std::string &Result) {
37248f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff  if (ivar->isBitField()) {
37258f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    // FIXME: The hack below doesn't work for bitfields. For now, we simply
37268f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    // place all bitfields at offset 0.
37278f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    Result += "0";
37288f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff  } else {
37298f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    Result += "__OFFSETOFIVAR__(struct ";
37302d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    Result += ivar->getContainingInterface()->getNameAsString();
37318f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    if (LangOpts.Microsoft)
37328f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff      Result += "_IMPL";
37338f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    Result += ", ";
3734d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += ivar->getNameAsString();
37358f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff    Result += ")";
37368f3b2654a9ff6912862f366102f5c46f7757260aSteve Naroff  }
373726e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian}
373826e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian
37392e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian//===----------------------------------------------------------------------===//
37402e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian// Meta Data Emission
37412e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian//===----------------------------------------------------------------------===//
37422e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian
3743b29b427fa977e8e13ea104d22b193b2cd8a4a52fSteve Naroffvoid RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
3744ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian                                           std::string &Result) {
3745a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
37461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3747ebe668fac7553b9932e1936a997e96dc08c9cae4Fariborz Jahanian  // Explictly declared @interface's are already synthesized.
374833feeb019a5742b286eededd5446ec0fe87c5a61Steve Naroff  if (CDecl->isImplicitInterfaceDecl()) {
37491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // FIXME: Implementation of a class with no @interface (legacy) doese not
3750ebe668fac7553b9932e1936a997e96dc08c9cae4Fariborz Jahanian    // produce correct synthesis as yet.
3751a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    SynthesizeObjCInternalStruct(CDecl, Result);
3752ebe668fac7553b9932e1936a997e96dc08c9cae4Fariborz Jahanian  }
37531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3754be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner  // Build _objc_ivar_list metadata for classes ivars if needed
375517945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  unsigned NumIvars = !IDecl->ivar_empty()
37561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                      ? IDecl->ivar_size()
3757f3a7af901231535191d14cb524d58f22907ac4d2Chris Lattner                      : (CDecl ? CDecl->ivar_size() : 0);
37582e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  if (NumIvars > 0) {
37592e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    static bool objc_ivar = false;
37602e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    if (!objc_ivar) {
37612e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian      /* struct _objc_ivar {
37622e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian          char *ivar_name;
37632e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian          char *ivar_type;
37642e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian          int ivar_offset;
37651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        };
37662e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian       */
3767ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "\nstruct _objc_ivar {\n";
3768ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "\tchar *ivar_name;\n";
3769ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "\tchar *ivar_type;\n";
3770ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "\tint ivar_offset;\n";
3771ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "};\n";
37721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
37732e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian      objc_ivar = true;
37742e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian    }
37752e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian
3776946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    /* struct {
3777946a693aea83123f4039012c3bca7bc70800018bSteve Naroff       int ivar_count;
3778946a693aea83123f4039012c3bca7bc70800018bSteve Naroff       struct _objc_ivar ivar_list[nIvars];
37791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump       };
3780946a693aea83123f4039012c3bca7bc70800018bSteve Naroff     */
37811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Result += "\nstatic struct {\n";
3782946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += "\tint ivar_count;\n";
3783946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += "\tstruct _objc_ivar ivar_list[";
3784946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += utostr(NumIvars);
3785946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
3786d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += IDecl->getNameAsString();
3787dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff    Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
3788ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      "{\n\t";
3789ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += utostr(NumIvars);
3790ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
37911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3792a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    ObjCInterfaceDecl::ivar_iterator IVI, IVE;
37938f36aba016c2d236a90f9ecf0a66904209202202Douglas Gregor    llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
379417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    if (!IDecl->ivar_empty()) {
379511062e11236b7bc689dad150e8b490fd6b063ec3Fariborz Jahanian      for (ObjCInterfaceDecl::ivar_iterator
379617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis             IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
37978f36aba016c2d236a90f9ecf0a66904209202202Douglas Gregor           IV != IVEnd; ++IV)
37988f36aba016c2d236a90f9ecf0a66904209202202Douglas Gregor        IVars.push_back(*IV);
379911062e11236b7bc689dad150e8b490fd6b063ec3Fariborz Jahanian      IVI = IDecl->ivar_begin();
380011062e11236b7bc689dad150e8b490fd6b063ec3Fariborz Jahanian      IVE = IDecl->ivar_end();
3801be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner    } else {
3802be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner      IVI = CDecl->ivar_begin();
3803be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner      IVE = CDecl->ivar_end();
3804be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner    }
3805ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t,{{\"";
3806d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += (*IVI)->getNameAsString();
3807160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian    Result += "\", \"";
3808621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    std::string TmpString, StrEncoding;
3809621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3810621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    QuoteDoublequotes(TmpString, StrEncoding);
3811160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian    Result += StrEncoding;
3812160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian    Result += "\", ";
38132d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian    SynthesizeIvarOffsetComputation(*IVI, Result);
381426e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian    Result += "}\n";
3815be6df088d69bca0e99c7845a6cd8c1ca85034f31Chris Lattner    for (++IVI; IVI != IVE; ++IVI) {
3816ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian      Result += "\t  ,{\"";
3817d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      Result += (*IVI)->getNameAsString();
3818160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian      Result += "\", \"";
3819621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      std::string TmpString, StrEncoding;
3820621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3821621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      QuoteDoublequotes(TmpString, StrEncoding);
3822160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian      Result += StrEncoding;
3823160eb6538eee38b6827a6173c4f7cc0630b29ed5Fariborz Jahanian      Result += "\", ";
38242d8c1fdef9658d7c3d56bcfd5533188f6c8b6bf5Fariborz Jahanian      SynthesizeIvarOffsetComputation((*IVI), Result);
382526e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian      Result += "}\n";
3826ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    }
38271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3828ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t }\n};\n";
38292e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  }
38301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
38312e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Build _objc_method_list for class's instance methods if needed
38321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::SmallVector<ObjCMethodDecl *, 32>
383317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3834653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor
3835653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  // If any of our property implementations have associated getters or
3836653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  // setters, produce metadata for them as well.
383717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
383817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         PropEnd = IDecl->propimpl_end();
3839653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor       Prop != PropEnd; ++Prop) {
3840653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3841653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3842653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (!(*Prop)->getPropertyIvarDecl())
3843653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3844653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3845653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (!PD)
3846653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3847653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3848ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      if (!Getter->isDefined())
3849ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        InstanceMethods.push_back(Getter);
3850653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (PD->isReadOnly())
3851653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      continue;
3852653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor    if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3853ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian      if (!Setter->isDefined())
3854ec3683b3f33beda2449b4896b1a9548ab283e0e7Fariborz Jahanian        InstanceMethods.push_back(Setter);
3855653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  }
3856653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
38574087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                             true, "", IDecl->getName(), Result);
38581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
38592e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Build _objc_method_list for class's class methods if needed
386017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
38614087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                             false, "", IDecl->getName(), Result);
38621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
38632e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // Protocols referenced in class declaration?
3864621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
38654087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                  "CLASS", CDecl->getName(), Result);
38661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3867deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  // Declaration of class/meta-class metadata
3868deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  /* struct _objc_class {
3869deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian   struct _objc_class *isa; // or const char *root_class_name when metadata
38709f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   const char *super_class_name;
38719f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   char *name;
38729f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   long version;
38739f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   long info;
38749f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   long instance_size;
3875deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian   struct _objc_ivar_list *ivars;
3876deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian   struct _objc_method_list *methods;
38779f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   struct objc_cache *cache;
38789f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   struct objc_protocol_list *protocols;
38799f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   const char *ivar_layout;
38809f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian   struct _objc_class_ext  *ext;
38811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump   };
38829f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  */
3883deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  static bool objc_class = false;
3884deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  if (!objc_class) {
3885ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\nstruct _objc_class {\n";
3886ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_class *isa;\n";
3887ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tconst char *super_class_name;\n";
3888ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tchar *name;\n";
3889ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tlong version;\n";
3890ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tlong info;\n";
3891ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tlong instance_size;\n";
3892ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_ivar_list *ivars;\n";
3893ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_method_list *methods;\n";
3894ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct objc_cache *cache;\n";
3895ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_protocol_list *protocols;\n";
3896ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tconst char *ivar_layout;\n";
3897ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\tstruct _objc_class_ext  *ext;\n";
3898ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "};\n";
3899deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian    objc_class = true;
39009f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  }
39011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
39029f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  // Meta-class metadata generation.
3903a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCInterfaceDecl *RootClass = 0;
3904a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
39059f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  while (SuperClass) {
39069f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian    RootClass = SuperClass;
39079f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian    SuperClass = SuperClass->getSuperClass();
39089f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  }
39099f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  SuperClass = CDecl->getSuperClass();
39101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3911ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3912d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += CDecl->getNameAsString();
3913dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff  Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
3914ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  "{\n\t(struct _objc_class *)\"";
3915d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
3916ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\"";
3917ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian
3918ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  if (SuperClass) {
3919ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", \"";
3920d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += SuperClass->getNameAsString();
3921ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\", \"";
3922d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3923ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\"";
3924ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3925ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  else {
3926ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", 0, \"";
3927d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3928ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\"";
3929ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3930a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
39319f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  // 'info' field is initialized to CLS_META(2) for metaclass
3932ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += ", 0,2, sizeof(struct _objc_class), 0";
393317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
393423f4127411d926fc6a1fe9af7c2bf97e653f16ebSteve Naroff    Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
3935d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += IDecl->getNameAsString();
39361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Result += "\n";
3937ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
39389f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian  else
3939ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", 0\n";
3940cafeb35117578585dbbfef0bc79d8aa27712bc0eChris Lattner  if (CDecl->protocol_begin() != CDecl->protocol_end()) {
39418eb4a5e70a1bc3d832f90a150fdd84096532c2e2Steve Naroff    Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
3942d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3943ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ",0,0\n";
3944ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3945454cb012a948ab3dfef5e80ee32b470689c42ba5Fariborz Jahanian  else
3946ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t,0,0,0,0\n";
3947ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n";
39481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3949deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  // class metadata generation.
3950ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3951d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += CDecl->getNameAsString();
3952dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff  Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
3953ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian            "{\n\t&_OBJC_METACLASS_";
3954d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner  Result += CDecl->getNameAsString();
3955ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  if (SuperClass) {
3956ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", \"";
3957d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += SuperClass->getNameAsString();
3958ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\", \"";
3959d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3960ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\"";
3961ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3962ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  else {
3963ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", 0, \"";
3964d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3965ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\"";
3966ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3967deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  // 'info' field is initialized to CLS_CLASS(1) for class
39684d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian  Result += ", 0,1";
3969a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek  if (!ObjCSynthesizedStructs.count(CDecl))
39704d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian    Result += ",0";
39714d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian  else {
39724d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian    // class has size. Must synthesize its size.
3973909f02a69786e94d34d34fc8d4ea3e160bcff775Fariborz Jahanian    Result += ",sizeof(struct ";
3974d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3975ba9ac4e5b86842216a0a0eef5886d41e0d7fed0eSteve Naroff    if (LangOpts.Microsoft)
3976ba9ac4e5b86842216a0a0eef5886d41e0d7fed0eSteve Naroff      Result += "_IMPL";
39774d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian    Result += ")";
39784d733d3288112667cfa3993424987b9ad9427f8fFariborz Jahanian  }
3979ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  if (NumIvars > 0) {
3980c0a123c81b4c88eb713ad2f82e3d7ad0e9ef7c68Steve Naroff    Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
3981d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3982ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n\t";
3983ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3984deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  else
3985ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ",0";
398617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3987946a693aea83123f4039012c3bca7bc70800018bSteve Naroff    Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
3988d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
39891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Result += ", 0\n\t";
3990ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3991deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  else
3992ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ",0,0";
3993cafeb35117578585dbbfef0bc79d8aa27712bc0eChris Lattner  if (CDecl->protocol_begin() != CDecl->protocol_end()) {
39948eb4a5e70a1bc3d832f90a150fdd84096532c2e2Steve Naroff    Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
3995d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CDecl->getNameAsString();
3996ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ", 0,0\n";
3997ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
3998deef51838bcf0a1a94832a083fb69ddecd008e8cFariborz Jahanian  else
3999ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += ",0,0,0\n";
4000ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n";
40019f0a1cb8cf741d8ccd86beb15b50867b0758750fFariborz Jahanian}
4002f4d331dd922f92478ebf30e808c0ca97ce49418bFariborz Jahanian
40037a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian/// RewriteImplementations - This routine rewrites all method implementations
40047a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian/// and emits meta-data.
40057a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian
4006ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroffvoid RewriteObjC::RewriteImplementations() {
4007545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  int ClsDefCount = ClassImplementation.size();
4008545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  int CatDefCount = CategoryImplementation.size();
40091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
40107a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian  // Rewrite implemented methods
40117a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian  for (int i = 0; i < ClsDefCount; i++)
40127a3279ddb8b0cdb7444410bc91e2c7419efaedd8Fariborz Jahanian    RewriteImplementationDecl(ClassImplementation[i]);
40131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
401466d6b294af6f114c718039e3279cfd23040cad7bFariborz Jahanian  for (int i = 0; i < CatDefCount; i++)
401566d6b294af6f114c718039e3279cfd23040cad7bFariborz Jahanian    RewriteImplementationDecl(CategoryImplementation[i]);
4016ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff}
40171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4018ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroffvoid RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4019ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff  int ClsDefCount = ClassImplementation.size();
4020ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff  int CatDefCount = CategoryImplementation.size();
40217c63fddad600e710042fa018768807bd04eaa233Fariborz Jahanian
40222e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // For each implemented class, write out all its meta data.
4023f4d331dd922f92478ebf30e808c0ca97ce49418bFariborz Jahanian  for (int i = 0; i < ClsDefCount; i++)
4024a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    RewriteObjCClassMetaData(ClassImplementation[i], Result);
40251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
40262e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  // For each implemented category, write out all its meta data.
40272e6d935930867d93d84d234ada30d93a0371754dFariborz Jahanian  for (int i = 0; i < CatDefCount; i++)
4028a526c5c67e5a0473c340903ee542ce570119665fTed Kremenek    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
4029621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
4030545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  // Write objc_symtab metadata
4031545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  /*
4032545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   struct _objc_symtab
4033545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   {
4034545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   long sel_ref_cnt;
4035545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   SEL *refs;
4036545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   short cls_def_cnt;
4037545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   short cat_def_cnt;
4038545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   void *defs[cls_def_cnt + cat_def_cnt];
40391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump   };
4040545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   */
40411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4042ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\nstruct _objc_symtab {\n";
4043ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tlong sel_ref_cnt;\n";
4044ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tSEL *refs;\n";
4045ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tshort cls_def_cnt;\n";
4046ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tshort cat_def_cnt;\n";
4047ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4048ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n\n";
40491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4050ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "static struct _objc_symtab "
4051dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff         "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
40521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Result += "\t0, 0, " + utostr(ClsDefCount)
4053ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian            + ", " + utostr(CatDefCount) + "\n";
4054ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  for (int i = 0; i < ClsDefCount; i++) {
4055ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t,&_OBJC_CLASS_";
4056d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += ClassImplementation[i]->getNameAsString();
4057ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
4058ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
40591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4060ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  for (int i = 0; i < CatDefCount; i++) {
4061ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\t,&_OBJC_CATEGORY_";
4062d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
4063ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "_";
4064d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    Result += CategoryImplementation[i]->getNameAsString();
4065ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian    Result += "\n";
4066ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  }
40671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4068ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n\n";
40691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4070545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  // Write objc_module metadata
40711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4072545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  /*
4073545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   struct _objc_module {
4074545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian    long version;
4075545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian    long size;
4076545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian    const char *name;
4077545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian    struct _objc_symtab *symtab;
4078545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian   }
4079545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian  */
40801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4081ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\nstruct _objc_module {\n";
4082ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tlong version;\n";
4083ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tlong size;\n";
4084ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tconst char *name;\n";
4085ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "\tstruct _objc_symtab *symtab;\n";
4086ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n\n";
4087ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "static struct _objc_module "
4088dbb6543dd11e818df8a3228c6ffcc1976f096b15Steve Naroff    "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
40891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Result += "\t" + utostr(OBJC_ABI_VERSION) +
409026e4cd331c389a9b7d51c91981a7a10c8a909bf4Fariborz Jahanian  ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
4091ccd87b07a714b6e2735a80e89e425ce7fdf6a8d8Fariborz Jahanian  Result += "};\n\n";
40924f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff
40934f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff  if (LangOpts.Microsoft) {
4094621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    if (ProtocolExprDecls.size()) {
4095621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4096621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
40971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4098621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff           E = ProtocolExprDecls.end(); I != E; ++I) {
4099621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4100621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += (*I)->getNameAsString();
4101621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += " = &_OBJC_PROTOCOL_";
4102621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += (*I)->getNameAsString();
4103621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff        Result += ";\n";
4104621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      }
4105621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Result += "#pragma data_seg(pop)\n\n";
4106621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    }
41074f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff    Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
41081919032c9b6e9969e42093ee2e75a4de6abcb2b0Steve Naroff    Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
41094f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff    Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
41104f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff    Result += "&_OBJC_MODULES;\n";
41114f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff    Result += "#pragma data_seg(pop)\n\n";
41124f943c23a47d042c3275e78f2d6015daa650f105Steve Naroff  }
4113545b9ae381158761d387d2b5b071f28b1f489ed6Fariborz Jahanian}
4114311ff02fae0392bee6abe7723cdf5a69b2899a47Chris Lattner
4115a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanianvoid RewriteObjC::RewriteByRefString(std::string &ResultStr,
4116a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian                                     const std::string &Name,
41171e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian                                     ValueDecl *VD, bool def) {
4118a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  assert(BlockByRefDeclNo.count(VD) &&
4119a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian         "RewriteByRefString: ByRef decl missing");
41201e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian  if (def)
41211e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian    ResultStr += "struct ";
41221e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian  ResultStr += "__Block_byref_" + Name +
4123a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    "_" + utostr(BlockByRefDeclNo[VD]) ;
4124a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian}
4125a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian
41266cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanianstatic bool HasLocalVariableExternalStorage(ValueDecl *VD) {
41276cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
41286cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
41296cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  return false;
41306cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian}
41316cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian
413254055232a5ddb9529726e934301b125cb720a273Steve Naroffstd::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
41334087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                                   llvm::StringRef funcName,
413454055232a5ddb9529726e934301b125cb720a273Steve Naroff                                                   std::string Tag) {
413554055232a5ddb9529726e934301b125cb720a273Steve Naroff  const FunctionType *AFT = CE->getFunctionType();
413654055232a5ddb9529726e934301b125cb720a273Steve Naroff  QualType RT = AFT->getResultType();
413754055232a5ddb9529726e934301b125cb720a273Steve Naroff  std::string StructRef = "struct " + Tag;
4138fa297fb29b38991c537a0ae90ff595102dcd21a9Daniel Dunbar  std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
41394087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                  funcName.str() + "_" + "block_func_" + utostr(i);
414054055232a5ddb9529726e934301b125cb720a273Steve Naroff
414154055232a5ddb9529726e934301b125cb720a273Steve Naroff  BlockDecl *BD = CE->getBlockDecl();
41421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
414372564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor  if (isa<FunctionNoProtoType>(AFT)) {
41441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // No user-supplied arguments. Still need to pass in a pointer to the
4145df8570d1ff98155b74df2a0544068f40b4fd5195Steve Naroff    // block (to reference imported block decl refs).
4146df8570d1ff98155b74df2a0544068f40b4fd5195Steve Naroff    S += "(" + StructRef + " *__cself)";
414754055232a5ddb9529726e934301b125cb720a273Steve Naroff  } else if (BD->param_empty()) {
414854055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += "(" + StructRef + " *__cself)";
414954055232a5ddb9529726e934301b125cb720a273Steve Naroff  } else {
415072564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
415154055232a5ddb9529726e934301b125cb720a273Steve Naroff    assert(FT && "SynthesizeBlockFunc: No function proto");
415254055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += '(';
415354055232a5ddb9529726e934301b125cb720a273Steve Naroff    // first add the implicit argument.
415454055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += StructRef + " *__cself, ";
415554055232a5ddb9529726e934301b125cb720a273Steve Naroff    std::string ParamStr;
415654055232a5ddb9529726e934301b125cb720a273Steve Naroff    for (BlockDecl::param_iterator AI = BD->param_begin(),
415754055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = BD->param_end(); AI != E; ++AI) {
415854055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (AI != BD->param_begin()) S += ", ";
4159d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      ParamStr = (*AI)->getNameAsString();
41601f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      QualType QT = (*AI)->getType();
41614fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      if (convertBlockPointerToFunctionPointer(QT))
41624fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian        QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
41631f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      else
41641f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian        QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
416554055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += ParamStr;
416654055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
416754055232a5ddb9529726e934301b125cb720a273Steve Naroff    if (FT->isVariadic()) {
416854055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (!BD->param_empty()) S += ", ";
416954055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += "...";
417054055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
417154055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += ')';
417254055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
417354055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += " {\n";
41741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
417554055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Create local declarations to avoid rewriting all closure decl ref exprs.
417654055232a5ddb9529726e934301b125cb720a273Steve Naroff  // First, emit a declaration for all "by ref" decls.
4177bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian  for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
417854055232a5ddb9529726e934301b125cb720a273Steve Naroff       E = BlockByRefDecls.end(); I != E; ++I) {
417954055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += "  ";
4180d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    std::string Name = (*I)->getNameAsString();
4181a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    std::string TypeString;
4182a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    RewriteByRefString(TypeString, Name, (*I));
4183a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    TypeString += " *";
418452b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian    Name = TypeString + Name;
4185d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
41861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
418754055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Next, emit a declaration for all "by copy" declarations.
4188bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian  for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
418954055232a5ddb9529726e934301b125cb720a273Steve Naroff       E = BlockByCopyDecls.end(); I != E; ++I) {
419054055232a5ddb9529726e934301b125cb720a273Steve Naroff    S += "  ";
419154055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Handle nested closure invocation. For example:
419254055232a5ddb9529726e934301b125cb720a273Steve Naroff    //
419354055232a5ddb9529726e934301b125cb720a273Steve Naroff    //   void (^myImportedClosure)(void);
419454055232a5ddb9529726e934301b125cb720a273Steve Naroff    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
41951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    //
419654055232a5ddb9529726e934301b125cb720a273Steve Naroff    //   void (^anotherClosure)(void);
419754055232a5ddb9529726e934301b125cb720a273Steve Naroff    //   anotherClosure = ^(void) {
419854055232a5ddb9529726e934301b125cb720a273Steve Naroff    //     myImportedClosure(); // import and invoke the closure
419954055232a5ddb9529726e934301b125cb720a273Steve Naroff    //   };
420054055232a5ddb9529726e934301b125cb720a273Steve Naroff    //
4201e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    if (isTopLevelBlockPointerType((*I)->getType())) {
4202e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      RewriteBlockPointerTypeVariable(S, (*I));
4203e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      S += " = (";
4204e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      RewriteBlockPointerType(S, (*I)->getType());
4205e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      S += ")";
4206e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4207e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    }
4208e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    else {
4209210c248449788d9ef910c8222267029653f83a2fFariborz Jahanian      std::string Name = (*I)->getNameAsString();
42106cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      QualType QT = (*I)->getType();
42116cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      if (HasLocalVariableExternalStorage(*I))
42126cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        QT = Context->getPointerType(QT);
42136cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      QT.getAsStringInternal(Name, Context->PrintingPolicy);
4214e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian      S += Name + " = __cself->" +
4215e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian                              (*I)->getNameAsString() + "; // bound by copy\n";
4216e8c28dffce846b1783fd11cc130b4be4f9894301Fariborz Jahanian    }
421754055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
421854055232a5ddb9529726e934301b125cb720a273Steve Naroff  std::string RewrittenStr = RewrittenBlockExprs[CE];
421954055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *cstr = RewrittenStr.c_str();
422054055232a5ddb9529726e934301b125cb720a273Steve Naroff  while (*cstr++ != '{') ;
422154055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += cstr;
422254055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "\n";
422354055232a5ddb9529726e934301b125cb720a273Steve Naroff  return S;
422454055232a5ddb9529726e934301b125cb720a273Steve Naroff}
422554055232a5ddb9529726e934301b125cb720a273Steve Naroff
422654055232a5ddb9529726e934301b125cb720a273Steve Naroffstd::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
42274087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                                   llvm::StringRef funcName,
422854055232a5ddb9529726e934301b125cb720a273Steve Naroff                                                   std::string Tag) {
422954055232a5ddb9529726e934301b125cb720a273Steve Naroff  std::string StructRef = "struct " + Tag;
423054055232a5ddb9529726e934301b125cb720a273Steve Naroff  std::string S = "static void __";
42311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
423254055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += funcName;
423354055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "_block_copy_" + utostr(i);
423454055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "(" + StructRef;
423554055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "*dst, " + StructRef;
423654055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "*src) {";
42371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
423854055232a5ddb9529726e934301b125cb720a273Steve Naroff      E = ImportedBlockDecls.end(); I != E; ++I) {
42395bc60d0c324a1b3984cd4a32acb587c8f873ab5fSteve Naroff    S += "_Block_object_assign((void*)&dst->";
4240d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    S += (*I)->getNameAsString();
424147a242208867fa433d05a78bf346bbb37721a507Steve Naroff    S += ", (void*)src->";
4242d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    S += (*I)->getNameAsString();
4243bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    if (BlockByRefDeclsPtrSet.count((*I)))
424473e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4245d25d1b53f098a4dc52469d9956bdd248ea29b38eFariborz Jahanian    else
424673e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
424754055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
4248d25d1b53f098a4dc52469d9956bdd248ea29b38eFariborz Jahanian  S += "}\n";
4249d25d1b53f098a4dc52469d9956bdd248ea29b38eFariborz Jahanian
425054055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "\nstatic void __";
425154055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += funcName;
425254055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "_block_dispose_" + utostr(i);
425354055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "(" + StructRef;
425454055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "*src) {";
42551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
425654055232a5ddb9529726e934301b125cb720a273Steve Naroff      E = ImportedBlockDecls.end(); I != E; ++I) {
42575bc60d0c324a1b3984cd4a32acb587c8f873ab5fSteve Naroff    S += "_Block_object_dispose((void*)src->";
4258d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    S += (*I)->getNameAsString();
4259bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    if (BlockByRefDeclsPtrSet.count((*I)))
426073e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4261d25d1b53f098a4dc52469d9956bdd248ea29b38eFariborz Jahanian    else
426273e437bbe7e9631ad9055b1d50f4ae8564efbdf3Fariborz Jahanian      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
426354055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
42641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  S += "}\n";
426554055232a5ddb9529726e934301b125cb720a273Steve Naroff  return S;
426654055232a5ddb9529726e934301b125cb720a273Steve Naroff}
4267ef177820100ab583b08fd3056e2a5a52ee4b1629Argyrios Kyrtzidis
426801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroffstd::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
426901aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                             std::string Desc) {
4270ced80a848de94ef44b6e7b4ce6f182249b3141a8Steve Naroff  std::string S = "\nstruct " + Tag;
427154055232a5ddb9529726e934301b125cb720a273Steve Naroff  std::string Constructor = "  " + Tag;
42721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
427354055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += " {\n  struct __block_impl impl;\n";
427401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += "  struct " + Desc;
427501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += "* Desc;\n";
42761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
427701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  Constructor += "(void *fp, "; // Invoke function pointer.
427801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  Constructor += "struct " + Desc; // Descriptor pointer.
427901aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  Constructor += " *desc";
42801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
428154055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (BlockDeclRefs.size()) {
428254055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Output all "by copy" declarations.
4283bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
428454055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = BlockByCopyDecls.end(); I != E; ++I) {
428554055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += "  ";
4286d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      std::string FieldName = (*I)->getNameAsString();
428754055232a5ddb9529726e934301b125cb720a273Steve Naroff      std::string ArgName = "_" + FieldName;
428854055232a5ddb9529726e934301b125cb720a273Steve Naroff      // Handle nested closure invocation. For example:
428954055232a5ddb9529726e934301b125cb720a273Steve Naroff      //
429054055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   void (^myImportedBlock)(void);
429154055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
42921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      //
429354055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   void (^anotherBlock)(void);
429454055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   anotherBlock = ^(void) {
429554055232a5ddb9529726e934301b125cb720a273Steve Naroff      //     myImportedBlock(); // import and invoke the closure
429654055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   };
429754055232a5ddb9529726e934301b125cb720a273Steve Naroff      //
429801f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      if (isTopLevelBlockPointerType((*I)->getType())) {
429954055232a5ddb9529726e934301b125cb720a273Steve Naroff        S += "struct __block_impl *";
430054055232a5ddb9529726e934301b125cb720a273Steve Naroff        Constructor += ", void *" + ArgName;
430154055232a5ddb9529726e934301b125cb720a273Steve Naroff      } else {
43026cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        QualType QT = (*I)->getType();
43036cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        if (HasLocalVariableExternalStorage(*I))
43046cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian          QT = Context->getPointerType(QT);
43056cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
43066cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
430754055232a5ddb9529726e934301b125cb720a273Steve Naroff        Constructor += ", " + ArgName;
430854055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
430954055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += FieldName + ";\n";
431054055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
431154055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Output all "by ref" declarations.
4312bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
431354055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = BlockByRefDecls.end(); I != E; ++I) {
431454055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += "  ";
4315d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      std::string FieldName = (*I)->getNameAsString();
431654055232a5ddb9529726e934301b125cb720a273Steve Naroff      std::string ArgName = "_" + FieldName;
431754055232a5ddb9529726e934301b125cb720a273Steve Naroff      // Handle nested closure invocation. For example:
431854055232a5ddb9529726e934301b125cb720a273Steve Naroff      //
431954055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   void (^myImportedBlock)(void);
432054055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
43211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      //
432254055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   void (^anotherBlock)(void);
432354055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   anotherBlock = ^(void) {
432454055232a5ddb9529726e934301b125cb720a273Steve Naroff      //     myImportedBlock(); // import and invoke the closure
432554055232a5ddb9529726e934301b125cb720a273Steve Naroff      //   };
432654055232a5ddb9529726e934301b125cb720a273Steve Naroff      //
432701f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      if (isTopLevelBlockPointerType((*I)->getType())) {
432854055232a5ddb9529726e934301b125cb720a273Steve Naroff        S += "struct __block_impl *";
432954055232a5ddb9529726e934301b125cb720a273Steve Naroff        Constructor += ", void *" + ArgName;
433054055232a5ddb9529726e934301b125cb720a273Steve Naroff      } else {
4331a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian        std::string TypeString;
4332a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian        RewriteByRefString(TypeString, FieldName, (*I));
433352b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian        TypeString += " *";
433452b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian        FieldName = TypeString + FieldName;
433552b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian        ArgName = TypeString + ArgName;
433654055232a5ddb9529726e934301b125cb720a273Steve Naroff        Constructor += ", " + ArgName;
433754055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
433854055232a5ddb9529726e934301b125cb720a273Steve Naroff      S += FieldName + "; // by ref\n";
433954055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
434054055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Finish writing the constructor.
434120432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    Constructor += ", int flags=0)";
434254055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Initialize all "by copy" arguments.
434320432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    bool firsTime = true;
4344bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
434554055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = BlockByCopyDecls.end(); I != E; ++I) {
4346d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      std::string Name = (*I)->getNameAsString();
434720432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        if (firsTime) {
434820432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian          Constructor += " : ";
434920432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian          firsTime = false;
435020432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        }
435120432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        else
435220432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian          Constructor += ", ";
435320432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        if (isTopLevelBlockPointerType((*I)->getType()))
435420432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
435520432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        else
435620432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian          Constructor += Name + "(_" + Name + ")";
435754055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
435854055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Initialize all "by ref" arguments.
4359bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
436054055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = BlockByRefDecls.end(); I != E; ++I) {
4361d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner      std::string Name = (*I)->getNameAsString();
436220432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian      if (firsTime) {
436320432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        Constructor += " : ";
436420432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        firsTime = false;
436520432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian      }
436620432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian      else
436720432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        Constructor += ", ";
436801f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      if (isTopLevelBlockPointerType((*I)->getType()))
436920432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        Constructor += Name + "((struct __block_impl *)_"
437020432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian                        + Name + "->__forwarding)";
437154055232a5ddb9529726e934301b125cb720a273Steve Naroff      else
437220432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian        Constructor += Name + "(_" + Name + "->__forwarding)";
437354055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
437420432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian
437520432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    Constructor += " {\n";
437620432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    if (GlobalVarDecl)
437720432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
437820432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    else
437920432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
438020432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
438120432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian
438220432ef377e8ebcf2933d3f568eaf72766b06116Fariborz Jahanian    Constructor += "    Desc = desc;\n";
438354055232a5ddb9529726e934301b125cb720a273Steve Naroff  } else {
438454055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Finish writing the constructor.
438554055232a5ddb9529726e934301b125cb720a273Steve Naroff    Constructor += ", int flags=0) {\n";
4386621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    if (GlobalVarDecl)
4387621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4388621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    else
4389621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
439001aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
439101aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    Constructor += "    Desc = desc;\n";
439254055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
439354055232a5ddb9529726e934301b125cb720a273Steve Naroff  Constructor += "  ";
439454055232a5ddb9529726e934301b125cb720a273Steve Naroff  Constructor += "}\n";
439554055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += Constructor;
439654055232a5ddb9529726e934301b125cb720a273Steve Naroff  S += "};\n";
439754055232a5ddb9529726e934301b125cb720a273Steve Naroff  return S;
439854055232a5ddb9529726e934301b125cb720a273Steve Naroff}
439939ba4aeca296b1c9f04bde7d9d3cbbf129f1abd3Argyrios Kyrtzidis
440001aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroffstd::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
440101aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                                   std::string ImplTag, int i,
44024087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                                   llvm::StringRef FunName,
440301aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                                   unsigned hasCopy) {
440401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  std::string S = "\nstatic struct " + DescTag;
440501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff
440601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += " {\n  unsigned long reserved;\n";
440701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += "  unsigned long Block_size;\n";
440801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  if (hasCopy) {
44094fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian    S += "  void (*copy)(struct ";
44104fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian    S += ImplTag; S += "*, struct ";
44114fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian    S += ImplTag; S += "*);\n";
44124fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian
44134fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian    S += "  void (*dispose)(struct ";
44144fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian    S += ImplTag; S += "*);\n";
441501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  }
441601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += "} ";
441701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff
441801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += DescTag + "_DATA = { 0, sizeof(struct ";
441901aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += ImplTag + ")";
442001aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  if (hasCopy) {
44214087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
44224087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
442301aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  }
442401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  S += "};\n";
442501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  return S;
442601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff}
442701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff
442854055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
44294087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                                          llvm::StringRef FunName) {
4430abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  // Insert declaration for the function in which block literal is used.
4431bf07012cf92253380ce427924870288a34230d1bFariborz Jahanian  if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4432abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
44338611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian  bool RewriteSC = (GlobalVarDecl &&
44348611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian                    !Blocks.empty() &&
4435d931b086984257de68868a64a235c2b4b34003fbJohn McCall                    GlobalVarDecl->getStorageClass() == SC_Static &&
44368611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian                    GlobalVarDecl->getType().getCVRQualifiers());
44378611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian  if (RewriteSC) {
44388611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    std::string SC(" void __");
44398611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    SC += GlobalVarDecl->getNameAsString();
44408611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    SC += "() {}";
44418611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    InsertText(FunLocStart, SC);
44428611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian  }
44438611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian
444454055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Insert closures that were part of the function.
444572952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian  for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
444672952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian    CollectBlockDeclRefInfo(Blocks[i]);
44475e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    // Need to copy-in the inner copied-in variables not actually used in this
44485e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    // block.
444972952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian    for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
445072952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
445172952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      ValueDecl *VD = Exp->getDecl();
445272952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      BlockDeclRefs.push_back(Exp);
445372952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
445472952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        BlockByCopyDeclsPtrSet.insert(VD);
445572952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        BlockByCopyDecls.push_back(VD);
445672952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      }
445772952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
445872952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        BlockByRefDeclsPtrSet.insert(VD);
445972952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        BlockByRefDecls.push_back(VD);
446072952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      }
446192c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian      // imported objects in the inner blocks not used in the outer
446292c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian      // blocks must be copied/disposed in the outer block as well.
446392c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian      if (Exp->isByRef() ||
446492c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian          VD->getType()->isObjCObjectPointerType() ||
446592c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian          VD->getType()->isBlockPointerType())
446692c8568856bf24360f0a90a2161b9962263d4994Fariborz Jahanian        ImportedBlockDecls.insert(VD);
446772952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian    }
446854055232a5ddb9529726e934301b125cb720a273Steve Naroff
44694087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
44704087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
44711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
447201aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
447354055232a5ddb9529726e934301b125cb720a273Steve Naroff
4474d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(FunLocStart, CI);
447554055232a5ddb9529726e934301b125cb720a273Steve Naroff
447601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
44771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4478d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(FunLocStart, CF);
447954055232a5ddb9529726e934301b125cb720a273Steve Naroff
448054055232a5ddb9529726e934301b125cb720a273Steve Naroff    if (ImportedBlockDecls.size()) {
448101aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4482d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(FunLocStart, HF);
448354055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
448401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
448501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                               ImportedBlockDecls.size() > 0);
4486d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(FunLocStart, BD);
44871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
448854055232a5ddb9529726e934301b125cb720a273Steve Naroff    BlockDeclRefs.clear();
448954055232a5ddb9529726e934301b125cb720a273Steve Naroff    BlockByRefDecls.clear();
4490bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    BlockByRefDeclsPtrSet.clear();
449154055232a5ddb9529726e934301b125cb720a273Steve Naroff    BlockByCopyDecls.clear();
4492bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    BlockByCopyDeclsPtrSet.clear();
449354055232a5ddb9529726e934301b125cb720a273Steve Naroff    ImportedBlockDecls.clear();
449454055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
44958611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian  if (RewriteSC) {
449661b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian    // Must insert any 'const/volatile/static here. Since it has been
449761b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian    // removed as result of rewriting of block literals.
449861b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian    std::string SC;
4499d931b086984257de68868a64a235c2b4b34003fbJohn McCall    if (GlobalVarDecl->getStorageClass() == SC_Static)
450061b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian      SC = "static ";
450161b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian    if (GlobalVarDecl->getType().isConstQualified())
450261b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian      SC += "const ";
450361b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian    if (GlobalVarDecl->getType().isVolatileQualified())
450461b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian      SC += "volatile ";
45058611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    if (GlobalVarDecl->getType().isRestrictQualified())
45068611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian      SC += "restrict ";
45078611eb02e8296bd31ffa31b6eafefd76dd1e299cFariborz Jahanian    InsertText(FunLocStart, SC);
450861b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian  }
450961b82e3ed67d9c02d8cc0a8c5976e5fb7fad12a8Fariborz Jahanian
451054055232a5ddb9529726e934301b125cb720a273Steve Naroff  Blocks.clear();
45115e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  InnerDeclRefsCount.clear();
45125e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  InnerDeclRefs.clear();
451354055232a5ddb9529726e934301b125cb720a273Steve Naroff  RewrittenBlockExprs.clear();
451454055232a5ddb9529726e934301b125cb720a273Steve Naroff}
451554055232a5ddb9529726e934301b125cb720a273Steve Naroff
451654055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
451754055232a5ddb9529726e934301b125cb720a273Steve Naroff  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
45184087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  llvm::StringRef FuncName = FD->getName();
45191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
452054055232a5ddb9529726e934301b125cb720a273Steve Naroff  SynthesizeBlockLiterals(FunLocStart, FuncName);
452154055232a5ddb9529726e934301b125cb720a273Steve Naroff}
452254055232a5ddb9529726e934301b125cb720a273Steve Naroff
4523e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanianstatic void BuildUniqueMethodName(std::string &Name,
4524e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian                                  ObjCMethodDecl *MD) {
4525e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  ObjCInterfaceDecl *IFace = MD->getClassInterface();
45264087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  Name = IFace->getName();
4527e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  Name += "__" + MD->getSelector().getAsString();
4528e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  // Convert colons to underscores.
4529e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  std::string::size_type loc = 0;
4530e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  while ((loc = Name.find(":", loc)) != std::string::npos)
4531e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian    Name.replace(loc, 1, "_");
4532e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian}
4533e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian
453454055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4535ced80a848de94ef44b6e7b4ce6f182249b3141a8Steve Naroff  //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4536ced80a848de94ef44b6e7b4ce6f182249b3141a8Steve Naroff  //SourceLocation FunLocStart = MD->getLocStart();
45370e1c99a1a9068020daa7d85fcafb18490ea6a475Fariborz Jahanian  SourceLocation FunLocStart = MD->getLocStart();
4538e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  std::string FuncName;
4539e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  BuildUniqueMethodName(FuncName, MD);
45404087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  SynthesizeBlockLiterals(FunLocStart, FuncName);
454154055232a5ddb9529726e934301b125cb720a273Steve Naroff}
454254055232a5ddb9529726e934301b125cb720a273Steve Naroff
454354055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
45447502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
454554055232a5ddb9529726e934301b125cb720a273Steve Naroff    if (*CI) {
454654055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
454754055232a5ddb9529726e934301b125cb720a273Steve Naroff        GetBlockDeclRefExprs(CBE->getBody());
454854055232a5ddb9529726e934301b125cb720a273Steve Naroff      else
454954055232a5ddb9529726e934301b125cb720a273Steve Naroff        GetBlockDeclRefExprs(*CI);
455054055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
455154055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Handle specific things.
45526cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
455354055232a5ddb9529726e934301b125cb720a273Steve Naroff    // FIXME: Handle enums.
455454055232a5ddb9529726e934301b125cb720a273Steve Naroff    if (!isa<FunctionDecl>(CDRE->getDecl()))
455554055232a5ddb9529726e934301b125cb720a273Steve Naroff      BlockDeclRefs.push_back(CDRE);
45566cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  }
45576cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
45586cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    if (HasLocalVariableExternalStorage(DRE->getDecl())) {
45596cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        BlockDeclRefExpr *BDRE =
45606b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall          new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
45616b5a61b6dc400027fd793dcadceeb9da944a37eaJohn McCall                                        DRE->getType(),
4562f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        VK_LValue, DRE->getLocation(), false);
45636cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        BlockDeclRefs.push_back(BDRE);
45646cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    }
45656cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian
456654055232a5ddb9529726e934301b125cb720a273Steve Naroff  return;
456754055232a5ddb9529726e934301b125cb720a273Steve Naroff}
456854055232a5ddb9529726e934301b125cb720a273Steve Naroff
45695e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanianvoid RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
45705e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian                llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
457172952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian                llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
45727502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
45735e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    if (*CI) {
457472952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
457572952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
45765e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian        GetInnerBlockDeclRefExprs(CBE->getBody(),
45775e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian                                  InnerBlockDeclRefs,
457872952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian                                  InnerContexts);
457972952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian      }
45805e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian      else
45815e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian        GetInnerBlockDeclRefExprs(*CI,
45825e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian                                  InnerBlockDeclRefs,
458372952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian                                  InnerContexts);
45845e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
45855e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    }
45865e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  // Handle specific things.
45876cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
45885e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    if (!isa<FunctionDecl>(CDRE->getDecl()) &&
458972952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian        !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
45905e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian      InnerBlockDeclRefs.push_back(CDRE);
45916cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  }
45926cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
45936cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
45946cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      if (Var->isFunctionOrMethodVarDecl())
45956cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        ImportedLocalExternalDecls.insert(Var);
45966cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  }
459772952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian
45985e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  return;
45995e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian}
46005e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
46011f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian/// convertFunctionTypeOfBlocks - This routine converts a function type
46021f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian/// whose result type may be a block pointer or whose argument type(s)
46031f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian/// might be block pointers to an equivalent funtion type replacing
46041f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian/// all block pointers to function pointers.
46051f90622e9d24064164df1608ea125d0ed451ac68Fariborz JahanianQualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
46061f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
46071f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  // FTP will be null for closures that don't take arguments.
46081f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  // Generate a funky cast.
46091f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  llvm::SmallVector<QualType, 8> ArgTypes;
46101f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  QualType Res = FT->getResultType();
46114fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian  bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
46121f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian
46131f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  if (FTP) {
46141f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
46151f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian         E = FTP->arg_type_end(); I && (I != E); ++I) {
46161f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      QualType t = *I;
46171f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      // Make sure we convert "t (^)(...)" to "t (*)(...)".
46184fc8453dd02d015b1161d83a5740632617aedd12Fariborz Jahanian      if (convertBlockPointerToFunctionPointer(t))
46191f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian        HasBlockType = true;
46201f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian      ArgTypes.push_back(t);
46211f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian    }
46221f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  }
46231f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  QualType FuncType;
46241f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  // FIXME. Does this work if block takes no argument but has a return type
46251f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  // which is of block type?
46261f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  if (HasBlockType)
4627e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
46281f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  else FuncType = QualType(FT, 0);
46291f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  return FuncType;
46301f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian}
46311f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian
46328a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz JahanianStmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
463354055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Navigate to relevant type information.
463454055232a5ddb9529726e934301b125cb720a273Steve Naroff  const BlockPointerType *CPT = 0;
46351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
46368a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
46376217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    CPT = DRE->getType()->getAs<BlockPointerType>();
46388a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  } else if (const BlockDeclRefExpr *CDRE =
46398a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian              dyn_cast<BlockDeclRefExpr>(BlockExp)) {
46406217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    CPT = CDRE->getType()->getAs<BlockPointerType>();
46418a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
46426217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    CPT = MExpr->getType()->getAs<BlockPointerType>();
46438a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  }
46448a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
46458a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
46468a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  }
46478a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
46488a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    CPT = IEXPR->getType()->getAs<BlockPointerType>();
46498a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian  else if (const ConditionalOperator *CEXPR =
46508a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian            dyn_cast<ConditionalOperator>(BlockExp)) {
46518a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Expr *LHSExp = CEXPR->getLHS();
46528a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
46538a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Expr *RHSExp = CEXPR->getRHS();
46548a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
46558a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    Expr *CONDExp = CEXPR->getCond();
46568a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    ConditionalOperator *CondExpr =
46578a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian      new (Context) ConditionalOperator(CONDExp,
46588a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian                                      SourceLocation(), cast<Expr>(LHSStmt),
4659f9b949fecf339a2c9bd97dd11a272c4878f85ce4Fariborz Jahanian                                      SourceLocation(), cast<Expr>(RHSStmt),
46600943168ac126b8047f30f6bd215fbe7db14d61baJohn McCall                                      Exp->getType(), VK_RValue, OK_Ordinary);
46618a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian    return CondExpr;
4662e24b22bb58e38253da0bda26da51da7663ca743bFariborz Jahanian  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4663e24b22bb58e38253da0bda26da51da7663ca743bFariborz Jahanian    CPT = IRE->getType()->getAs<BlockPointerType>();
466454055232a5ddb9529726e934301b125cb720a273Steve Naroff  } else {
466554055232a5ddb9529726e934301b125cb720a273Steve Naroff    assert(1 && "RewriteBlockClass: Bad type");
466654055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
466754055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert(CPT && "RewriteBlockClass: Bad type");
4668183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
466954055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert(FT && "RewriteBlockClass: Bad type");
467072564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
467154055232a5ddb9529726e934301b125cb720a273Steve Naroff  // FTP will be null for closures that don't take arguments.
46721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4673465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4674aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff                                      SourceLocation(),
4675aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff                                      &Context->Idents.get("__block_impl"));
4676aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
467754055232a5ddb9529726e934301b125cb720a273Steve Naroff
4678aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Generate a funky cast.
4679aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  llvm::SmallVector<QualType, 8> ArgTypes;
46801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4681aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Push the block argument type.
4682aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  ArgTypes.push_back(PtrBlock);
468354055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (FTP) {
46841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4685aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff         E = FTP->arg_type_end(); I && (I != E); ++I) {
4686aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff      QualType t = *I;
4687aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff      // Make sure we convert "t (^)(...)" to "t (*)(...)".
46888188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian      if (!convertBlockPointerToFunctionPointer(t))
46898188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian        convertToUnqualifiedObjCType(t);
4690aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff      ArgTypes.push_back(t);
4691aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff    }
4692aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  }
4693aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Now do the pointer to function cast.
4694e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall  QualType PtrToFuncCastType
4695e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
46961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4697aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
46981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
46999d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4700a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                               CK_BitCast,
47019d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                               const_cast<Expr*>(BlockExp));
4702aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Don't forget the parens to enforce the proper binding.
47038189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
47048189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                                          BlkCast);
4705aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  //PE->dump();
47061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
470744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
47081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                     &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
47094afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor                                    /*BitWidth=*/0, /*Mutable=*/true);
47108189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4711f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            FD->getType(), VK_LValue,
4712f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            OK_Ordinary);
47131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
47148188e5f6367714e0eda2bdf9a9710131cb15bbfbFariborz Jahanian
47159d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4716a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                CK_BitCast, ME);
47178189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
47181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4719aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  llvm::SmallVector<Expr*, 8> BlkExprs;
4720aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Add the implicit argument.
4721aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  BlkExprs.push_back(BlkCast);
4722aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  // Add the user arguments.
47231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (CallExpr::arg_iterator I = Exp->arg_begin(),
472454055232a5ddb9529726e934301b125cb720a273Steve Naroff       E = Exp->arg_end(); I != E; ++I) {
4725aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff    BlkExprs.push_back(*I);
472654055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
4727668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek  CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4728668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek                                        BlkExprs.size(),
4729f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        Exp->getType(), VK_RValue,
4730f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        SourceLocation());
4731aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff  return CE;
473254055232a5ddb9529726e934301b125cb720a273Steve Naroff}
473354055232a5ddb9529726e934301b125cb720a273Steve Naroff
4734621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff// We need to return the rewritten expression to handle cases where the
4735621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff// BlockDeclRefExpr is embedded in another expression being rewritten.
4736621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff// For example:
4737621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//
4738621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff// int main() {
4739621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//    __block Foo *f;
4740621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//    __block int i;
47411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump//
4742621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//    void (^myblock)() = ^() {
4743621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4744621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//        i = 77;
4745621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//    };
4746621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff//}
4747f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz JahanianStmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
4748bbf37e232b10793b9ec91f4ea01ec168123d5026Fariborz Jahanian  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4749f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  // for each DeclRefExp where BYREFVAR is name of the variable.
4750f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  ValueDecl *VD;
4751f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  bool isArrow = true;
4752f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4753f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    VD = BDRE->getDecl();
4754f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  else {
4755f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4756f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    isArrow = false;
4757f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  }
4758f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian
4759ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian  FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4760ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                                    &Context->Idents.get("__forwarding"),
4761ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                                    Context->VoidPtrTy, 0,
4762ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                                    /*BitWidth=*/0, /*Mutable=*/true);
4763f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4764f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian                                            FD, SourceLocation(),
4765f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            FD->getType(), VK_LValue,
4766f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            OK_Ordinary);
4767f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian
47684087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  llvm::StringRef Name = VD->getName();
4769ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian  FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4770ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                         &Context->Idents.get(Name),
4771ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                         Context->VoidPtrTy, 0,
4772ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                         /*BitWidth=*/0, /*Mutable=*/true);
4773ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian  ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4774f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4775ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian
4776ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian
4777ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian
4778df8570d1ff98155b74df2a0544068f40b4fd5195Steve Naroff  // Need parens to enforce precedence.
4779ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4780ec878f2726e00e6dc0c432f462dab099e3f4a717Fariborz Jahanian                                          ME);
4781f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  ReplaceStmt(DeclRefExp, PE);
4782621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  return PE;
478354055232a5ddb9529726e934301b125cb720a273Steve Naroff}
478454055232a5ddb9529726e934301b125cb720a273Steve Naroff
47856cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian// Rewrites the imported local variable V with external storage
47866cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian// (static, extern, etc.) as *V
47876cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian//
47886cb6eb4c792b504ad652d9230640656852e18ee9Fariborz JahanianStmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
47896cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  ValueDecl *VD = DRE->getDecl();
47906cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
47916cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    if (!ImportedLocalExternalDecls.count(Var))
47926cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      return DRE;
4793f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4794f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                          VK_LValue, OK_Ordinary,
4795f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                          DRE->getLocation());
47966cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  // Need parens to enforce precedence.
47976cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
47986cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian                                          Exp);
47996cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  ReplaceStmt(DRE, PE);
48006cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian  return PE;
48016cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian}
48026cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian
4803b2f9e516327310d95840d442416084508f80c183Steve Naroffvoid RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4804b2f9e516327310d95840d442416084508f80c183Steve Naroff  SourceLocation LocStart = CE->getLParenLoc();
4805b2f9e516327310d95840d442416084508f80c183Steve Naroff  SourceLocation LocEnd = CE->getRParenLoc();
4806fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
4807fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Need to avoid trying to rewrite synthesized casts.
4808fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (LocStart.isInvalid())
4809fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
48108f6ce5796fb74daf0c4cd39fbda9f7ceb1c7a7b6Steve Naroff  // Need to avoid trying to rewrite casts contained in macros.
48118f6ce5796fb74daf0c4cd39fbda9f7ceb1c7a7b6Steve Naroff  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
48128f6ce5796fb74daf0c4cd39fbda9f7ceb1c7a7b6Steve Naroff    return;
48131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
481454055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *startBuf = SM->getCharacterData(LocStart);
481554055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *endBuf = SM->getCharacterData(LocEnd);
48161d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian  QualType QT = CE->getType();
48171d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian  const Type* TypePtr = QT->getAs<Type>();
48181d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian  if (isa<TypeOfExprType>(TypePtr)) {
48191d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
48201d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
48211d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian    std::string TypeAsString = "(";
4822afad76f6134e635c3cb240ec725d3b7989e7a625Fariborz Jahanian    RewriteBlockPointerType(TypeAsString, QT);
48231d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian    TypeAsString += ")";
4824d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
48251d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian    return;
48261d4fca2e42da8506cc1042a1ea93815a8e9ae0f0Fariborz Jahanian  }
482754055232a5ddb9529726e934301b125cb720a273Steve Naroff  // advance the location to startArgList.
482854055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *argPtr = startBuf;
48291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
483054055232a5ddb9529726e934301b125cb720a273Steve Naroff  while (*argPtr++ && (argPtr < endBuf)) {
483154055232a5ddb9529726e934301b125cb720a273Steve Naroff    switch (*argPtr) {
4832b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case '^':
4833b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      // Replace the '^' with '*'.
4834b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4835d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(LocStart, 1, "*");
4836b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      break;
483754055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
483854055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
483954055232a5ddb9529726e934301b125cb720a273Steve Naroff  return;
484054055232a5ddb9529726e934301b125cb720a273Steve Naroff}
484154055232a5ddb9529726e934301b125cb720a273Steve Naroff
484254055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
484354055232a5ddb9529726e934301b125cb720a273Steve Naroff  SourceLocation DeclLoc = FD->getLocation();
484454055232a5ddb9529726e934301b125cb720a273Steve Naroff  unsigned parenCount = 0;
48451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
484654055232a5ddb9529726e934301b125cb720a273Steve Naroff  // We have 1 or more arguments that have closure pointers.
484754055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *startBuf = SM->getCharacterData(DeclLoc);
484854055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *startArgList = strchr(startBuf, '(');
48491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
485054055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
48511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
485254055232a5ddb9529726e934301b125cb720a273Steve Naroff  parenCount++;
485354055232a5ddb9529726e934301b125cb720a273Steve Naroff  // advance the location to startArgList.
485454055232a5ddb9529726e934301b125cb720a273Steve Naroff  DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
485554055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
48561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
485754055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *argPtr = startArgList;
48581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
485954055232a5ddb9529726e934301b125cb720a273Steve Naroff  while (*argPtr++ && parenCount) {
486054055232a5ddb9529726e934301b125cb720a273Steve Naroff    switch (*argPtr) {
4861b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case '^':
4862b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      // Replace the '^' with '*'.
4863b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4864d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      ReplaceText(DeclLoc, 1, "*");
4865b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      break;
4866b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case '(':
4867b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      parenCount++;
4868b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      break;
4869b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case ')':
4870b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      parenCount--;
4871b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump      break;
487254055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
487354055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
487454055232a5ddb9529726e934301b125cb720a273Steve Naroff  return;
487554055232a5ddb9529726e934301b125cb720a273Steve Naroff}
487654055232a5ddb9529726e934301b125cb720a273Steve Naroff
487754055232a5ddb9529726e934301b125cb720a273Steve Naroffbool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
487872564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor  const FunctionProtoType *FTP;
48796217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek  const PointerType *PT = QT->getAs<PointerType>();
488054055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (PT) {
4881183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
488254055232a5ddb9529726e934301b125cb720a273Steve Naroff  } else {
48836217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
488454055232a5ddb9529726e934301b125cb720a273Steve Naroff    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4885183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
488654055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
488754055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (FTP) {
48881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
488954055232a5ddb9529726e934301b125cb720a273Steve Naroff         E = FTP->arg_type_end(); I != E; ++I)
489001f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      if (isTopLevelBlockPointerType(*I))
489154055232a5ddb9529726e934301b125cb720a273Steve Naroff        return true;
489254055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
489354055232a5ddb9529726e934301b125cb720a273Steve Naroff  return false;
489454055232a5ddb9529726e934301b125cb720a273Steve Naroff}
489554055232a5ddb9529726e934301b125cb720a273Steve Naroff
4896e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanianbool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4897e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  const FunctionProtoType *FTP;
4898e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  const PointerType *PT = QT->getAs<PointerType>();
4899e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  if (PT) {
4900e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4901e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  } else {
4902e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4903e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4904e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4905e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  }
4906e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  if (FTP) {
4907e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
490806de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian         E = FTP->arg_type_end(); I != E; ++I) {
490906de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian      if ((*I)->isObjCQualifiedIdType())
491006de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian        return true;
491106de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian      if ((*I)->isObjCObjectPointerType() &&
491206de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian          (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4913e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        return true;
491406de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian    }
491506de2cfe0b46e525ba8618536b12aecfbd12d127Fariborz Jahanian
4916e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  }
4917e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  return false;
4918e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian}
4919e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian
49208189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenekvoid RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
49218189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                                     const char *&RParen) {
492254055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *argPtr = strchr(Name, '(');
492354055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
49241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
492554055232a5ddb9529726e934301b125cb720a273Steve Naroff  LParen = argPtr; // output the start.
492654055232a5ddb9529726e934301b125cb720a273Steve Naroff  argPtr++; // skip past the left paren.
492754055232a5ddb9529726e934301b125cb720a273Steve Naroff  unsigned parenCount = 1;
49281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
492954055232a5ddb9529726e934301b125cb720a273Steve Naroff  while (*argPtr && parenCount) {
493054055232a5ddb9529726e934301b125cb720a273Steve Naroff    switch (*argPtr) {
4931b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case '(': parenCount++; break;
4932b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    case ')': parenCount--; break;
4933b7166334d897e1e4e6a5b428fe2d0ec752ef187fMike Stump    default: break;
493454055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
493554055232a5ddb9529726e934301b125cb720a273Steve Naroff    if (parenCount) argPtr++;
493654055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
493754055232a5ddb9529726e934301b125cb720a273Steve Naroff  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
493854055232a5ddb9529726e934301b125cb720a273Steve Naroff  RParen = argPtr; // output the end
493954055232a5ddb9529726e934301b125cb720a273Steve Naroff}
494054055232a5ddb9529726e934301b125cb720a273Steve Naroff
494154055232a5ddb9529726e934301b125cb720a273Steve Naroffvoid RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
494254055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
494354055232a5ddb9529726e934301b125cb720a273Steve Naroff    RewriteBlockPointerFunctionArgs(FD);
494454055232a5ddb9529726e934301b125cb720a273Steve Naroff    return;
49451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
494654055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Handle Variables and Typedefs.
494754055232a5ddb9529726e934301b125cb720a273Steve Naroff  SourceLocation DeclLoc = ND->getLocation();
494854055232a5ddb9529726e934301b125cb720a273Steve Naroff  QualType DeclT;
494954055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
495054055232a5ddb9529726e934301b125cb720a273Steve Naroff    DeclT = VD->getType();
495154055232a5ddb9529726e934301b125cb720a273Steve Naroff  else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
495254055232a5ddb9529726e934301b125cb720a273Steve Naroff    DeclT = TDD->getUnderlyingType();
495354055232a5ddb9529726e934301b125cb720a273Steve Naroff  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
495454055232a5ddb9529726e934301b125cb720a273Steve Naroff    DeclT = FD->getType();
49551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  else
495654055232a5ddb9529726e934301b125cb720a273Steve Naroff    assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
49571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
495854055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *startBuf = SM->getCharacterData(DeclLoc);
495954055232a5ddb9529726e934301b125cb720a273Steve Naroff  const char *endBuf = startBuf;
496054055232a5ddb9529726e934301b125cb720a273Steve Naroff  // scan backward (from the decl location) for the end of the previous decl.
496154055232a5ddb9529726e934301b125cb720a273Steve Naroff  while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
496254055232a5ddb9529726e934301b125cb720a273Steve Naroff    startBuf--;
4963e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4964e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  std::string buf;
4965e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  unsigned OrigLength=0;
496654055232a5ddb9529726e934301b125cb720a273Steve Naroff  // *startBuf != '^' if we are dealing with a pointer to function that
496754055232a5ddb9529726e934301b125cb720a273Steve Naroff  // may take block argument types (which will be handled below).
496854055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (*startBuf == '^') {
496954055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Replace the '^' with '*', computing a negative offset.
4970e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    buf = '*';
4971e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    startBuf++;
4972e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    OrigLength++;
497354055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
4974e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  while (*startBuf != ')') {
4975e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    buf += *startBuf;
4976e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    startBuf++;
4977e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    OrigLength++;
4978e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  }
4979e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  buf += ')';
4980e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  OrigLength++;
4981e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian
4982e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4983e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian      PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
498454055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Replace the '^' with '*' for arguments.
4985e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    // Replace id<P> with id/*<>*/
498654055232a5ddb9529726e934301b125cb720a273Steve Naroff    DeclLoc = ND->getLocation();
498754055232a5ddb9529726e934301b125cb720a273Steve Naroff    startBuf = SM->getCharacterData(DeclLoc);
498854055232a5ddb9529726e934301b125cb720a273Steve Naroff    const char *argListBegin, *argListEnd;
498954055232a5ddb9529726e934301b125cb720a273Steve Naroff    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
499054055232a5ddb9529726e934301b125cb720a273Steve Naroff    while (argListBegin < argListEnd) {
4991e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian      if (*argListBegin == '^')
4992e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += '*';
4993e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian      else if (*argListBegin ==  '<') {
4994e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += "/*";
4995e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += *argListBegin++;
4996e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        OrigLength++;;
4997e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        while (*argListBegin != '>') {
4998e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian          buf += *argListBegin++;
4999e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian          OrigLength++;
5000e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        }
5001e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += *argListBegin;
5002e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += "*/";
500354055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
5004e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian      else
5005e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian        buf += *argListBegin;
500654055232a5ddb9529726e934301b125cb720a273Steve Naroff      argListBegin++;
5007e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian      OrigLength++;
500854055232a5ddb9529726e934301b125cb720a273Steve Naroff    }
5009e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    buf += ')';
5010e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian    OrigLength++;
501154055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
5012e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian  ReplaceText(Start, OrigLength, buf);
5013e985d01390a828d9ea679c26c711d5509fd27709Fariborz Jahanian
501454055232a5ddb9529726e934301b125cb720a273Steve Naroff  return;
501554055232a5ddb9529726e934301b125cb720a273Steve Naroff}
501654055232a5ddb9529726e934301b125cb720a273Steve Naroff
5017d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian
5018d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5019d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5020d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                    struct Block_byref_id_object *src) {
5021d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///  _Block_object_assign (&_dest->object, _src->object,
5022d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5023d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                        [|BLOCK_FIELD_IS_WEAK]) // object
5024d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///  _Block_object_assign(&_dest->object, _src->object,
5025d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5026d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                       [|BLOCK_FIELD_IS_WEAK]) // block
5027d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// }
5028d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// And:
5029d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5030d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///  _Block_object_dispose(_src->object,
5031d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5032d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                        [|BLOCK_FIELD_IS_WEAK]) // object
5033d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///  _Block_object_dispose(_src->object,
5034d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5035d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian///                         [|BLOCK_FIELD_IS_WEAK]) // block
5036d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// }
5037d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian
5038ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanianstd::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5039ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian                                                          int flag) {
5040d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  std::string S;
50411211a71912f263f6991eebfc27a8421a8800b9ecBenjamin Kramer  if (CopyDestroyCache.count(flag))
5042d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    return S;
5043ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  CopyDestroyCache.insert(flag);
5044ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S = "static void __Block_byref_id_object_copy_";
5045ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S += utostr(flag);
5046ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S += "(void *dst, void *src) {\n";
5047ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian
5048d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  // offset into the object pointer is computed as:
5049d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  // void * + void* + int + int + void* + void *
5050d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  unsigned IntSize =
5051d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5052d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  unsigned VoidPtrSize =
5053d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5054d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian
5055d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5056d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += " _Block_object_assign((char*)dst + ";
5057d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += utostr(offset);
5058d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += ", *(void * *) ((char*)src + ";
5059d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += utostr(offset);
5060d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += "), ";
5061d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += utostr(flag);
5062d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += ");\n}\n";
5063d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian
5064ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S += "static void __Block_byref_id_object_dispose_";
5065ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S += utostr(flag);
5066ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian  S += "(void *src) {\n";
5067d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5068d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += utostr(offset);
5069d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += "), ";
5070d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += utostr(flag);
5071d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  S += ");\n}\n";
5072d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  return S;
5073d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian}
5074d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian
507552b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// RewriteByRefVar - For each __block typex ND variable this routine transforms
507652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// the declaration into:
507752b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// struct __Block_byref_ND {
507852b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// void *__isa;                  // NULL for everything except __weak pointers
507952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// struct __Block_byref_ND *__forwarding;
508052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// int32_t __flags;
508152b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// int32_t __size;
5082d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5083d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
508452b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// typex ND;
508552b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// };
508652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian///
508752b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// It then replaces declaration of ND variable with:
508852b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
508952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian///                               __size=sizeof(struct __Block_byref_ND),
509052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian///                               ND=initializer-if-any};
509152b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian///
509252b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian///
509352b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanianvoid RewriteObjC::RewriteByRefVar(VarDecl *ND) {
5094abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  // Insert declaration for the function in which block literal is
5095abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  // used.
5096abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian  if (CurFunctionDeclToDeclareForBlock)
5097abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
50982086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  int flag = 0;
50992086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  int isa = 0;
510052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5101d64a4f4798907495091daf2b081c3d62d729dca9Fariborz Jahanian  if (DeclLoc.isInvalid())
5102d64a4f4798907495091daf2b081c3d62d729dca9Fariborz Jahanian    // If type location is missing, it is because of missing type (a warning).
5103d64a4f4798907495091daf2b081c3d62d729dca9Fariborz Jahanian    // Use variable's location which is good for this case.
5104d64a4f4798907495091daf2b081c3d62d729dca9Fariborz Jahanian    DeclLoc = ND->getLocation();
510552b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  const char *startBuf = SM->getCharacterData(DeclLoc);
51066f0a0a9d2068c2ee9f399c72bf550c307bb76f9aFariborz Jahanian  SourceLocation X = ND->getLocEnd();
51076f0a0a9d2068c2ee9f399c72bf550c307bb76f9aFariborz Jahanian  X = SM->getInstantiationLoc(X);
51086f0a0a9d2068c2ee9f399c72bf550c307bb76f9aFariborz Jahanian  const char *endBuf = SM->getCharacterData(X);
510952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  std::string Name(ND->getNameAsString());
5110a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  std::string ByrefType;
51111e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian  RewriteByRefString(ByrefType, Name, ND, true);
511252b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += " {\n";
511352b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += "  void *__isa;\n";
5114a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  RewriteByRefString(ByrefType, Name, ND);
5115a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  ByrefType += " *__forwarding;\n";
511652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += " int __flags;\n";
511752b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += " int __size;\n";
5118d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  // Add void *__Block_byref_id_object_copy;
5119d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  // void *__Block_byref_id_object_dispose; if needed.
5120f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  QualType Ty = ND->getType();
5121f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5122f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  if (HasCopyAndDispose) {
5123d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5124d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5125f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  }
5126f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian
5127f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  Ty.getAsStringInternal(Name, Context->PrintingPolicy);
512852b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += " " + Name + ";\n";
512952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  ByrefType += "};\n";
513052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  // Insert this type in global scope. It is needed by helper function.
5131dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian  SourceLocation FunLocStart;
5132dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian  if (CurFunctionDef)
5133dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian     FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5134dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian  else {
5135dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5136dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    FunLocStart = CurMethodDef->getLocStart();
5137dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian  }
5138d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(FunLocStart, ByrefType);
51392086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  if (Ty.isObjCGCWeak()) {
51402086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    flag |= BLOCK_FIELD_IS_WEAK;
51412086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    isa = 1;
51422086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian  }
51432086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian
5144d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  if (HasCopyAndDispose) {
5145ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    flag = BLOCK_BYREF_CALLER;
5146ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    QualType Ty = ND->getType();
5147ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5148ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    if (Ty->isBlockPointerType())
5149ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      flag |= BLOCK_FIELD_IS_BLOCK;
5150ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    else
5151ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      flag |= BLOCK_FIELD_IS_OBJECT;
5152ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5153d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    if (!HF.empty())
5154d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer      InsertText(FunLocStart, HF);
5155d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian  }
515652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian
515752b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  // struct __Block_byref_ND ND =
515852b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
515952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  //  initializer-if-any};
516052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  bool hasInit = (ND->getInit() != 0);
5161e1f84f8e4cd02347ab0e74eb8f328b3bcacb369cFariborz Jahanian  unsigned flags = 0;
5162e1f84f8e4cd02347ab0e74eb8f328b3bcacb369cFariborz Jahanian  if (HasCopyAndDispose)
5163e1f84f8e4cd02347ab0e74eb8f328b3bcacb369cFariborz Jahanian    flags |= BLOCK_HAS_COPY_DISPOSE;
516452b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  Name = ND->getNameAsString();
5165a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  ByrefType.clear();
5166a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian  RewriteByRefString(ByrefType, Name, ND);
51672663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian  std::string ForwardingCastType("(");
51682663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian  ForwardingCastType += ByrefType + " *)";
516952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  if (!hasInit) {
51702086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    ByrefType += " " + Name + " = {(void*)";
51712086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    ByrefType += utostr(isa);
51722663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5173ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    ByrefType += utostr(flags);
5174f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    ByrefType += ", ";
5175a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    ByrefType += "sizeof(";
5176a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    RewriteByRefString(ByrefType, Name, ND);
5177a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    ByrefType += ")";
5178d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    if (HasCopyAndDispose) {
5179ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += ", __Block_byref_id_object_copy_";
5180ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += utostr(flag);
5181ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += ", __Block_byref_id_object_dispose_";
5182ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += utostr(flag);
5183d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    }
518452b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian    ByrefType += "};\n";
5185d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
518652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  }
518752b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  else {
5188dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    SourceLocation startLoc;
5189dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    Expr *E = ND->getInit();
5190dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5191dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian      startLoc = ECE->getLParenLoc();
5192dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    else
5193dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian      startLoc = E->getLocStart();
5194791b10d03570ca8c5d3e344cc09900d1a8313999Fariborz Jahanian    startLoc = SM->getInstantiationLoc(startLoc);
5195dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    endBuf = SM->getCharacterData(startLoc);
519652b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian    ByrefType += " " + Name;
5197dfa4fa0fc5b78a91c74db84fce305771c2038229Fariborz Jahanian    ByrefType += " = {(void*)";
51982086d544d38f2611f2fba034e25833a47c81fb21Fariborz Jahanian    ByrefType += utostr(isa);
51992663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5200ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian    ByrefType += utostr(flags);
5201f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    ByrefType += ", ";
5202a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    ByrefType += "sizeof(";
5203a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    RewriteByRefString(ByrefType, Name, ND);
5204a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian    ByrefType += "), ";
5205d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    if (HasCopyAndDispose) {
5206ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += "__Block_byref_id_object_copy_";
5207ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += utostr(flag);
5208ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += ", __Block_byref_id_object_dispose_";
5209ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += utostr(flag);
5210ab10b2ebad09c283ccab0ef043118b3cf0166b56Fariborz Jahanian      ByrefType += ", ";
5211d2eb1fdb1cfd37a6b93b46161826a23740d185e7Fariborz Jahanian    }
5212d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5213c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff
5214c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // Complete the newly synthesized compound expression by inserting a right
5215c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // curly brace before the end of the declaration.
5216c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // FIXME: This approach avoids rewriting the initializer expression. It
5217c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // also assumes there is only one declarator. For example, the following
5218c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // isn't currently supported by this routine (in general):
5219c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    //
5220c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5221c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    //
52225f371ee49c11ced954ee2c805ff1adfdcef94774Fariborz Jahanian    const char *startInitializerBuf = SM->getCharacterData(startLoc);
52235f371ee49c11ced954ee2c805ff1adfdcef94774Fariborz Jahanian    const char *semiBuf = strchr(startInitializerBuf, ';');
5224c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5225c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff    SourceLocation semiLoc =
52265f371ee49c11ced954ee2c805ff1adfdcef94774Fariborz Jahanian      startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
5227c5143c538783a2834cfdc3d29db0ff76e857818fSteve Naroff
5228d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    InsertText(semiLoc, "}");
522952b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian  }
52301be6b460d5aa4dda4274a15eeba824dfd4ad10d0Fariborz Jahanian  return;
52311be6b460d5aa4dda4274a15eeba824dfd4ad10d0Fariborz Jahanian}
52321be6b460d5aa4dda4274a15eeba824dfd4ad10d0Fariborz Jahanian
52331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
523454055232a5ddb9529726e934301b125cb720a273Steve Naroff  // Add initializers for any closure decl refs.
523554055232a5ddb9529726e934301b125cb720a273Steve Naroff  GetBlockDeclRefExprs(Exp->getBody());
523654055232a5ddb9529726e934301b125cb720a273Steve Naroff  if (BlockDeclRefs.size()) {
523754055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Unique all "by copy" declarations.
523854055232a5ddb9529726e934301b125cb720a273Steve Naroff    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5239bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian      if (!BlockDeclRefs[i]->isByRef()) {
5240bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian        if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5241bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5242bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5243bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian        }
5244bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian      }
524554055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Unique all "by ref" declarations.
524654055232a5ddb9529726e934301b125cb720a273Steve Naroff    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
524754055232a5ddb9529726e934301b125cb720a273Steve Naroff      if (BlockDeclRefs[i]->isByRef()) {
5248bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian        if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5249bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5250bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5251bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian        }
525254055232a5ddb9529726e934301b125cb720a273Steve Naroff      }
525354055232a5ddb9529726e934301b125cb720a273Steve Naroff    // Find any imported blocks...they will need special attention.
525454055232a5ddb9529726e934301b125cb720a273Steve Naroff    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
52554fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian      if (BlockDeclRefs[i]->isByRef() ||
52564fcc4fd1adf272450bdecab7f9133ae2f0b8aa19Fariborz Jahanian          BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
52575b011b050e764fe1c2a38bd81b386fc6e66eeb93Fariborz Jahanian          BlockDeclRefs[i]->getType()->isBlockPointerType())
525854055232a5ddb9529726e934301b125cb720a273Steve Naroff        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
525954055232a5ddb9529726e934301b125cb720a273Steve Naroff  }
526054055232a5ddb9529726e934301b125cb720a273Steve Naroff}
526154055232a5ddb9529726e934301b125cb720a273Steve Naroff
52624087f27e5416c799bcb6be072f905be752acb61cDaniel DunbarFunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
5263fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  IdentifierInfo *ID = &Context->Idents.get(name);
526472564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
52651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
5266d931b086984257de68868a64a235c2b4b34003fbJohn McCall                              ID, FType, 0, SC_Extern,
5267d931b086984257de68868a64a235c2b4b34003fbJohn McCall                              SC_None, false, false);
5268fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
5269fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
52705e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz JahanianStmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
52715e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian          const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
527205318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian  const BlockDecl *block = Exp->getBlockDecl();
5273fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  Blocks.push_back(Exp);
5274fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5275fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  CollectBlockDeclRefInfo(Exp);
52765e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
52775e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  // Add inner imported variables now used in current block.
52785e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian int countOfInnerDecls = 0;
52791276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian  if (!InnerBlockDeclRefs.empty()) {
52801276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
52811276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
52821276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      ValueDecl *VD = Exp->getDecl();
52831276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
52845e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian      // We need to save the copied-in variables in nested
52855e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian      // blocks because it is needed at the end for some of the API generations.
52865e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian      // See SynthesizeBlockLiterals routine.
52871276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
52881276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockDeclRefs.push_back(Exp);
52891276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockByCopyDeclsPtrSet.insert(VD);
52901276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockByCopyDecls.push_back(VD);
52911276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      }
52921276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
52931276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
52941276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockDeclRefs.push_back(Exp);
52951276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockByRefDeclsPtrSet.insert(VD);
52961276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        BlockByRefDecls.push_back(VD);
52971276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      }
5298f89c4270c94ddd966819fe6b8306aa572d1e5d83Fariborz Jahanian    }
52991276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian    // Find any imported blocks...they will need special attention.
53001276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
53011276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian      if (InnerBlockDeclRefs[i]->isByRef() ||
53021276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian          InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
53031276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian          InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
53041276bfe0cec18a8b07226797f410b7506005269dFariborz Jahanian        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
53055e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  }
53065e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian  InnerDeclRefsCount.push_back(countOfInnerDecls);
53075e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
5308fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string FuncName;
53091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5310fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (CurFunctionDef)
5311077bf5e2f48acfa9e7d69429b6e4ba86ea14896dChris Lattner    FuncName = CurFunctionDef->getNameAsString();
5312e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  else if (CurMethodDef)
5313e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian    BuildUniqueMethodName(FuncName, CurMethodDef);
5314e61a1d4c57bbce3dfaa191a4b4de48ad79ac0b83Fariborz Jahanian  else if (GlobalVarDecl)
5315d9d22dd9c94618490dbffb0e2caf222530ca39d3Chris Lattner    FuncName = std::string(GlobalVarDecl->getNameAsString());
53161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5317fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string BlockNumber = utostr(Blocks.size()-1);
53181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5319fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5320fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
53211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5322fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Get a pointer to the function type so we can cast appropriately.
53231f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
53241f90622e9d24064164df1608ea125d0ed451ac68Fariborz Jahanian  QualType FType = Context->getPointerType(BFT);
5325fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5326fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  FunctionDecl *FD;
5327fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  Expr *NewRep;
53281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5329fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Simulate a contructor call...
53304087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  FD = SynthBlockInitFunctionDecl(Tag);
5331f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5332f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                               SourceLocation());
53331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5334fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  llvm::SmallVector<Expr*, 4> InitExprs;
53351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5336fdc0372eda30952b03f3fd4269dbc4b2acfdfa55Steve Naroff  // Initialize the block function.
53374087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar  FD = SynthBlockInitFunctionDecl(Func);
5338f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
53398189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                                               SourceLocation());
53409d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5341a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                                CK_BitCast, Arg);
53421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  InitExprs.push_back(castExpr);
53431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
534401aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  // Initialize the block descriptor.
534501aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
534601aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff
534701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
534801aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                    &Context->Idents.get(DescData.c_str()),
534901aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff                                    Context->VoidPtrTy, 0,
5350d931b086984257de68868a64a235c2b4b34003fbJohn McCall                                    SC_Static, SC_None);
5351f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall  UnaryOperator *DescRefExpr =
5352f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall    new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5353f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                          Context->VoidPtrTy,
5354f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                          VK_LValue,
5355f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                                          SourceLocation()),
5356f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                UO_AddrOf,
5357f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                Context->getPointerType(Context->VoidPtrTy),
5358f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                VK_RValue, OK_Ordinary,
5359f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                SourceLocation());
536001aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  InitExprs.push_back(DescRefExpr);
536101aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff
5362fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Add initializers for any closure decl refs.
5363fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (BlockDeclRefs.size()) {
5364fdc0372eda30952b03f3fd4269dbc4b2acfdfa55Steve Naroff    Expr *Exp;
5365fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Output all "by copy" declarations.
5366bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5367fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff         E = BlockByCopyDecls.end(); I != E; ++I) {
5368fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      if (isObjCType((*I)->getType())) {
5369fdc0372eda30952b03f3fd4269dbc4b2acfdfa55Steve Naroff        // FIXME: Conform to ABI ([[obj retain] autorelease]).
53704087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar        FD = SynthBlockInitFunctionDecl((*I)->getName());
5371f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall        Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5372f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        SourceLocation());
5373a5a7987394ca15334c03b7e168677a8056561062Fariborz Jahanian        if (HasLocalVariableExternalStorage(*I)) {
5374a5a7987394ca15334c03b7e168677a8056561062Fariborz Jahanian          QualType QT = (*I)->getType();
5375a5a7987394ca15334c03b7e168677a8056561062Fariborz Jahanian          QT = Context->getPointerType(QT);
5376f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5377f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            OK_Ordinary, SourceLocation());
5378a5a7987394ca15334c03b7e168677a8056561062Fariborz Jahanian        }
537901f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff      } else if (isTopLevelBlockPointerType((*I)->getType())) {
53804087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar        FD = SynthBlockInitFunctionDecl((*I)->getName());
5381f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall        Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5382f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        SourceLocation());
53839d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5384a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall                                       CK_BitCast, Arg);
5385fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      } else {
53864087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar        FD = SynthBlockInitFunctionDecl((*I)->getName());
5387f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall        Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5388f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                        SourceLocation());
53896cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        if (HasLocalVariableExternalStorage(*I)) {
53906cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian          QualType QT = (*I)->getType();
53916cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian          QT = Context->getPointerType(QT);
5392f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5393f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                            OK_Ordinary, SourceLocation());
53946cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian        }
53956cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian
5396fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      }
53971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      InitExprs.push_back(Exp);
5398fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    }
5399fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Output all "by ref" declarations.
5400bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5401fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff         E = BlockByRefDecls.end(); I != E; ++I) {
54022663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      ValueDecl *ND = (*I);
54032663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      std::string Name(ND->getNameAsString());
54042663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      std::string RecName;
54051e8011e2fcddc4a638d210ec2dcd21adcf7b1763Fariborz Jahanian      RewriteByRefString(RecName, Name, ND, true);
54062663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
54072663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian                                                + sizeof("struct"));
5408465d41b92b2c862f3062c412a0538db65c6a2661Abramo Bagnara      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
54092663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian                                          SourceLocation(), II);
54102663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
54112663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
54122663f527c2717295fbaed4715945b879ad68f4cfFariborz Jahanian
54134087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar      FD = SynthBlockInitFunctionDecl((*I)->getName());
5414f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall      Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5415f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                      SourceLocation());
541605318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian      bool isNestedCapturedVar = false;
541705318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian      if (block)
541805318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian        for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
541905318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian             ce = block->capture_end(); ci != ce; ++ci) {
542005318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian          const VarDecl *variable = ci->getVariable();
542105318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian          if (variable == ND && ci->isNested()) {
542205318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian            assert (ci->isByRef() &&
542305318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian                    "SynthBlockInitExpr - captured block variable is not byref");
542405318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian            isNestedCapturedVar = true;
542505318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian            break;
542605318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian          }
542705318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian        }
542805318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian      // captured nested byref variable has its address passed. Do not take
542905318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian      // its address again.
543005318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian      if (!isNestedCapturedVar)
543105318d835e8beb16ac6bdd2c0db0ab6a922f35cfFariborz Jahanian          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5432f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                     Context->getPointerType(Exp->getType()),
5433f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                     VK_RValue, OK_Ordinary, SourceLocation());
5434a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
54351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      InitExprs.push_back(Exp);
5436fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    }
543701aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff  }
5438ff1278809e62d1da22da171752cc5f07734bcf0cFariborz Jahanian  if (ImportedBlockDecls.size()) {
5439ff1278809e62d1da22da171752cc5f07734bcf0cFariborz Jahanian    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5440ff1278809e62d1da22da171752cc5f07734bcf0cFariborz Jahanian    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
544101aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff    unsigned IntSize =
544201aec11c8cace2b9b22531627970d8bbdbac0c1cSteve Naroff      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
54439996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
54449996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis                                           Context->IntTy, SourceLocation());
5445ff1278809e62d1da22da171752cc5f07734bcf0cFariborz Jahanian    InitExprs.push_back(FlagExp);
5446fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5447668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek  NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5448f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                                  FType, VK_LValue, SourceLocation());
54492de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall  NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
54501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                             Context->getPointerType(NewRep->getType()),
5451f89e55ab1bfb3ea997f8b02997c611a02254eb2dJohn McCall                             VK_RValue, OK_Ordinary, SourceLocation());
5452a5bbc50b1e1b27008a79c11a6c6c33e51d8a9cc9John McCall  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
54539d125033a9853f3b572a4c9e2f9e2d4e5e346973John McCall                                    NewRep);
5454fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  BlockDeclRefs.clear();
5455fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  BlockByRefDecls.clear();
5456bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian  BlockByRefDeclsPtrSet.clear();
5457fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  BlockByCopyDecls.clear();
5458bab71685568085b635f077ee5720d22dffab84beFariborz Jahanian  BlockByCopyDeclsPtrSet.clear();
5459fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  ImportedBlockDecls.clear();
5460fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  return NewRep;
5461fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
5462fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
546342f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanianbool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
546442f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian  if (const ObjCForCollectionStmt * CS =
546542f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian      dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
546642f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian        return CS->getElement() == DS;
546742f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian  return false;
546842f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian}
546942f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian
5470fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff//===----------------------------------------------------------------------===//
5471fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff// Function Body / Expression rewriting
5472fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff//===----------------------------------------------------------------------===//
5473fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5474c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5475c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5476c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5477c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5478c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// Since the rewriter isn't capable of rewriting rewritten code, it's important
5479c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff// we get this right.
5480c77a636688e188af7e7a9a05829e542adb48e880Steve Naroffvoid RewriteObjC::CollectPropertySetters(Stmt *S) {
5481c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  // Perform a bottom up traversal of all children.
54827502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
5483c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    if (*CI)
5484c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      CollectPropertySetters(*CI);
5485c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff
5486c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5487c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    if (BinOp->isAssignmentOp()) {
548812f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall      if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
548912f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall        PropSetters[BinOp->getLHS()] = BinOp;
5490c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    }
5491c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff  }
5492c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff}
5493c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff
5494fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve NaroffStmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
54951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5496fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      isa<DoStmt>(S) || isa<ForStmt>(S))
5497fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    Stmts.push_back(S);
5498fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  else if (isa<ObjCForCollectionStmt>(S)) {
5499fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    Stmts.push_back(S);
55004824fcdf37139efa57466a2a5753dd6e5e792ef8Chris Lattner    ObjCBcLabelNo.push_back(++BcLabelCount);
5501fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
55021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5503fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  SourceRange OrigStmtRange = S->getSourceRange();
55041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5505fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Perform a bottom up rewrite of all children.
55067502c1d3ce8bb97bcc4f7bebef507040bd93b26fJohn McCall  for (Stmt::child_range CI = S->children(); CI; ++CI)
5507fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    if (*CI) {
55082b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      Stmt *newStmt;
55092b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      Stmt *S = (*CI);
55102b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
55112b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        Expr *OldBase = IvarRefExpr->getBase();
55122b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        bool replaced = false;
55132b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
55142b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        if (replaced) {
55152b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian          if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
55162b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian            ReplaceStmt(OldBase, IRE->getBase());
55172b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian          else
55182b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian            ReplaceStmt(S, newStmt);
55192b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        }
55202b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      }
55212b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian      else
55222b9b0b2c9a7137f46b7cc6a02ca9608f2fcc868dFariborz Jahanian        newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
55231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      if (newStmt)
5524fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff        *CI = newStmt;
552590fe4bc75d7fe0a68fd858b278221101787320daFariborz Jahanian      // If dealing with an assignment with LHS being a property reference
552690fe4bc75d7fe0a68fd858b278221101787320daFariborz Jahanian      // expression, the entire assignment tree is rewritten into a property
552790fe4bc75d7fe0a68fd858b278221101787320daFariborz Jahanian      // setter messaging. This involvs the RHS too. Do not attempt to rewrite
552890fe4bc75d7fe0a68fd858b278221101787320daFariborz Jahanian      // RHS again.
55298537f7b49402bddeac95893eb711a3912aef3552Fariborz Jahanian      if (Expr *Exp = dyn_cast<Expr>(S))
553012f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall        if (isa<ObjCPropertyRefExpr>(Exp)) {
55318537f7b49402bddeac95893eb711a3912aef3552Fariborz Jahanian          if (PropSetters[Exp]) {
55328537f7b49402bddeac95893eb711a3912aef3552Fariborz Jahanian            ++CI;
55338537f7b49402bddeac95893eb711a3912aef3552Fariborz Jahanian            continue;
55348537f7b49402bddeac95893eb711a3912aef3552Fariborz Jahanian          }
553590fe4bc75d7fe0a68fd858b278221101787320daFariborz Jahanian        }
55367e7492442f32e3abbe246f6bb35568b044c1188bNick Lewycky    }
55371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5538fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
55395e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
554072952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
554172952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian    InnerContexts.insert(BE->getBlockDecl());
55426cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    ImportedLocalExternalDecls.clear();
55435e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    GetInnerBlockDeclRefExprs(BE->getBody(),
554472952fc11f80c975492a2a1e0f6e3601c5252e0aFariborz Jahanian                              InnerBlockDeclRefs, InnerContexts);
5545fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Rewrite the block body in place.
5546da4ad9fa26b607adde033badcf67396ebc0cfe17Fariborz Jahanian    Stmt *SaveCurrentBody = CurrentBody;
5547da4ad9fa26b607adde033badcf67396ebc0cfe17Fariborz Jahanian    CurrentBody = BE->getBody();
5548da4ad9fa26b607adde033badcf67396ebc0cfe17Fariborz Jahanian    PropParentMap = 0;
5549fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5550da4ad9fa26b607adde033badcf67396ebc0cfe17Fariborz Jahanian    CurrentBody = SaveCurrentBody;
5551da4ad9fa26b607adde033badcf67396ebc0cfe17Fariborz Jahanian    PropParentMap = 0;
55526cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    ImportedLocalExternalDecls.clear();
5553fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Now we snarf the rewritten text and stash it away for later use.
55546a12a14a529a79524e17889046c7098b80a73c49Ted Kremenek    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
55558e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    RewrittenBlockExprs[BE] = Str;
55561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
55575e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
55585e49b2f3e0bbc583076fe8af00dff06bcba06dafFariborz Jahanian
5559fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    //blockTranscribed->dump();
55608e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    ReplaceStmt(S, blockTranscribed);
5561fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return blockTranscribed;
5562fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5563fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Handle specific things.
5564fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5565fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteAtEncode(AtEncode);
55661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
556712f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall  if (isa<ObjCPropertyRefExpr>(S)) {
5568f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5569f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5570f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian
5571f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian    BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
5572c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    if (BinOp) {
5573c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      // Because the rewriter doesn't allow us to rewrite rewritten code,
5574c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      // we need to rewrite the right hand side prior to rewriting the setter.
5575b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      DisableReplaceStmt = true;
5576b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      // Save the source range. Even if we disable the replacement, the
5577b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      // rewritten node will have been inserted into the tree. If the synthesized
5578b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      // node is at the 'end', the rewriter will fail. Consider this:
55791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      //    self.errorHandler = handler ? handler :
5580b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      //              ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5581b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      SourceRange SrcRange = BinOp->getSourceRange();
5582c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
5583f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian      // Need to rewrite the ivar access expression if need be.
5584f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian      if (isa<ObjCIvarRefExpr>(newStmt)) {
5585f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian        bool replaced = false;
5586f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian        newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5587f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian      }
5588f2c6fa4eca6e4d3b2a005416746a47e85690f3a7Fariborz Jahanian
5589b619d957b020744bb6bfdd1cef8169d8042df43eSteve Naroff      DisableReplaceStmt = false;
55904c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
55914c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
55924c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // we changed the RHS of BinOp, the rewriter would fail (since it needs
55934c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // to see the original expression). Consider this example:
55944c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
55954c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // Foo *obj1, *obj2;
55964c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
55974c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // obj1.i = [obj2 rrrr];
55984c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
55994c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // 'BinOp' for the previous expression looks like:
56004c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
56014c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // (BinaryOperator 0x231ccf0 'int' '='
56024c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //   (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
56034c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //     (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
56044c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //   (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
56054c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //     (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
56064c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
56074c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // 'newStmt' represents the rewritten message expression. For example:
56084c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
56094c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // (CallExpr 0x231d300 'id':'struct objc_object *'
56104c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //   (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
56114c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //     (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
56124c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //       (CStyleCastExpr 0x231d220 'void *'
56134c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //         (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
56144c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
5615f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian      // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
56164c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // can be used as the setter argument. ReplaceStmt() will still 'see'
56174c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // the original RHS (since we haven't altered BinOp).
56184c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
56191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // This implies the Rewrite* routines can no longer delete the original
56204c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      // node. As a result, we now leak the original AST nodes.
56214c3580e5f9d1804fa08fecca76ad5089bc9965feSteve Naroff      //
5622f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian      return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
5623c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff    } else {
5624f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian      return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
562515f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff    }
562615f081de2c8ac7deadf5d938b458b20732230cd9Steve Naroff  }
5627f2ad2c92720f0e25c032188783a1d6374155f03aFariborz Jahanian
5628fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5629fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteAtSelector(AtSelector);
56301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5631fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5632fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteObjCStringLiteral(AtString);
56331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5634fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5635c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff#if 0
5636fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Before we rewrite it, put the original message expression in a comment.
5637fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    SourceLocation startLoc = MessExpr->getLocStart();
5638fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    SourceLocation endLoc = MessExpr->getLocEnd();
56391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5640fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    const char *startBuf = SM->getCharacterData(startLoc);
5641fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    const char *endBuf = SM->getCharacterData(endLoc);
56421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5643fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    std::string messString;
5644fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    messString += "// ";
5645fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    messString.append(startBuf, endBuf-startBuf+1);
5646fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    messString += "\n";
56471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
56481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // FIXME: Missing definition of
5649fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // InsertText(clang::SourceLocation, char const*, unsigned int).
5650fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // InsertText(startLoc, messString.c_str(), messString.size());
5651fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Tried this, but it didn't work either...
5652fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5653c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff#endif
5654fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteMessageExpr(MessExpr);
5655fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
56561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5657fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5658fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteObjCTryStmt(StmtTry);
5659fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5660fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5661fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteObjCSynchronizedStmt(StmtTry);
5662fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5663fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5664fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteObjCThrowStmt(StmtThrow);
56651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5666fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5667fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteObjCProtocolExpr(ProtocolExp);
56681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
56691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (ObjCForCollectionStmt *StmtForCollection =
5670fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff        dyn_cast<ObjCForCollectionStmt>(S))
56711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return RewriteObjCForCollectionStmt(StmtForCollection,
5672fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff                                        OrigStmtRange.getEnd());
5673fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (BreakStmt *StmtBreakStmt =
5674fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      dyn_cast<BreakStmt>(S))
5675fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteBreakStmt(StmtBreakStmt);
5676fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ContinueStmt *StmtContinueStmt =
5677fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      dyn_cast<ContinueStmt>(S))
5678fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return RewriteContinueStmt(StmtContinueStmt);
56791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
56801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5681fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // and cast exprs.
5682fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5683fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // FIXME: What we're doing here is modifying the type-specifier that
5684fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // precedes the first Decl.  In the future the DeclGroup should have
56851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // a separate type-specifier that we can rewrite.
56863d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    // NOTE: We need to avoid rewriting the DeclStmt if it is within
56873d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    // the context of an ObjCForCollectionStmt. For example:
56883d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    //   NSArray *someArray;
56893d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    //   for (id <FooProtocol> index in someArray) ;
56903d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    // This is because RewriteObjCForCollectionStmt() does textual rewriting
56913d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    // and it depends on the original text locations/positions.
569242f1e658765b0b3e069f52726da23517a466c582Fariborz Jahanian    if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
56933d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
56941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5695fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Blocks rewrite rules.
5696fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5697fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff         DI != DE; ++DI) {
56984afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor      Decl *SD = *DI;
5699fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
570001f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff        if (isTopLevelBlockPointerType(ND->getType()))
5701fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff          RewriteBlockPointerDecl(ND);
57021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        else if (ND->getType()->isFunctionPointerType())
5703fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff          CheckFunctionPointerDecl(ND->getType(), ND);
57044c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian        if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5705a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian          if (VD->hasAttr<BlocksAttr>()) {
5706a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian            static unsigned uniqueByrefDeclCount = 0;
5707a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian            assert(!BlockByRefDeclNo.count(ND) &&
5708a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5709a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
571052b08f2c8a65c059cb2123fa0fd6317b829416deFariborz Jahanian            RewriteByRefVar(VD);
5711a73165e47aefbea60312d284343660c9c962c9c3Fariborz Jahanian          }
57124c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian          else
57134c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian            RewriteTypeOfDecl(VD);
57144c863ef92c2b74572090da245c87e1487b0b596cFariborz Jahanian        }
5715fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      }
5716fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
571701f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5718fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff          RewriteBlockPointerDecl(TD);
57191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        else if (TD->getUnderlyingType()->isFunctionPointerType())
5720fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5721fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      }
5722fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    }
5723fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
57241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5725fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5726fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    RewriteObjCQualifiedInterfaceTypes(CE);
57271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
57281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5729fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      isa<DoStmt>(S) || isa<ForStmt>(S)) {
5730fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    assert(!Stmts.empty() && "Statement stack is empty");
57311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
57321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5733fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff            && "Statement stack mismatch");
5734fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    Stmts.pop_back();
5735fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5736fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Handle blocks rewriting.
5737fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5738fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    if (BDRE->isByRef())
5739621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      return RewriteBlockDeclRefExpr(BDRE);
5740fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5741f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5742f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    ValueDecl *VD = DRE->getDecl();
5743f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian    if (VD->hasAttr<BlocksAttr>())
5744f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian      return RewriteBlockDeclRefExpr(DRE);
57456cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian    if (HasLocalVariableExternalStorage(VD))
57466cb6eb4c792b504ad652d9230640656852e18ee9Fariborz Jahanian      return RewriteLocalVariableExternalStorage(DRE);
5747f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian  }
5748f381cc90d6cfa0966ddf791db57a6ed6c2462b5dFariborz Jahanian
5749fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5750aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff    if (CE->getCallee()->getType()->isBlockPointerType()) {
57518a9e170efd32855377bc7fc5f7ea431ec4f8802eFariborz Jahanian      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5752aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff      ReplaceStmt(S, BlockCall);
5753aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff      return BlockCall;
5754aa4d5ae6c450fdbe207cdb12373fc026376ece42Steve Naroff    }
5755fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5756b2f9e516327310d95840d442416084508f80c183Steve Naroff  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5757fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    RewriteCastExpr(CE);
5758fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5759fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff#if 0
5760fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5761906082edf2aea1c6de2926f93a8d7121e49d2a54Sebastian Redl    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5762906082edf2aea1c6de2926f93a8d7121e49d2a54Sebastian Redl                                                   ICE->getSubExpr(),
5763906082edf2aea1c6de2926f93a8d7121e49d2a54Sebastian Redl                                                   SourceLocation());
5764fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Get the new text.
5765fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    std::string SStr;
5766fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    llvm::raw_string_ostream Buf(SStr);
57673a9eb44f2906e44ca29ae2d9df56fb9824ef7d05Eli Friedman    Replacement->printPretty(Buf, *Context);
5768fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    const std::string &Str = Buf.str();
5769fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5770fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    printf("CAST = %s\n", &Str[0]);
5771fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5772fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    delete S;
5773fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return Replacement;
5774fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5775fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff#endif
5776fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Return this stmt unmodified.
5777fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  return S;
5778fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
5779fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
57803d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroffvoid RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
57813d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff  for (RecordDecl::field_iterator i = RD->field_begin(),
57823d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff                                  e = RD->field_end(); i != e; ++i) {
57833d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    FieldDecl *FD = *i;
57843d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    if (isTopLevelBlockPointerType(FD->getType()))
57853d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      RewriteBlockPointerDecl(FD);
57863d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    if (FD->getType()->isObjCQualifiedIdType() ||
57873d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff        FD->getType()->isObjCQualifiedInterfaceType())
57883d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      RewriteObjCQualifiedInterfaceTypes(FD);
57893d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff  }
57903d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff}
57913d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff
5792fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5793fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff/// main file of the input.
5794fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroffvoid RewriteObjC::HandleDeclInMainFile(Decl *D) {
5795fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5796cb73530987a22a6877039b9404b29aba3bf226e0Steve Naroff    if (FD->isOverloadedOperator())
5797cb73530987a22a6877039b9404b29aba3bf226e0Steve Naroff      return;
57981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5799fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // Since function prototypes don't have ParmDecl's, we check the function
5800fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // prototype. This enables us to rewrite function declarations and
5801fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    // definitions using the same code.
580272564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5803fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5804d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl    // FIXME: If this should support Obj-C++, support CXXTryStmt
58055f1bfc10a12d9759444eb433f52a85d2e0058967Argyrios Kyrtzidis    if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5806fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CurFunctionDef = FD;
5807abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian      CurFunctionDeclToDeclareForBlock = FD;
5808c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      CollectPropertySetters(Body);
58098599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = Body;
5810eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek      Body =
5811eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5812eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek      FD->setBody(Body);
58138599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = 0;
58148599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      if (PropParentMap) {
58158599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        delete PropParentMap;
58168599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        PropParentMap = 0;
58178599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      }
5818fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      // This synthesizes and inserts the block "impl" struct, invoke function,
5819fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      // and any copy/dispose helper functions.
5820fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      InsertBlockLiteralsWithinFunction(FD);
5821fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CurFunctionDef = 0;
5822abfd83e74ca8a7553e375dd4631d2570f33648b4Fariborz Jahanian      CurFunctionDeclToDeclareForBlock = 0;
58231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
5824fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
5825fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5826fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
58276fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (CompoundStmt *Body = MD->getCompoundBody()) {
5828fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CurMethodDef = MD;
5829c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      CollectPropertySetters(Body);
58308599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = Body;
5831eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek      Body =
5832eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5833eaab20669b6a9910a5deb0110fdd8f7581d86a36Ted Kremenek      MD->setBody(Body);
58348599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = 0;
58358599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      if (PropParentMap) {
58368599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        delete PropParentMap;
58378599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        PropParentMap = 0;
58388599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      }
5839fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      InsertBlockLiteralsWithinMethod(MD);
5840fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CurMethodDef = 0;
5841fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    }
5842fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5843fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5844fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    ClassImplementation.push_back(CI);
5845fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5846fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    CategoryImplementation.push_back(CI);
5847fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5848fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    RewriteForwardClassDecl(CD);
5849fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5850fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    RewriteObjCQualifiedInterfaceTypes(VD);
585101f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff    if (isTopLevelBlockPointerType(VD->getType()))
5852fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      RewriteBlockPointerDecl(VD);
58538e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    else if (VD->getType()->isFunctionPointerType()) {
5854fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CheckFunctionPointerDecl(VD->getType(), VD);
5855fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      if (VD->getInit()) {
5856b2f9e516327310d95840d442416084508f80c183Steve Naroff        if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5857fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff          RewriteCastExpr(CE);
5858fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff        }
5859fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      }
58603d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    } else if (VD->getType()->isRecordType()) {
58613d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
58623d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      if (RD->isDefinition())
58633d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff        RewriteRecordBody(RD);
5864fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    }
58658e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    if (VD->getInit()) {
58668e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff      GlobalVarDecl = VD;
5867c77a636688e188af7e7a9a05829e542adb48e880Steve Naroff      CollectPropertySetters(VD->getInit());
58688599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = VD->getInit();
58698e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff      RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
58708599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      CurrentBody = 0;
58718599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      if (PropParentMap) {
58728599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        delete PropParentMap;
58738599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff        PropParentMap = 0;
58748599e7a394e7ed44a32dfe64733125e095e3f28cSteve Naroff      }
58751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
58764087f27e5416c799bcb6be072f905be752acb61cDaniel Dunbar                              VD->getName());
58778e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff      GlobalVarDecl = 0;
58788e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff
58798e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff      // This is needed for blocks.
5880b2f9e516327310d95840d442416084508f80c183Steve Naroff      if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
58818e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff        RewriteCastExpr(CE);
58828e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff      }
58838e2f57ad06d73a6c2cacf0167a3b9e244439a9f9Steve Naroff    }
5884fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
5885fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5886fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
588701f2ffacc427de6bef08fe138e8cae82ba1b30a3Steve Naroff    if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5888fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      RewriteBlockPointerDecl(TD);
58891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    else if (TD->getUnderlyingType()->isFunctionPointerType())
5890fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5891fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
5892fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5893fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
58943d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff    if (RD->isDefinition())
58953d7e7865bd0863fcf36aee14d8911b785dde57ddSteve Naroff      RewriteRecordBody(RD);
5896fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
5897fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5898fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Nothing yet.
5899fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
5900fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff
5901dacbc5d46aaeea817742b8c76c987b87d2490c85Chris Lattnervoid RewriteObjC::HandleTranslationUnit(ASTContext &C) {
5902fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  if (Diags.hasErrorOccurred())
5903fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    return;
59041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5905fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  RewriteInclude();
59061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5907621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Here's a great place to add any extra declarations that may be needed.
5908621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  // Write out meta data for each @protocol(<expr>).
59091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5910621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff       E = ProtocolExprDecls.end(); I != E; ++I)
5911621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff    RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5912621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
5913d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
59140aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff  if (ClassImplementation.size() || CategoryImplementation.size())
59150aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    RewriteImplementations();
5916621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff
5917fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5918fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  // we are done.
59191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (const RewriteBuffer *RewriteBuf =
5920fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff      Rewrite.getRewriteBufferFor(MainFileID)) {
5921fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    //printf("Changed:\n");
5922fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5923fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  } else {
5924d999b3736ce2646ae0711416b421d906298764dbBenjamin Kramer    llvm::errs() << "No changes\n";
5925fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  }
5926ace6625f236af4fc81d87d63d79d7819944524dcSteve Naroff
5927621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff  if (ClassImplementation.size() || CategoryImplementation.size() ||
5928621edce9cd7d4e06979daf911cc306350619f33bSteve Naroff      ProtocolExprDecls.size()) {
59290aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    // Rewrite Objective-c meta data*
59300aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    std::string ResultStr;
59310aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    SynthesizeMetaDataIntoBuffer(ResultStr);
59320aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    // Emit metadata.
59330aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff    *OutFile << ResultStr;
59340aab796da21bfc45381d3ce76c795710cb97acfcSteve Naroff  }
5935fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff  OutFile->flush();
5936fa15fd9db405f2d0a9811e94a671f7d7bc282385Steve Naroff}
5937