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