RewriteObjC.cpp revision 90fe4bc75d7fe0a68fd858b278221101787320da
1//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34  class RewriteObjC : public ASTConsumer {
35    enum {
36      BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
37                                        block, ... */
38      BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
39      BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
40                                        __block variable */
41      BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
42                                        helpers */
43      BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
44                                        support routines */
45      BLOCK_BYREF_CURRENT_MAX = 256
46    };
47
48    enum {
49      BLOCK_NEEDS_FREE =        (1 << 24),
50      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  if (T->isArrayType()) {
2113    QualType ElemTy = Context->getBaseElementType(T);
2114    return needToScanForQualifiers(ElemTy);
2115  }
2116  return false;
2117}
2118
2119void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2120  QualType Type = E->getType();
2121  if (needToScanForQualifiers(Type)) {
2122    SourceLocation Loc, EndLoc;
2123
2124    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2125      Loc = ECE->getLParenLoc();
2126      EndLoc = ECE->getRParenLoc();
2127    } else {
2128      Loc = E->getLocStart();
2129      EndLoc = E->getLocEnd();
2130    }
2131    // This will defend against trying to rewrite synthesized expressions.
2132    if (Loc.isInvalid() || EndLoc.isInvalid())
2133      return;
2134
2135    const char *startBuf = SM->getCharacterData(Loc);
2136    const char *endBuf = SM->getCharacterData(EndLoc);
2137    const char *startRef = 0, *endRef = 0;
2138    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2139      // Get the locations of the startRef, endRef.
2140      SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2141      SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2142      // Comment out the protocol references.
2143      InsertText(LessLoc, "/*");
2144      InsertText(GreaterLoc, "*/");
2145    }
2146  }
2147}
2148
2149void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2150  SourceLocation Loc;
2151  QualType Type;
2152  const FunctionProtoType *proto = 0;
2153  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2154    Loc = VD->getLocation();
2155    Type = VD->getType();
2156  }
2157  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2158    Loc = FD->getLocation();
2159    // Check for ObjC 'id' and class types that have been adorned with protocol
2160    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2161    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2162    assert(funcType && "missing function type");
2163    proto = dyn_cast<FunctionProtoType>(funcType);
2164    if (!proto)
2165      return;
2166    Type = proto->getResultType();
2167  }
2168  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2169    Loc = FD->getLocation();
2170    Type = FD->getType();
2171  }
2172  else
2173    return;
2174
2175  if (needToScanForQualifiers(Type)) {
2176    // Since types are unique, we need to scan the buffer.
2177
2178    const char *endBuf = SM->getCharacterData(Loc);
2179    const char *startBuf = endBuf;
2180    while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2181      startBuf--; // scan backward (from the decl location) for return type.
2182    const char *startRef = 0, *endRef = 0;
2183    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184      // Get the locations of the startRef, endRef.
2185      SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2186      SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2187      // Comment out the protocol references.
2188      InsertText(LessLoc, "/*");
2189      InsertText(GreaterLoc, "*/");
2190    }
2191  }
2192  if (!proto)
2193      return; // most likely, was a variable
2194  // Now check arguments.
2195  const char *startBuf = SM->getCharacterData(Loc);
2196  const char *startFuncBuf = startBuf;
2197  for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2198    if (needToScanForQualifiers(proto->getArgType(i))) {
2199      // Since types are unique, we need to scan the buffer.
2200
2201      const char *endBuf = startBuf;
2202      // scan forward (from the decl location) for argument types.
2203      scanToNextArgument(endBuf);
2204      const char *startRef = 0, *endRef = 0;
2205      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206        // Get the locations of the startRef, endRef.
2207        SourceLocation LessLoc =
2208          Loc.getFileLocWithOffset(startRef-startFuncBuf);
2209        SourceLocation GreaterLoc =
2210          Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
2211        // Comment out the protocol references.
2212        InsertText(LessLoc, "/*");
2213        InsertText(GreaterLoc, "*/");
2214      }
2215      startBuf = ++endBuf;
2216    }
2217    else {
2218      // If the function name is derived from a macro expansion, then the
2219      // argument buffer will not follow the name. Need to speak with Chris.
2220      while (*startBuf && *startBuf != ')' && *startBuf != ',')
2221        startBuf++; // scan forward (from the decl location) for argument types.
2222      startBuf++;
2223    }
2224  }
2225}
2226
2227void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2228  QualType QT = ND->getType();
2229  const Type* TypePtr = QT->getAs<Type>();
2230  if (!isa<TypeOfExprType>(TypePtr))
2231    return;
2232  while (isa<TypeOfExprType>(TypePtr)) {
2233    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2234    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2235    TypePtr = QT->getAs<Type>();
2236  }
2237  // FIXME. This will not work for multiple declarators; as in:
2238  // __typeof__(a) b,c,d;
2239  std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
2240  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2241  const char *startBuf = SM->getCharacterData(DeclLoc);
2242  if (ND->getInit()) {
2243    std::string Name(ND->getNameAsString());
2244    TypeAsString += " " + Name + " = ";
2245    Expr *E = ND->getInit();
2246    SourceLocation startLoc;
2247    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2248      startLoc = ECE->getLParenLoc();
2249    else
2250      startLoc = E->getLocStart();
2251    startLoc = SM->getInstantiationLoc(startLoc);
2252    const char *endBuf = SM->getCharacterData(startLoc);
2253    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2254  }
2255  else {
2256    SourceLocation X = ND->getLocEnd();
2257    X = SM->getInstantiationLoc(X);
2258    const char *endBuf = SM->getCharacterData(X);
2259    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2260  }
2261}
2262
2263// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2264void RewriteObjC::SynthSelGetUidFunctionDecl() {
2265  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2266  llvm::SmallVector<QualType, 16> ArgTys;
2267  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2268  QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
2269                                                  &ArgTys[0], ArgTys.size(),
2270                                                  false /*isVariadic*/, 0,
2271                                                  false, false, 0, 0,
2272                                                  FunctionType::ExtInfo());
2273  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2274                                           SourceLocation(),
2275                                           SelGetUidIdent, getFuncType, 0,
2276                                           SC_Extern,
2277                                           SC_None, false);
2278}
2279
2280void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2281  // declared in <objc/objc.h>
2282  if (FD->getIdentifier() &&
2283      FD->getName() == "sel_registerName") {
2284    SelGetUidFunctionDecl = FD;
2285    return;
2286  }
2287  RewriteObjCQualifiedInterfaceTypes(FD);
2288}
2289
2290void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2291  std::string TypeString(Type.getAsString(Context->PrintingPolicy));
2292  const char *argPtr = TypeString.c_str();
2293  if (!strchr(argPtr, '^')) {
2294    Str += TypeString;
2295    return;
2296  }
2297  while (*argPtr) {
2298    Str += (*argPtr == '^' ? '*' : *argPtr);
2299    argPtr++;
2300  }
2301}
2302
2303// FIXME. Consolidate this routine with RewriteBlockPointerType.
2304void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2305                                                  ValueDecl *VD) {
2306  QualType Type = VD->getType();
2307  std::string TypeString(Type.getAsString(Context->PrintingPolicy));
2308  const char *argPtr = TypeString.c_str();
2309  int paren = 0;
2310  while (*argPtr) {
2311    switch (*argPtr) {
2312      case '(':
2313        Str += *argPtr;
2314        paren++;
2315        break;
2316      case ')':
2317        Str += *argPtr;
2318        paren--;
2319        break;
2320      case '^':
2321        Str += '*';
2322        if (paren == 1)
2323          Str += VD->getNameAsString();
2324        break;
2325      default:
2326        Str += *argPtr;
2327        break;
2328    }
2329    argPtr++;
2330  }
2331}
2332
2333
2334void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2335  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2336  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2337  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2338  if (!proto)
2339    return;
2340  QualType Type = proto->getResultType();
2341  std::string FdStr = Type.getAsString(Context->PrintingPolicy);
2342  FdStr += " ";
2343  FdStr += FD->getName();
2344  FdStr +=  "(";
2345  unsigned numArgs = proto->getNumArgs();
2346  for (unsigned i = 0; i < numArgs; i++) {
2347    QualType ArgType = proto->getArgType(i);
2348    RewriteBlockPointerType(FdStr, ArgType);
2349    if (i+1 < numArgs)
2350      FdStr += ", ";
2351  }
2352  FdStr +=  ");\n";
2353  InsertText(FunLocStart, FdStr);
2354  CurFunctionDeclToDeclareForBlock = 0;
2355}
2356
2357// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2358void RewriteObjC::SynthSuperContructorFunctionDecl() {
2359  if (SuperContructorFunctionDecl)
2360    return;
2361  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2362  llvm::SmallVector<QualType, 16> ArgTys;
2363  QualType argT = Context->getObjCIdType();
2364  assert(!argT.isNull() && "Can't find 'id' type");
2365  ArgTys.push_back(argT);
2366  ArgTys.push_back(argT);
2367  QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2368                                                  &ArgTys[0], ArgTys.size(),
2369                                                  false, 0,
2370                                                  false, false, 0, 0,
2371                                                  FunctionType::ExtInfo());
2372  SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2373                                         SourceLocation(),
2374                                         msgSendIdent, msgSendType, 0,
2375                                         SC_Extern,
2376                                         SC_None, false);
2377}
2378
2379// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2380void RewriteObjC::SynthMsgSendFunctionDecl() {
2381  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2382  llvm::SmallVector<QualType, 16> ArgTys;
2383  QualType argT = Context->getObjCIdType();
2384  assert(!argT.isNull() && "Can't find 'id' type");
2385  ArgTys.push_back(argT);
2386  argT = Context->getObjCSelType();
2387  assert(!argT.isNull() && "Can't find 'SEL' type");
2388  ArgTys.push_back(argT);
2389  QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2390                                                  &ArgTys[0], ArgTys.size(),
2391                                                  true /*isVariadic*/, 0,
2392                                                  false, false, 0, 0,
2393                                                  FunctionType::ExtInfo());
2394  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2395                                         SourceLocation(),
2396                                         msgSendIdent, msgSendType, 0,
2397                                         SC_Extern,
2398                                         SC_None, false);
2399}
2400
2401// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2402void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2403  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2404  llvm::SmallVector<QualType, 16> ArgTys;
2405  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2406                                      SourceLocation(),
2407                                      &Context->Idents.get("objc_super"));
2408  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2409  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2410  ArgTys.push_back(argT);
2411  argT = Context->getObjCSelType();
2412  assert(!argT.isNull() && "Can't find 'SEL' type");
2413  ArgTys.push_back(argT);
2414  QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2415                                                  &ArgTys[0], ArgTys.size(),
2416                                                  true /*isVariadic*/, 0,
2417                                                  false, false, 0, 0,
2418                                                  FunctionType::ExtInfo());
2419  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2420                                              SourceLocation(),
2421                                              msgSendIdent, msgSendType, 0,
2422                                              SC_Extern,
2423                                              SC_None, false);
2424}
2425
2426// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2427void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2428  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2429  llvm::SmallVector<QualType, 16> ArgTys;
2430  QualType argT = Context->getObjCIdType();
2431  assert(!argT.isNull() && "Can't find 'id' type");
2432  ArgTys.push_back(argT);
2433  argT = Context->getObjCSelType();
2434  assert(!argT.isNull() && "Can't find 'SEL' type");
2435  ArgTys.push_back(argT);
2436  QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2437                                                  &ArgTys[0], ArgTys.size(),
2438                                                  true /*isVariadic*/, 0,
2439                                                  false, false, 0, 0,
2440                                                  FunctionType::ExtInfo());
2441  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2442                                         SourceLocation(),
2443                                         msgSendIdent, msgSendType, 0,
2444                                         SC_Extern,
2445                                         SC_None, false);
2446}
2447
2448// SynthMsgSendSuperStretFunctionDecl -
2449// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2450void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2451  IdentifierInfo *msgSendIdent =
2452    &Context->Idents.get("objc_msgSendSuper_stret");
2453  llvm::SmallVector<QualType, 16> ArgTys;
2454  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2455                                      SourceLocation(),
2456                                      &Context->Idents.get("objc_super"));
2457  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2458  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2459  ArgTys.push_back(argT);
2460  argT = Context->getObjCSelType();
2461  assert(!argT.isNull() && "Can't find 'SEL' type");
2462  ArgTys.push_back(argT);
2463  QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2464                                                  &ArgTys[0], ArgTys.size(),
2465                                                  true /*isVariadic*/, 0,
2466                                                  false, false, 0, 0,
2467                                                  FunctionType::ExtInfo());
2468  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469                                                       SourceLocation(),
2470                                              msgSendIdent, msgSendType, 0,
2471                                              SC_Extern,
2472                                              SC_None, false);
2473}
2474
2475// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2476void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2477  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2478  llvm::SmallVector<QualType, 16> ArgTys;
2479  QualType argT = Context->getObjCIdType();
2480  assert(!argT.isNull() && "Can't find 'id' type");
2481  ArgTys.push_back(argT);
2482  argT = Context->getObjCSelType();
2483  assert(!argT.isNull() && "Can't find 'SEL' type");
2484  ArgTys.push_back(argT);
2485  QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
2486                                                  &ArgTys[0], ArgTys.size(),
2487                                                  true /*isVariadic*/, 0,
2488                                                  false, false, 0, 0,
2489                                                  FunctionType::ExtInfo());
2490  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2491                                              SourceLocation(),
2492                                              msgSendIdent, msgSendType, 0,
2493                                              SC_Extern,
2494                                              SC_None, false);
2495}
2496
2497// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2498void RewriteObjC::SynthGetClassFunctionDecl() {
2499  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2500  llvm::SmallVector<QualType, 16> ArgTys;
2501  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2502  QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
2503                                                   &ArgTys[0], ArgTys.size(),
2504                                                   false /*isVariadic*/, 0,
2505                                                  false, false, 0, 0,
2506                                                   FunctionType::ExtInfo());
2507  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508                                          SourceLocation(),
2509                                          getClassIdent, getClassType, 0,
2510                                          SC_Extern,
2511                                          SC_None, false);
2512}
2513
2514// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2515void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2516  IdentifierInfo *getSuperClassIdent =
2517    &Context->Idents.get("class_getSuperclass");
2518  llvm::SmallVector<QualType, 16> ArgTys;
2519  ArgTys.push_back(Context->getObjCClassType());
2520  QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2521                                                   &ArgTys[0], ArgTys.size(),
2522                                                   false /*isVariadic*/, 0,
2523                                                   false, false, 0, 0,
2524                                                   FunctionType::ExtInfo());
2525  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2526                                                   SourceLocation(),
2527                                                   getSuperClassIdent,
2528                                                   getClassType, 0,
2529                                                   SC_Extern,
2530                                                   SC_None,
2531                                                   false);
2532}
2533
2534// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
2535void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2536  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2537  llvm::SmallVector<QualType, 16> ArgTys;
2538  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2539  QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
2540                                                   &ArgTys[0], ArgTys.size(),
2541                                                   false /*isVariadic*/, 0,
2542                                                   false, false, 0, 0,
2543                                                   FunctionType::ExtInfo());
2544  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2545                                              SourceLocation(),
2546                                              getClassIdent, getClassType, 0,
2547                                              SC_Extern,
2548                                              SC_None, false);
2549}
2550
2551Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2552  QualType strType = getConstantStringStructType();
2553
2554  std::string S = "__NSConstantStringImpl_";
2555
2556  std::string tmpName = InFileName;
2557  unsigned i;
2558  for (i=0; i < tmpName.length(); i++) {
2559    char c = tmpName.at(i);
2560    // replace any non alphanumeric characters with '_'.
2561    if (!isalpha(c) && (c < '0' || c > '9'))
2562      tmpName[i] = '_';
2563  }
2564  S += tmpName;
2565  S += "_";
2566  S += utostr(NumObjCStringLiterals++);
2567
2568  Preamble += "static __NSConstantStringImpl " + S;
2569  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2570  Preamble += "0x000007c8,"; // utf8_str
2571  // The pretty printer for StringLiteral handles escape characters properly.
2572  std::string prettyBufS;
2573  llvm::raw_string_ostream prettyBuf(prettyBufS);
2574  Exp->getString()->printPretty(prettyBuf, *Context, 0,
2575                                PrintingPolicy(LangOpts));
2576  Preamble += prettyBuf.str();
2577  Preamble += ",";
2578  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2579
2580  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2581                                    &Context->Idents.get(S), strType, 0,
2582                                    SC_Static, SC_None);
2583  DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2584  Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2585                                 Context->getPointerType(DRE->getType()),
2586                                 SourceLocation());
2587  // cast to NSConstantString *
2588  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2589                                            CK_Unknown, Unop);
2590  ReplaceStmt(Exp, cast);
2591  // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2592  return cast;
2593}
2594
2595// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2596QualType RewriteObjC::getSuperStructType() {
2597  if (!SuperStructDecl) {
2598    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2599                                         SourceLocation(),
2600                                         &Context->Idents.get("objc_super"));
2601    QualType FieldTypes[2];
2602
2603    // struct objc_object *receiver;
2604    FieldTypes[0] = Context->getObjCIdType();
2605    // struct objc_class *super;
2606    FieldTypes[1] = Context->getObjCClassType();
2607
2608    // Create fields
2609    for (unsigned i = 0; i < 2; ++i) {
2610      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2611                                                 SourceLocation(), 0,
2612                                                 FieldTypes[i], 0,
2613                                                 /*BitWidth=*/0,
2614                                                 /*Mutable=*/false));
2615    }
2616
2617    SuperStructDecl->completeDefinition();
2618  }
2619  return Context->getTagDeclType(SuperStructDecl);
2620}
2621
2622QualType RewriteObjC::getConstantStringStructType() {
2623  if (!ConstantStringDecl) {
2624    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2625                                            SourceLocation(),
2626                         &Context->Idents.get("__NSConstantStringImpl"));
2627    QualType FieldTypes[4];
2628
2629    // struct objc_object *receiver;
2630    FieldTypes[0] = Context->getObjCIdType();
2631    // int flags;
2632    FieldTypes[1] = Context->IntTy;
2633    // char *str;
2634    FieldTypes[2] = Context->getPointerType(Context->CharTy);
2635    // long length;
2636    FieldTypes[3] = Context->LongTy;
2637
2638    // Create fields
2639    for (unsigned i = 0; i < 4; ++i) {
2640      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2641                                                    ConstantStringDecl,
2642                                                    SourceLocation(), 0,
2643                                                    FieldTypes[i], 0,
2644                                                    /*BitWidth=*/0,
2645                                                    /*Mutable=*/true));
2646    }
2647
2648    ConstantStringDecl->completeDefinition();
2649  }
2650  return Context->getTagDeclType(ConstantStringDecl);
2651}
2652
2653Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2654                                    SourceLocation StartLoc,
2655                                    SourceLocation EndLoc) {
2656  if (!SelGetUidFunctionDecl)
2657    SynthSelGetUidFunctionDecl();
2658  if (!MsgSendFunctionDecl)
2659    SynthMsgSendFunctionDecl();
2660  if (!MsgSendSuperFunctionDecl)
2661    SynthMsgSendSuperFunctionDecl();
2662  if (!MsgSendStretFunctionDecl)
2663    SynthMsgSendStretFunctionDecl();
2664  if (!MsgSendSuperStretFunctionDecl)
2665    SynthMsgSendSuperStretFunctionDecl();
2666  if (!MsgSendFpretFunctionDecl)
2667    SynthMsgSendFpretFunctionDecl();
2668  if (!GetClassFunctionDecl)
2669    SynthGetClassFunctionDecl();
2670  if (!GetSuperClassFunctionDecl)
2671    SynthGetSuperClassFunctionDecl();
2672  if (!GetMetaClassFunctionDecl)
2673    SynthGetMetaClassFunctionDecl();
2674
2675  // default to objc_msgSend().
2676  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2677  // May need to use objc_msgSend_stret() as well.
2678  FunctionDecl *MsgSendStretFlavor = 0;
2679  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2680    QualType resultType = mDecl->getResultType();
2681    if (resultType->isRecordType())
2682      MsgSendStretFlavor = MsgSendStretFunctionDecl;
2683    else if (resultType->isRealFloatingType())
2684      MsgSendFlavor = MsgSendFpretFunctionDecl;
2685  }
2686
2687  // Synthesize a call to objc_msgSend().
2688  llvm::SmallVector<Expr*, 8> MsgExprs;
2689  switch (Exp->getReceiverKind()) {
2690  case ObjCMessageExpr::SuperClass: {
2691    MsgSendFlavor = MsgSendSuperFunctionDecl;
2692    if (MsgSendStretFlavor)
2693      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2694    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2695
2696    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2697
2698    llvm::SmallVector<Expr*, 4> InitExprs;
2699
2700    // set the receiver to self, the first argument to all methods.
2701    InitExprs.push_back(
2702      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2703                               CK_Unknown,
2704                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2705                                   Context->getObjCIdType(),
2706                                   SourceLocation()))
2707                        ); // set the 'receiver'.
2708
2709    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2710    llvm::SmallVector<Expr*, 8> ClsExprs;
2711    QualType argType = Context->getPointerType(Context->CharTy);
2712    ClsExprs.push_back(StringLiteral::Create(*Context,
2713                                   ClassDecl->getIdentifier()->getNameStart(),
2714                                   ClassDecl->getIdentifier()->getLength(),
2715                                   false, argType, SourceLocation()));
2716    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2717                                                 &ClsExprs[0],
2718                                                 ClsExprs.size(),
2719                                                 StartLoc,
2720                                                 EndLoc);
2721    // (Class)objc_getClass("CurrentClass")
2722    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2723                                             Context->getObjCClassType(),
2724                                             CK_Unknown, Cls);
2725    ClsExprs.clear();
2726    ClsExprs.push_back(ArgExpr);
2727    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2728                                       &ClsExprs[0], ClsExprs.size(),
2729                                       StartLoc, EndLoc);
2730
2731    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2732    // To turn off a warning, type-cast to 'id'
2733    InitExprs.push_back( // set 'super class', using class_getSuperclass().
2734                        NoTypeInfoCStyleCastExpr(Context,
2735                                                 Context->getObjCIdType(),
2736                                                 CK_Unknown, Cls));
2737    // struct objc_super
2738    QualType superType = getSuperStructType();
2739    Expr *SuperRep;
2740
2741    if (LangOpts.Microsoft) {
2742      SynthSuperContructorFunctionDecl();
2743      // Simulate a contructor call...
2744      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2745                                         superType, SourceLocation());
2746      SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2747                                        InitExprs.size(),
2748                                        superType, SourceLocation());
2749      // The code for super is a little tricky to prevent collision with
2750      // the structure definition in the header. The rewriter has it's own
2751      // internal definition (__rw_objc_super) that is uses. This is why
2752      // we need the cast below. For example:
2753      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2754      //
2755      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2756                               Context->getPointerType(SuperRep->getType()),
2757                               SourceLocation());
2758      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2759                                          Context->getPointerType(superType),
2760                                          CK_Unknown, SuperRep);
2761    } else {
2762      // (struct objc_super) { <exprs from above> }
2763      InitListExpr *ILE =
2764        new (Context) InitListExpr(*Context, SourceLocation(),
2765                                   &InitExprs[0], InitExprs.size(),
2766                                   SourceLocation());
2767      TypeSourceInfo *superTInfo
2768        = Context->getTrivialTypeSourceInfo(superType);
2769      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2770                                                   superType, ILE, false);
2771      // struct objc_super *
2772      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2773                               Context->getPointerType(SuperRep->getType()),
2774                               SourceLocation());
2775    }
2776    MsgExprs.push_back(SuperRep);
2777    break;
2778  }
2779
2780  case ObjCMessageExpr::Class: {
2781    llvm::SmallVector<Expr*, 8> ClsExprs;
2782    QualType argType = Context->getPointerType(Context->CharTy);
2783    ObjCInterfaceDecl *Class
2784      = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2785    IdentifierInfo *clsName = Class->getIdentifier();
2786    ClsExprs.push_back(StringLiteral::Create(*Context,
2787                                             clsName->getNameStart(),
2788                                             clsName->getLength(),
2789                                             false, argType,
2790                                             SourceLocation()));
2791    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2792                                                 &ClsExprs[0],
2793                                                 ClsExprs.size(),
2794                                                 StartLoc, EndLoc);
2795    MsgExprs.push_back(Cls);
2796    break;
2797  }
2798
2799  case ObjCMessageExpr::SuperInstance:{
2800    MsgSendFlavor = MsgSendSuperFunctionDecl;
2801    if (MsgSendStretFlavor)
2802      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2803    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2804    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2805    llvm::SmallVector<Expr*, 4> InitExprs;
2806
2807    InitExprs.push_back(
2808      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2809                               CK_Unknown,
2810                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2811                                   Context->getObjCIdType(),
2812                                   SourceLocation()))
2813                        ); // set the 'receiver'.
2814
2815    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2816    llvm::SmallVector<Expr*, 8> ClsExprs;
2817    QualType argType = Context->getPointerType(Context->CharTy);
2818    ClsExprs.push_back(StringLiteral::Create(*Context,
2819                                   ClassDecl->getIdentifier()->getNameStart(),
2820                                   ClassDecl->getIdentifier()->getLength(),
2821                                   false, argType, SourceLocation()));
2822    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2823                                                 &ClsExprs[0],
2824                                                 ClsExprs.size(),
2825                                                 StartLoc, EndLoc);
2826    // (Class)objc_getClass("CurrentClass")
2827    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2828                                                 Context->getObjCClassType(),
2829                                                 CK_Unknown, Cls);
2830    ClsExprs.clear();
2831    ClsExprs.push_back(ArgExpr);
2832    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2833                                       &ClsExprs[0], ClsExprs.size(),
2834                                       StartLoc, EndLoc);
2835
2836    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2837    // To turn off a warning, type-cast to 'id'
2838    InitExprs.push_back(
2839      // set 'super class', using class_getSuperclass().
2840      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2841                               CK_Unknown, Cls));
2842    // struct objc_super
2843    QualType superType = getSuperStructType();
2844    Expr *SuperRep;
2845
2846    if (LangOpts.Microsoft) {
2847      SynthSuperContructorFunctionDecl();
2848      // Simulate a contructor call...
2849      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2850                                         superType, SourceLocation());
2851      SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2852                                        InitExprs.size(),
2853                                        superType, SourceLocation());
2854      // The code for super is a little tricky to prevent collision with
2855      // the structure definition in the header. The rewriter has it's own
2856      // internal definition (__rw_objc_super) that is uses. This is why
2857      // we need the cast below. For example:
2858      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2859      //
2860      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2861                               Context->getPointerType(SuperRep->getType()),
2862                               SourceLocation());
2863      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2864                               Context->getPointerType(superType),
2865                               CK_Unknown, SuperRep);
2866    } else {
2867      // (struct objc_super) { <exprs from above> }
2868      InitListExpr *ILE =
2869        new (Context) InitListExpr(*Context, SourceLocation(),
2870                                   &InitExprs[0], InitExprs.size(),
2871                                   SourceLocation());
2872      TypeSourceInfo *superTInfo
2873        = Context->getTrivialTypeSourceInfo(superType);
2874      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2875                                                   superType, ILE, false);
2876    }
2877    MsgExprs.push_back(SuperRep);
2878    break;
2879  }
2880
2881  case ObjCMessageExpr::Instance: {
2882    // Remove all type-casts because it may contain objc-style types; e.g.
2883    // Foo<Proto> *.
2884    Expr *recExpr = Exp->getInstanceReceiver();
2885    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2886      recExpr = CE->getSubExpr();
2887    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2888                                       CK_Unknown, recExpr);
2889    MsgExprs.push_back(recExpr);
2890    break;
2891  }
2892  }
2893
2894  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2895  llvm::SmallVector<Expr*, 8> SelExprs;
2896  QualType argType = Context->getPointerType(Context->CharTy);
2897  SelExprs.push_back(StringLiteral::Create(*Context,
2898                                       Exp->getSelector().getAsString().c_str(),
2899                                       Exp->getSelector().getAsString().size(),
2900                                       false, argType, SourceLocation()));
2901  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2902                                                 &SelExprs[0], SelExprs.size(),
2903                                                  StartLoc,
2904                                                  EndLoc);
2905  MsgExprs.push_back(SelExp);
2906
2907  // Now push any user supplied arguments.
2908  for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2909    Expr *userExpr = Exp->getArg(i);
2910    // Make all implicit casts explicit...ICE comes in handy:-)
2911    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2912      // Reuse the ICE type, it is exactly what the doctor ordered.
2913      QualType type = ICE->getType()->isObjCQualifiedIdType()
2914                                ? Context->getObjCIdType()
2915                                : ICE->getType();
2916      // Make sure we convert "type (^)(...)" to "type (*)(...)".
2917      (void)convertBlockPointerToFunctionPointer(type);
2918      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
2919                                          userExpr);
2920    }
2921    // Make id<P...> cast into an 'id' cast.
2922    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2923      if (CE->getType()->isObjCQualifiedIdType()) {
2924        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2925          userExpr = CE->getSubExpr();
2926        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2927                                            CK_Unknown, userExpr);
2928      }
2929    }
2930    MsgExprs.push_back(userExpr);
2931    // We've transferred the ownership to MsgExprs. For now, we *don't* null
2932    // out the argument in the original expression (since we aren't deleting
2933    // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2934    //Exp->setArg(i, 0);
2935  }
2936  // Generate the funky cast.
2937  CastExpr *cast;
2938  llvm::SmallVector<QualType, 8> ArgTypes;
2939  QualType returnType;
2940
2941  // Push 'id' and 'SEL', the 2 implicit arguments.
2942  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2943    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2944  else
2945    ArgTypes.push_back(Context->getObjCIdType());
2946  ArgTypes.push_back(Context->getObjCSelType());
2947  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2948    // Push any user argument types.
2949    for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2950         E = OMD->param_end(); PI != E; ++PI) {
2951      QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2952                     ? Context->getObjCIdType()
2953                     : (*PI)->getType();
2954      // Make sure we convert "t (^)(...)" to "t (*)(...)".
2955      (void)convertBlockPointerToFunctionPointer(t);
2956      ArgTypes.push_back(t);
2957    }
2958    returnType = OMD->getResultType()->isObjCQualifiedIdType()
2959                   ? Context->getObjCIdType() : OMD->getResultType();
2960    (void)convertBlockPointerToFunctionPointer(returnType);
2961  } else {
2962    returnType = Context->getObjCIdType();
2963  }
2964  // Get the type, we will need to reference it in a couple spots.
2965  QualType msgSendType = MsgSendFlavor->getType();
2966
2967  // Create a reference to the objc_msgSend() declaration.
2968  DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2969                                     SourceLocation());
2970
2971  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2972  // If we don't do this cast, we get the following bizarre warning/note:
2973  // xx.m:13: warning: function called through a non-compatible type
2974  // xx.m:13: note: if this code is reached, the program will abort
2975  cast = NoTypeInfoCStyleCastExpr(Context,
2976                                  Context->getPointerType(Context->VoidTy),
2977                                  CK_Unknown, DRE);
2978
2979  // Now do the "normal" pointer to function cast.
2980  QualType castType = Context->getFunctionType(returnType,
2981    &ArgTypes[0], ArgTypes.size(),
2982    // If we don't have a method decl, force a variadic cast.
2983    Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2984                                               false, false, 0, 0,
2985                                               FunctionType::ExtInfo());
2986  castType = Context->getPointerType(castType);
2987  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
2988                                  cast);
2989
2990  // Don't forget the parens to enforce the proper binding.
2991  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2992
2993  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2994  CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2995                                        MsgExprs.size(),
2996                                        FT->getResultType(), EndLoc);
2997  Stmt *ReplacingStmt = CE;
2998  if (MsgSendStretFlavor) {
2999    // We have the method which returns a struct/union. Must also generate
3000    // call to objc_msgSend_stret and hang both varieties on a conditional
3001    // expression which dictate which one to envoke depending on size of
3002    // method's return type.
3003
3004    // Create a reference to the objc_msgSend_stret() declaration.
3005    DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3006                                         SourceLocation());
3007    // Need to cast objc_msgSend_stret to "void *" (see above comment).
3008    cast = NoTypeInfoCStyleCastExpr(Context,
3009                                    Context->getPointerType(Context->VoidTy),
3010                                    CK_Unknown, STDRE);
3011    // Now do the "normal" pointer to function cast.
3012    castType = Context->getFunctionType(returnType,
3013      &ArgTypes[0], ArgTypes.size(),
3014      Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
3015                                        false, false, 0, 0,
3016                                        FunctionType::ExtInfo());
3017    castType = Context->getPointerType(castType);
3018    cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
3019                                    cast);
3020
3021    // Don't forget the parens to enforce the proper binding.
3022    PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3023
3024    FT = msgSendType->getAs<FunctionType>();
3025    CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3026                                            MsgExprs.size(),
3027                                            FT->getResultType(), SourceLocation());
3028
3029    // Build sizeof(returnType)
3030    SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
3031                            Context->getTrivialTypeSourceInfo(returnType),
3032                                      Context->getSizeType(),
3033                                      SourceLocation(), SourceLocation());
3034    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3035    // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3036    // For X86 it is more complicated and some kind of target specific routine
3037    // is needed to decide what to do.
3038    unsigned IntSize =
3039      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3040    IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3041                                                   llvm::APInt(IntSize, 8),
3042                                                   Context->IntTy,
3043                                                   SourceLocation());
3044    BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3045                                                      BO_LE,
3046                                                      Context->IntTy,
3047                                                      SourceLocation());
3048    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3049    ConditionalOperator *CondExpr =
3050      new (Context) ConditionalOperator(lessThanExpr,
3051                                        SourceLocation(), CE,
3052                                        SourceLocation(), STCE, (Expr*)0,
3053                                        returnType);
3054    ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3055                                            CondExpr);
3056  }
3057  // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3058  return ReplacingStmt;
3059}
3060
3061Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3062  Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3063                                         Exp->getLocEnd());
3064
3065  // Now do the actual rewrite.
3066  ReplaceStmt(Exp, ReplacingStmt);
3067
3068  // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3069  return ReplacingStmt;
3070}
3071
3072// typedef struct objc_object Protocol;
3073QualType RewriteObjC::getProtocolType() {
3074  if (!ProtocolTypeDecl) {
3075    TypeSourceInfo *TInfo
3076      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3077    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3078                                           SourceLocation(),
3079                                           &Context->Idents.get("Protocol"),
3080                                           TInfo);
3081  }
3082  return Context->getTypeDeclType(ProtocolTypeDecl);
3083}
3084
3085/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3086/// a synthesized/forward data reference (to the protocol's metadata).
3087/// The forward references (and metadata) are generated in
3088/// RewriteObjC::HandleTranslationUnit().
3089Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3090  std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3091  IdentifierInfo *ID = &Context->Idents.get(Name);
3092  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3093                                ID, getProtocolType(), 0,
3094                                SC_Extern, SC_None);
3095  DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3096  Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3097                             Context->getPointerType(DRE->getType()),
3098                             SourceLocation());
3099  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3100                                                CK_Unknown,
3101                                                DerefExpr);
3102  ReplaceStmt(Exp, castExpr);
3103  ProtocolExprDecls.insert(Exp->getProtocol());
3104  // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
3105  return castExpr;
3106
3107}
3108
3109bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3110                                             const char *endBuf) {
3111  while (startBuf < endBuf) {
3112    if (*startBuf == '#') {
3113      // Skip whitespace.
3114      for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3115        ;
3116      if (!strncmp(startBuf, "if", strlen("if")) ||
3117          !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3118          !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3119          !strncmp(startBuf, "define", strlen("define")) ||
3120          !strncmp(startBuf, "undef", strlen("undef")) ||
3121          !strncmp(startBuf, "else", strlen("else")) ||
3122          !strncmp(startBuf, "elif", strlen("elif")) ||
3123          !strncmp(startBuf, "endif", strlen("endif")) ||
3124          !strncmp(startBuf, "pragma", strlen("pragma")) ||
3125          !strncmp(startBuf, "include", strlen("include")) ||
3126          !strncmp(startBuf, "import", strlen("import")) ||
3127          !strncmp(startBuf, "include_next", strlen("include_next")))
3128        return true;
3129    }
3130    startBuf++;
3131  }
3132  return false;
3133}
3134
3135/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
3136/// an objective-c class with ivars.
3137void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3138                                               std::string &Result) {
3139  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3140  assert(CDecl->getName() != "" &&
3141         "Name missing in SynthesizeObjCInternalStruct");
3142  // Do not synthesize more than once.
3143  if (ObjCSynthesizedStructs.count(CDecl))
3144    return;
3145  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3146  int NumIvars = CDecl->ivar_size();
3147  SourceLocation LocStart = CDecl->getLocStart();
3148  SourceLocation LocEnd = CDecl->getLocEnd();
3149
3150  const char *startBuf = SM->getCharacterData(LocStart);
3151  const char *endBuf = SM->getCharacterData(LocEnd);
3152
3153  // If no ivars and no root or if its root, directly or indirectly,
3154  // have no ivars (thus not synthesized) then no need to synthesize this class.
3155  if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3156      (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3157    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3158    ReplaceText(LocStart, endBuf-startBuf, Result);
3159    return;
3160  }
3161
3162  // FIXME: This has potential of causing problem. If
3163  // SynthesizeObjCInternalStruct is ever called recursively.
3164  Result += "\nstruct ";
3165  Result += CDecl->getNameAsString();
3166  if (LangOpts.Microsoft)
3167    Result += "_IMPL";
3168
3169  if (NumIvars > 0) {
3170    const char *cursor = strchr(startBuf, '{');
3171    assert((cursor && endBuf)
3172           && "SynthesizeObjCInternalStruct - malformed @interface");
3173    // If the buffer contains preprocessor directives, we do more fine-grained
3174    // rewrites. This is intended to fix code that looks like (which occurs in
3175    // NSURL.h, for example):
3176    //
3177    // #ifdef XYZ
3178    // @interface Foo : NSObject
3179    // #else
3180    // @interface FooBar : NSObject
3181    // #endif
3182    // {
3183    //    int i;
3184    // }
3185    // @end
3186    //
3187    // This clause is segregated to avoid breaking the common case.
3188    if (BufferContainsPPDirectives(startBuf, cursor)) {
3189      SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3190                                  CDecl->getClassLoc();
3191      const char *endHeader = SM->getCharacterData(L);
3192      endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3193
3194      if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3195        // advance to the end of the referenced protocols.
3196        while (endHeader < cursor && *endHeader != '>') endHeader++;
3197        endHeader++;
3198      }
3199      // rewrite the original header
3200      ReplaceText(LocStart, endHeader-startBuf, Result);
3201    } else {
3202      // rewrite the original header *without* disturbing the '{'
3203      ReplaceText(LocStart, cursor-startBuf, Result);
3204    }
3205    if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3206      Result = "\n    struct ";
3207      Result += RCDecl->getNameAsString();
3208      Result += "_IMPL ";
3209      Result += RCDecl->getNameAsString();
3210      Result += "_IVARS;\n";
3211
3212      // insert the super class structure definition.
3213      SourceLocation OnePastCurly =
3214        LocStart.getFileLocWithOffset(cursor-startBuf+1);
3215      InsertText(OnePastCurly, Result);
3216    }
3217    cursor++; // past '{'
3218
3219    // Now comment out any visibility specifiers.
3220    while (cursor < endBuf) {
3221      if (*cursor == '@') {
3222        SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3223        // Skip whitespace.
3224        for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3225          /*scan*/;
3226
3227        // FIXME: presence of @public, etc. inside comment results in
3228        // this transformation as well, which is still correct c-code.
3229        if (!strncmp(cursor, "public", strlen("public")) ||
3230            !strncmp(cursor, "private", strlen("private")) ||
3231            !strncmp(cursor, "package", strlen("package")) ||
3232            !strncmp(cursor, "protected", strlen("protected")))
3233          InsertText(atLoc, "// ");
3234      }
3235      // FIXME: If there are cases where '<' is used in ivar declaration part
3236      // of user code, then scan the ivar list and use needToScanForQualifiers
3237      // for type checking.
3238      else if (*cursor == '<') {
3239        SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3240        InsertText(atLoc, "/* ");
3241        cursor = strchr(cursor, '>');
3242        cursor++;
3243        atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3244        InsertText(atLoc, " */");
3245      } else if (*cursor == '^') { // rewrite block specifier.
3246        SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3247        ReplaceText(caretLoc, 1, "*");
3248      }
3249      cursor++;
3250    }
3251    // Don't forget to add a ';'!!
3252    InsertText(LocEnd.getFileLocWithOffset(1), ";");
3253  } else { // we don't have any instance variables - insert super struct.
3254    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3255    Result += " {\n    struct ";
3256    Result += RCDecl->getNameAsString();
3257    Result += "_IMPL ";
3258    Result += RCDecl->getNameAsString();
3259    Result += "_IVARS;\n};\n";
3260    ReplaceText(LocStart, endBuf-startBuf, Result);
3261  }
3262  // Mark this struct as having been generated.
3263  if (!ObjCSynthesizedStructs.insert(CDecl))
3264    assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
3265}
3266
3267// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
3268/// class methods.
3269template<typename MethodIterator>
3270void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3271                                             MethodIterator MethodEnd,
3272                                             bool IsInstanceMethod,
3273                                             llvm::StringRef prefix,
3274                                             llvm::StringRef ClassName,
3275                                             std::string &Result) {
3276  if (MethodBegin == MethodEnd) return;
3277
3278  if (!objc_impl_method) {
3279    /* struct _objc_method {
3280       SEL _cmd;
3281       char *method_types;
3282       void *_imp;
3283       }
3284     */
3285    Result += "\nstruct _objc_method {\n";
3286    Result += "\tSEL _cmd;\n";
3287    Result += "\tchar *method_types;\n";
3288    Result += "\tvoid *_imp;\n";
3289    Result += "};\n";
3290
3291    objc_impl_method = true;
3292  }
3293
3294  // Build _objc_method_list for class's methods if needed
3295
3296  /* struct  {
3297   struct _objc_method_list *next_method;
3298   int method_count;
3299   struct _objc_method method_list[];
3300   }
3301   */
3302  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
3303  Result += "\nstatic struct {\n";
3304  Result += "\tstruct _objc_method_list *next_method;\n";
3305  Result += "\tint method_count;\n";
3306  Result += "\tstruct _objc_method method_list[";
3307  Result += utostr(NumMethods);
3308  Result += "];\n} _OBJC_";
3309  Result += prefix;
3310  Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3311  Result += "_METHODS_";
3312  Result += ClassName;
3313  Result += " __attribute__ ((used, section (\"__OBJC, __";
3314  Result += IsInstanceMethod ? "inst" : "cls";
3315  Result += "_meth\")))= ";
3316  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
3317
3318  Result += "\t,{{(SEL)\"";
3319  Result += (*MethodBegin)->getSelector().getAsString().c_str();
3320  std::string MethodTypeString;
3321  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
3322  Result += "\", \"";
3323  Result += MethodTypeString;
3324  Result += "\", (void *)";
3325  Result += MethodInternalNames[*MethodBegin];
3326  Result += "}\n";
3327  for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3328    Result += "\t  ,{(SEL)\"";
3329    Result += (*MethodBegin)->getSelector().getAsString().c_str();
3330    std::string MethodTypeString;
3331    Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
3332    Result += "\", \"";
3333    Result += MethodTypeString;
3334    Result += "\", (void *)";
3335    Result += MethodInternalNames[*MethodBegin];
3336    Result += "}\n";
3337  }
3338  Result += "\t }\n};\n";
3339}
3340
3341/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
3342void RewriteObjC::
3343RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3344                            llvm::StringRef ClassName, std::string &Result) {
3345  static bool objc_protocol_methods = false;
3346
3347  // Output struct protocol_methods holder of method selector and type.
3348  if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3349    /* struct protocol_methods {
3350     SEL _cmd;
3351     char *method_types;
3352     }
3353     */
3354    Result += "\nstruct _protocol_methods {\n";
3355    Result += "\tstruct objc_selector *_cmd;\n";
3356    Result += "\tchar *method_types;\n";
3357    Result += "};\n";
3358
3359    objc_protocol_methods = true;
3360  }
3361  // Do not synthesize the protocol more than once.
3362  if (ObjCSynthesizedProtocols.count(PDecl))
3363    return;
3364
3365    if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3366      unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3367                                          PDecl->instmeth_end());
3368    /* struct _objc_protocol_method_list {
3369     int protocol_method_count;
3370     struct protocol_methods protocols[];
3371     }
3372     */
3373    Result += "\nstatic struct {\n";
3374    Result += "\tint protocol_method_count;\n";
3375    Result += "\tstruct _protocol_methods protocol_methods[";
3376    Result += utostr(NumMethods);
3377    Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3378    Result += PDecl->getNameAsString();
3379    Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3380      "{\n\t" + utostr(NumMethods) + "\n";
3381
3382    // Output instance methods declared in this protocol.
3383    for (ObjCProtocolDecl::instmeth_iterator
3384           I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
3385         I != E; ++I) {
3386      if (I == PDecl->instmeth_begin())
3387        Result += "\t  ,{{(struct objc_selector *)\"";
3388      else
3389        Result += "\t  ,{(struct objc_selector *)\"";
3390      Result += (*I)->getSelector().getAsString();
3391      std::string MethodTypeString;
3392      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3393      Result += "\", \"";
3394      Result += MethodTypeString;
3395      Result += "\"}\n";
3396    }
3397    Result += "\t }\n};\n";
3398  }
3399
3400  // Output class methods declared in this protocol.
3401  unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3402                                      PDecl->classmeth_end());
3403  if (NumMethods > 0) {
3404    /* struct _objc_protocol_method_list {
3405     int protocol_method_count;
3406     struct protocol_methods protocols[];
3407     }
3408     */
3409    Result += "\nstatic struct {\n";
3410    Result += "\tint protocol_method_count;\n";
3411    Result += "\tstruct _protocol_methods protocol_methods[";
3412    Result += utostr(NumMethods);
3413    Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3414    Result += PDecl->getNameAsString();
3415    Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3416           "{\n\t";
3417    Result += utostr(NumMethods);
3418    Result += "\n";
3419
3420    // Output instance methods declared in this protocol.
3421    for (ObjCProtocolDecl::classmeth_iterator
3422           I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
3423         I != E; ++I) {
3424      if (I == PDecl->classmeth_begin())
3425        Result += "\t  ,{{(struct objc_selector *)\"";
3426      else
3427        Result += "\t  ,{(struct objc_selector *)\"";
3428      Result += (*I)->getSelector().getAsString();
3429      std::string MethodTypeString;
3430      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3431      Result += "\", \"";
3432      Result += MethodTypeString;
3433      Result += "\"}\n";
3434    }
3435    Result += "\t }\n};\n";
3436  }
3437
3438  // Output:
3439  /* struct _objc_protocol {
3440   // Objective-C 1.0 extensions
3441   struct _objc_protocol_extension *isa;
3442   char *protocol_name;
3443   struct _objc_protocol **protocol_list;
3444   struct _objc_protocol_method_list *instance_methods;
3445   struct _objc_protocol_method_list *class_methods;
3446   };
3447   */
3448  static bool objc_protocol = false;
3449  if (!objc_protocol) {
3450    Result += "\nstruct _objc_protocol {\n";
3451    Result += "\tstruct _objc_protocol_extension *isa;\n";
3452    Result += "\tchar *protocol_name;\n";
3453    Result += "\tstruct _objc_protocol **protocol_list;\n";
3454    Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3455    Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
3456    Result += "};\n";
3457
3458    objc_protocol = true;
3459  }
3460
3461  Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3462  Result += PDecl->getNameAsString();
3463  Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3464    "{\n\t0, \"";
3465  Result += PDecl->getNameAsString();
3466  Result += "\", 0, ";
3467  if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3468    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3469    Result += PDecl->getNameAsString();
3470    Result += ", ";
3471  }
3472  else
3473    Result += "0, ";
3474  if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
3475    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3476    Result += PDecl->getNameAsString();
3477    Result += "\n";
3478  }
3479  else
3480    Result += "0\n";
3481  Result += "};\n";
3482
3483  // Mark this protocol as having been generated.
3484  if (!ObjCSynthesizedProtocols.insert(PDecl))
3485    assert(false && "protocol already synthesized");
3486
3487}
3488
3489void RewriteObjC::
3490RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3491                                llvm::StringRef prefix, llvm::StringRef ClassName,
3492                                std::string &Result) {
3493  if (Protocols.empty()) return;
3494
3495  for (unsigned i = 0; i != Protocols.size(); i++)
3496    RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3497
3498  // Output the top lovel protocol meta-data for the class.
3499  /* struct _objc_protocol_list {
3500   struct _objc_protocol_list *next;
3501   int    protocol_count;
3502   struct _objc_protocol *class_protocols[];
3503   }
3504   */
3505  Result += "\nstatic struct {\n";
3506  Result += "\tstruct _objc_protocol_list *next;\n";
3507  Result += "\tint    protocol_count;\n";
3508  Result += "\tstruct _objc_protocol *class_protocols[";
3509  Result += utostr(Protocols.size());
3510  Result += "];\n} _OBJC_";
3511  Result += prefix;
3512  Result += "_PROTOCOLS_";
3513  Result += ClassName;
3514  Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3515    "{\n\t0, ";
3516  Result += utostr(Protocols.size());
3517  Result += "\n";
3518
3519  Result += "\t,{&_OBJC_PROTOCOL_";
3520  Result += Protocols[0]->getNameAsString();
3521  Result += " \n";
3522
3523  for (unsigned i = 1; i != Protocols.size(); i++) {
3524    Result += "\t ,&_OBJC_PROTOCOL_";
3525    Result += Protocols[i]->getNameAsString();
3526    Result += "\n";
3527  }
3528  Result += "\t }\n};\n";
3529}
3530
3531
3532/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
3533/// implementation.
3534void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
3535                                              std::string &Result) {
3536  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
3537  // Find category declaration for this implementation.
3538  ObjCCategoryDecl *CDecl;
3539  for (CDecl = ClassDecl->getCategoryList(); CDecl;
3540       CDecl = CDecl->getNextClassCategory())
3541    if (CDecl->getIdentifier() == IDecl->getIdentifier())
3542      break;
3543
3544  std::string FullCategoryName = ClassDecl->getNameAsString();
3545  FullCategoryName += '_';
3546  FullCategoryName += IDecl->getNameAsString();
3547
3548  // Build _objc_method_list for class's instance methods if needed
3549  llvm::SmallVector<ObjCMethodDecl *, 32>
3550    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3551
3552  // If any of our property implementations have associated getters or
3553  // setters, produce metadata for them as well.
3554  for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3555         PropEnd = IDecl->propimpl_end();
3556       Prop != PropEnd; ++Prop) {
3557    if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3558      continue;
3559    if (!(*Prop)->getPropertyIvarDecl())
3560      continue;
3561    ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3562    if (!PD)
3563      continue;
3564    if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3565      InstanceMethods.push_back(Getter);
3566    if (PD->isReadOnly())
3567      continue;
3568    if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3569      InstanceMethods.push_back(Setter);
3570  }
3571  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
3572                             true, "CATEGORY_", FullCategoryName.c_str(),
3573                             Result);
3574
3575  // Build _objc_method_list for class's class methods if needed
3576  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
3577                             false, "CATEGORY_", FullCategoryName.c_str(),
3578                             Result);
3579
3580  // Protocols referenced in class declaration?
3581  // Null CDecl is case of a category implementation with no category interface
3582  if (CDecl)
3583    RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3584                                    FullCategoryName, Result);
3585  /* struct _objc_category {
3586   char *category_name;
3587   char *class_name;
3588   struct _objc_method_list *instance_methods;
3589   struct _objc_method_list *class_methods;
3590   struct _objc_protocol_list *protocols;
3591   // Objective-C 1.0 extensions
3592   uint32_t size;     // sizeof (struct _objc_category)
3593   struct _objc_property_list *instance_properties;  // category's own
3594                                                     // @property decl.
3595   };
3596   */
3597
3598  static bool objc_category = false;
3599  if (!objc_category) {
3600    Result += "\nstruct _objc_category {\n";
3601    Result += "\tchar *category_name;\n";
3602    Result += "\tchar *class_name;\n";
3603    Result += "\tstruct _objc_method_list *instance_methods;\n";
3604    Result += "\tstruct _objc_method_list *class_methods;\n";
3605    Result += "\tstruct _objc_protocol_list *protocols;\n";
3606    Result += "\tunsigned int size;\n";
3607    Result += "\tstruct _objc_property_list *instance_properties;\n";
3608    Result += "};\n";
3609    objc_category = true;
3610  }
3611  Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3612  Result += FullCategoryName;
3613  Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
3614  Result += IDecl->getNameAsString();
3615  Result += "\"\n\t, \"";
3616  Result += ClassDecl->getNameAsString();
3617  Result += "\"\n";
3618
3619  if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3620    Result += "\t, (struct _objc_method_list *)"
3621           "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3622    Result += FullCategoryName;
3623    Result += "\n";
3624  }
3625  else
3626    Result += "\t, 0\n";
3627  if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
3628    Result += "\t, (struct _objc_method_list *)"
3629           "&_OBJC_CATEGORY_CLASS_METHODS_";
3630    Result += FullCategoryName;
3631    Result += "\n";
3632  }
3633  else
3634    Result += "\t, 0\n";
3635
3636  if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
3637    Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3638    Result += FullCategoryName;
3639    Result += "\n";
3640  }
3641  else
3642    Result += "\t, 0\n";
3643  Result += "\t, sizeof(struct _objc_category), 0\n};\n";
3644}
3645
3646/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3647/// ivar offset.
3648void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
3649                                                  ObjCIvarDecl *ivar,
3650                                                  std::string &Result) {
3651  if (ivar->isBitField()) {
3652    // FIXME: The hack below doesn't work for bitfields. For now, we simply
3653    // place all bitfields at offset 0.
3654    Result += "0";
3655  } else {
3656    Result += "__OFFSETOFIVAR__(struct ";
3657    Result += IDecl->getNameAsString();
3658    if (LangOpts.Microsoft)
3659      Result += "_IMPL";
3660    Result += ", ";
3661    Result += ivar->getNameAsString();
3662    Result += ")";
3663  }
3664}
3665
3666//===----------------------------------------------------------------------===//
3667// Meta Data Emission
3668//===----------------------------------------------------------------------===//
3669
3670void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
3671                                           std::string &Result) {
3672  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
3673
3674  // Explictly declared @interface's are already synthesized.
3675  if (CDecl->isImplicitInterfaceDecl()) {
3676    // FIXME: Implementation of a class with no @interface (legacy) doese not
3677    // produce correct synthesis as yet.
3678    SynthesizeObjCInternalStruct(CDecl, Result);
3679  }
3680
3681  // Build _objc_ivar_list metadata for classes ivars if needed
3682  unsigned NumIvars = !IDecl->ivar_empty()
3683                      ? IDecl->ivar_size()
3684                      : (CDecl ? CDecl->ivar_size() : 0);
3685  if (NumIvars > 0) {
3686    static bool objc_ivar = false;
3687    if (!objc_ivar) {
3688      /* struct _objc_ivar {
3689          char *ivar_name;
3690          char *ivar_type;
3691          int ivar_offset;
3692        };
3693       */
3694      Result += "\nstruct _objc_ivar {\n";
3695      Result += "\tchar *ivar_name;\n";
3696      Result += "\tchar *ivar_type;\n";
3697      Result += "\tint ivar_offset;\n";
3698      Result += "};\n";
3699
3700      objc_ivar = true;
3701    }
3702
3703    /* struct {
3704       int ivar_count;
3705       struct _objc_ivar ivar_list[nIvars];
3706       };
3707     */
3708    Result += "\nstatic struct {\n";
3709    Result += "\tint ivar_count;\n";
3710    Result += "\tstruct _objc_ivar ivar_list[";
3711    Result += utostr(NumIvars);
3712    Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
3713    Result += IDecl->getNameAsString();
3714    Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
3715      "{\n\t";
3716    Result += utostr(NumIvars);
3717    Result += "\n";
3718
3719    ObjCInterfaceDecl::ivar_iterator IVI, IVE;
3720    llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3721    if (!IDecl->ivar_empty()) {
3722      for (ObjCInterfaceDecl::ivar_iterator
3723             IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
3724           IV != IVEnd; ++IV)
3725        IVars.push_back(*IV);
3726      IVI = IDecl->ivar_begin();
3727      IVE = IDecl->ivar_end();
3728    } else {
3729      IVI = CDecl->ivar_begin();
3730      IVE = CDecl->ivar_end();
3731    }
3732    Result += "\t,{{\"";
3733    Result += (*IVI)->getNameAsString();
3734    Result += "\", \"";
3735    std::string TmpString, StrEncoding;
3736    Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3737    QuoteDoublequotes(TmpString, StrEncoding);
3738    Result += StrEncoding;
3739    Result += "\", ";
3740    SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
3741    Result += "}\n";
3742    for (++IVI; IVI != IVE; ++IVI) {
3743      Result += "\t  ,{\"";
3744      Result += (*IVI)->getNameAsString();
3745      Result += "\", \"";
3746      std::string TmpString, StrEncoding;
3747      Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3748      QuoteDoublequotes(TmpString, StrEncoding);
3749      Result += StrEncoding;
3750      Result += "\", ";
3751      SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
3752      Result += "}\n";
3753    }
3754
3755    Result += "\t }\n};\n";
3756  }
3757
3758  // Build _objc_method_list for class's instance methods if needed
3759  llvm::SmallVector<ObjCMethodDecl *, 32>
3760    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
3761
3762  // If any of our property implementations have associated getters or
3763  // setters, produce metadata for them as well.
3764  for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3765         PropEnd = IDecl->propimpl_end();
3766       Prop != PropEnd; ++Prop) {
3767    if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3768      continue;
3769    if (!(*Prop)->getPropertyIvarDecl())
3770      continue;
3771    ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3772    if (!PD)
3773      continue;
3774    if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3775      InstanceMethods.push_back(Getter);
3776    if (PD->isReadOnly())
3777      continue;
3778    if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3779      InstanceMethods.push_back(Setter);
3780  }
3781  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
3782                             true, "", IDecl->getName(), Result);
3783
3784  // Build _objc_method_list for class's class methods if needed
3785  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
3786                             false, "", IDecl->getName(), Result);
3787
3788  // Protocols referenced in class declaration?
3789  RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3790                                  "CLASS", CDecl->getName(), Result);
3791
3792  // Declaration of class/meta-class metadata
3793  /* struct _objc_class {
3794   struct _objc_class *isa; // or const char *root_class_name when metadata
3795   const char *super_class_name;
3796   char *name;
3797   long version;
3798   long info;
3799   long instance_size;
3800   struct _objc_ivar_list *ivars;
3801   struct _objc_method_list *methods;
3802   struct objc_cache *cache;
3803   struct objc_protocol_list *protocols;
3804   const char *ivar_layout;
3805   struct _objc_class_ext  *ext;
3806   };
3807  */
3808  static bool objc_class = false;
3809  if (!objc_class) {
3810    Result += "\nstruct _objc_class {\n";
3811    Result += "\tstruct _objc_class *isa;\n";
3812    Result += "\tconst char *super_class_name;\n";
3813    Result += "\tchar *name;\n";
3814    Result += "\tlong version;\n";
3815    Result += "\tlong info;\n";
3816    Result += "\tlong instance_size;\n";
3817    Result += "\tstruct _objc_ivar_list *ivars;\n";
3818    Result += "\tstruct _objc_method_list *methods;\n";
3819    Result += "\tstruct objc_cache *cache;\n";
3820    Result += "\tstruct _objc_protocol_list *protocols;\n";
3821    Result += "\tconst char *ivar_layout;\n";
3822    Result += "\tstruct _objc_class_ext  *ext;\n";
3823    Result += "};\n";
3824    objc_class = true;
3825  }
3826
3827  // Meta-class metadata generation.
3828  ObjCInterfaceDecl *RootClass = 0;
3829  ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
3830  while (SuperClass) {
3831    RootClass = SuperClass;
3832    SuperClass = SuperClass->getSuperClass();
3833  }
3834  SuperClass = CDecl->getSuperClass();
3835
3836  Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3837  Result += CDecl->getNameAsString();
3838  Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
3839  "{\n\t(struct _objc_class *)\"";
3840  Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
3841  Result += "\"";
3842
3843  if (SuperClass) {
3844    Result += ", \"";
3845    Result += SuperClass->getNameAsString();
3846    Result += "\", \"";
3847    Result += CDecl->getNameAsString();
3848    Result += "\"";
3849  }
3850  else {
3851    Result += ", 0, \"";
3852    Result += CDecl->getNameAsString();
3853    Result += "\"";
3854  }
3855  // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
3856  // 'info' field is initialized to CLS_META(2) for metaclass
3857  Result += ", 0,2, sizeof(struct _objc_class), 0";
3858  if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
3859    Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
3860    Result += IDecl->getNameAsString();
3861    Result += "\n";
3862  }
3863  else
3864    Result += ", 0\n";
3865  if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3866    Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
3867    Result += CDecl->getNameAsString();
3868    Result += ",0,0\n";
3869  }
3870  else
3871    Result += "\t,0,0,0,0\n";
3872  Result += "};\n";
3873
3874  // class metadata generation.
3875  Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3876  Result += CDecl->getNameAsString();
3877  Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
3878            "{\n\t&_OBJC_METACLASS_";
3879  Result += CDecl->getNameAsString();
3880  if (SuperClass) {
3881    Result += ", \"";
3882    Result += SuperClass->getNameAsString();
3883    Result += "\", \"";
3884    Result += CDecl->getNameAsString();
3885    Result += "\"";
3886  }
3887  else {
3888    Result += ", 0, \"";
3889    Result += CDecl->getNameAsString();
3890    Result += "\"";
3891  }
3892  // 'info' field is initialized to CLS_CLASS(1) for class
3893  Result += ", 0,1";
3894  if (!ObjCSynthesizedStructs.count(CDecl))
3895    Result += ",0";
3896  else {
3897    // class has size. Must synthesize its size.
3898    Result += ",sizeof(struct ";
3899    Result += CDecl->getNameAsString();
3900    if (LangOpts.Microsoft)
3901      Result += "_IMPL";
3902    Result += ")";
3903  }
3904  if (NumIvars > 0) {
3905    Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
3906    Result += CDecl->getNameAsString();
3907    Result += "\n\t";
3908  }
3909  else
3910    Result += ",0";
3911  if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
3912    Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
3913    Result += CDecl->getNameAsString();
3914    Result += ", 0\n\t";
3915  }
3916  else
3917    Result += ",0,0";
3918  if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3919    Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
3920    Result += CDecl->getNameAsString();
3921    Result += ", 0,0\n";
3922  }
3923  else
3924    Result += ",0,0,0\n";
3925  Result += "};\n";
3926}
3927
3928/// RewriteImplementations - This routine rewrites all method implementations
3929/// and emits meta-data.
3930
3931void RewriteObjC::RewriteImplementations() {
3932  int ClsDefCount = ClassImplementation.size();
3933  int CatDefCount = CategoryImplementation.size();
3934
3935  // Rewrite implemented methods
3936  for (int i = 0; i < ClsDefCount; i++)
3937    RewriteImplementationDecl(ClassImplementation[i]);
3938
3939  for (int i = 0; i < CatDefCount; i++)
3940    RewriteImplementationDecl(CategoryImplementation[i]);
3941}
3942
3943void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3944  int ClsDefCount = ClassImplementation.size();
3945  int CatDefCount = CategoryImplementation.size();
3946
3947  // For each implemented class, write out all its meta data.
3948  for (int i = 0; i < ClsDefCount; i++)
3949    RewriteObjCClassMetaData(ClassImplementation[i], Result);
3950
3951  // For each implemented category, write out all its meta data.
3952  for (int i = 0; i < CatDefCount; i++)
3953    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
3954
3955  // Write objc_symtab metadata
3956  /*
3957   struct _objc_symtab
3958   {
3959   long sel_ref_cnt;
3960   SEL *refs;
3961   short cls_def_cnt;
3962   short cat_def_cnt;
3963   void *defs[cls_def_cnt + cat_def_cnt];
3964   };
3965   */
3966
3967  Result += "\nstruct _objc_symtab {\n";
3968  Result += "\tlong sel_ref_cnt;\n";
3969  Result += "\tSEL *refs;\n";
3970  Result += "\tshort cls_def_cnt;\n";
3971  Result += "\tshort cat_def_cnt;\n";
3972  Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3973  Result += "};\n\n";
3974
3975  Result += "static struct _objc_symtab "
3976         "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
3977  Result += "\t0, 0, " + utostr(ClsDefCount)
3978            + ", " + utostr(CatDefCount) + "\n";
3979  for (int i = 0; i < ClsDefCount; i++) {
3980    Result += "\t,&_OBJC_CLASS_";
3981    Result += ClassImplementation[i]->getNameAsString();
3982    Result += "\n";
3983  }
3984
3985  for (int i = 0; i < CatDefCount; i++) {
3986    Result += "\t,&_OBJC_CATEGORY_";
3987    Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
3988    Result += "_";
3989    Result += CategoryImplementation[i]->getNameAsString();
3990    Result += "\n";
3991  }
3992
3993  Result += "};\n\n";
3994
3995  // Write objc_module metadata
3996
3997  /*
3998   struct _objc_module {
3999    long version;
4000    long size;
4001    const char *name;
4002    struct _objc_symtab *symtab;
4003   }
4004  */
4005
4006  Result += "\nstruct _objc_module {\n";
4007  Result += "\tlong version;\n";
4008  Result += "\tlong size;\n";
4009  Result += "\tconst char *name;\n";
4010  Result += "\tstruct _objc_symtab *symtab;\n";
4011  Result += "};\n\n";
4012  Result += "static struct _objc_module "
4013    "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
4014  Result += "\t" + utostr(OBJC_ABI_VERSION) +
4015  ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
4016  Result += "};\n\n";
4017
4018  if (LangOpts.Microsoft) {
4019    if (ProtocolExprDecls.size()) {
4020      Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4021      Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
4022      for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4023           E = ProtocolExprDecls.end(); I != E; ++I) {
4024        Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4025        Result += (*I)->getNameAsString();
4026        Result += " = &_OBJC_PROTOCOL_";
4027        Result += (*I)->getNameAsString();
4028        Result += ";\n";
4029      }
4030      Result += "#pragma data_seg(pop)\n\n";
4031    }
4032    Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
4033    Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
4034    Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4035    Result += "&_OBJC_MODULES;\n";
4036    Result += "#pragma data_seg(pop)\n\n";
4037  }
4038}
4039
4040void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4041                                     const std::string &Name,
4042                                     ValueDecl *VD) {
4043  assert(BlockByRefDeclNo.count(VD) &&
4044         "RewriteByRefString: ByRef decl missing");
4045  ResultStr += "struct __Block_byref_" + Name +
4046    "_" + utostr(BlockByRefDeclNo[VD]) ;
4047}
4048
4049static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4050  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4051    return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4052  return false;
4053}
4054
4055std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4056                                                   llvm::StringRef funcName,
4057                                                   std::string Tag) {
4058  const FunctionType *AFT = CE->getFunctionType();
4059  QualType RT = AFT->getResultType();
4060  std::string StructRef = "struct " + Tag;
4061  std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
4062                  funcName.str() + "_" + "block_func_" + utostr(i);
4063
4064  BlockDecl *BD = CE->getBlockDecl();
4065
4066  if (isa<FunctionNoProtoType>(AFT)) {
4067    // No user-supplied arguments. Still need to pass in a pointer to the
4068    // block (to reference imported block decl refs).
4069    S += "(" + StructRef + " *__cself)";
4070  } else if (BD->param_empty()) {
4071    S += "(" + StructRef + " *__cself)";
4072  } else {
4073    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4074    assert(FT && "SynthesizeBlockFunc: No function proto");
4075    S += '(';
4076    // first add the implicit argument.
4077    S += StructRef + " *__cself, ";
4078    std::string ParamStr;
4079    for (BlockDecl::param_iterator AI = BD->param_begin(),
4080         E = BD->param_end(); AI != E; ++AI) {
4081      if (AI != BD->param_begin()) S += ", ";
4082      ParamStr = (*AI)->getNameAsString();
4083      QualType QT = (*AI)->getType();
4084      if (convertBlockPointerToFunctionPointer(QT))
4085        QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
4086      else
4087        QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
4088      S += ParamStr;
4089    }
4090    if (FT->isVariadic()) {
4091      if (!BD->param_empty()) S += ", ";
4092      S += "...";
4093    }
4094    S += ')';
4095  }
4096  S += " {\n";
4097
4098  // Create local declarations to avoid rewriting all closure decl ref exprs.
4099  // First, emit a declaration for all "by ref" decls.
4100  for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4101       E = BlockByRefDecls.end(); I != E; ++I) {
4102    S += "  ";
4103    std::string Name = (*I)->getNameAsString();
4104    std::string TypeString;
4105    RewriteByRefString(TypeString, Name, (*I));
4106    TypeString += " *";
4107    Name = TypeString + Name;
4108    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4109  }
4110  // Next, emit a declaration for all "by copy" declarations.
4111  for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4112       E = BlockByCopyDecls.end(); I != E; ++I) {
4113    S += "  ";
4114    // Handle nested closure invocation. For example:
4115    //
4116    //   void (^myImportedClosure)(void);
4117    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4118    //
4119    //   void (^anotherClosure)(void);
4120    //   anotherClosure = ^(void) {
4121    //     myImportedClosure(); // import and invoke the closure
4122    //   };
4123    //
4124    if (isTopLevelBlockPointerType((*I)->getType())) {
4125      RewriteBlockPointerTypeVariable(S, (*I));
4126      S += " = (";
4127      RewriteBlockPointerType(S, (*I)->getType());
4128      S += ")";
4129      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4130    }
4131    else {
4132      std::string Name = (*I)->getNameAsString();
4133      QualType QT = (*I)->getType();
4134      if (HasLocalVariableExternalStorage(*I))
4135        QT = Context->getPointerType(QT);
4136      QT.getAsStringInternal(Name, Context->PrintingPolicy);
4137      S += Name + " = __cself->" +
4138                              (*I)->getNameAsString() + "; // bound by copy\n";
4139    }
4140  }
4141  std::string RewrittenStr = RewrittenBlockExprs[CE];
4142  const char *cstr = RewrittenStr.c_str();
4143  while (*cstr++ != '{') ;
4144  S += cstr;
4145  S += "\n";
4146  return S;
4147}
4148
4149std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4150                                                   llvm::StringRef funcName,
4151                                                   std::string Tag) {
4152  std::string StructRef = "struct " + Tag;
4153  std::string S = "static void __";
4154
4155  S += funcName;
4156  S += "_block_copy_" + utostr(i);
4157  S += "(" + StructRef;
4158  S += "*dst, " + StructRef;
4159  S += "*src) {";
4160  for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4161      E = ImportedBlockDecls.end(); I != E; ++I) {
4162    S += "_Block_object_assign((void*)&dst->";
4163    S += (*I)->getNameAsString();
4164    S += ", (void*)src->";
4165    S += (*I)->getNameAsString();
4166    if (BlockByRefDeclsPtrSet.count((*I)))
4167      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4168    else
4169      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4170  }
4171  S += "}\n";
4172
4173  S += "\nstatic void __";
4174  S += funcName;
4175  S += "_block_dispose_" + utostr(i);
4176  S += "(" + StructRef;
4177  S += "*src) {";
4178  for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4179      E = ImportedBlockDecls.end(); I != E; ++I) {
4180    S += "_Block_object_dispose((void*)src->";
4181    S += (*I)->getNameAsString();
4182    if (BlockByRefDeclsPtrSet.count((*I)))
4183      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4184    else
4185      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4186  }
4187  S += "}\n";
4188  return S;
4189}
4190
4191std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4192                                             std::string Desc) {
4193  std::string S = "\nstruct " + Tag;
4194  std::string Constructor = "  " + Tag;
4195
4196  S += " {\n  struct __block_impl impl;\n";
4197  S += "  struct " + Desc;
4198  S += "* Desc;\n";
4199
4200  Constructor += "(void *fp, "; // Invoke function pointer.
4201  Constructor += "struct " + Desc; // Descriptor pointer.
4202  Constructor += " *desc";
4203
4204  if (BlockDeclRefs.size()) {
4205    // Output all "by copy" declarations.
4206    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4207         E = BlockByCopyDecls.end(); I != E; ++I) {
4208      S += "  ";
4209      std::string FieldName = (*I)->getNameAsString();
4210      std::string ArgName = "_" + FieldName;
4211      // Handle nested closure invocation. For example:
4212      //
4213      //   void (^myImportedBlock)(void);
4214      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4215      //
4216      //   void (^anotherBlock)(void);
4217      //   anotherBlock = ^(void) {
4218      //     myImportedBlock(); // import and invoke the closure
4219      //   };
4220      //
4221      if (isTopLevelBlockPointerType((*I)->getType())) {
4222        S += "struct __block_impl *";
4223        Constructor += ", void *" + ArgName;
4224      } else {
4225        QualType QT = (*I)->getType();
4226        if (HasLocalVariableExternalStorage(*I))
4227          QT = Context->getPointerType(QT);
4228        QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4229        QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
4230        Constructor += ", " + ArgName;
4231      }
4232      S += FieldName + ";\n";
4233    }
4234    // Output all "by ref" declarations.
4235    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4236         E = BlockByRefDecls.end(); I != E; ++I) {
4237      S += "  ";
4238      std::string FieldName = (*I)->getNameAsString();
4239      std::string ArgName = "_" + FieldName;
4240      // Handle nested closure invocation. For example:
4241      //
4242      //   void (^myImportedBlock)(void);
4243      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4244      //
4245      //   void (^anotherBlock)(void);
4246      //   anotherBlock = ^(void) {
4247      //     myImportedBlock(); // import and invoke the closure
4248      //   };
4249      //
4250      if (isTopLevelBlockPointerType((*I)->getType())) {
4251        S += "struct __block_impl *";
4252        Constructor += ", void *" + ArgName;
4253      } else {
4254        std::string TypeString;
4255        RewriteByRefString(TypeString, FieldName, (*I));
4256        TypeString += " *";
4257        FieldName = TypeString + FieldName;
4258        ArgName = TypeString + ArgName;
4259        Constructor += ", " + ArgName;
4260      }
4261      S += FieldName + "; // by ref\n";
4262    }
4263    // Finish writing the constructor.
4264    Constructor += ", int flags=0)";
4265    // Initialize all "by copy" arguments.
4266    bool firsTime = true;
4267    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4268         E = BlockByCopyDecls.end(); I != E; ++I) {
4269      std::string Name = (*I)->getNameAsString();
4270        if (firsTime) {
4271          Constructor += " : ";
4272          firsTime = false;
4273        }
4274        else
4275          Constructor += ", ";
4276        if (isTopLevelBlockPointerType((*I)->getType()))
4277          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4278        else
4279          Constructor += Name + "(_" + Name + ")";
4280    }
4281    // Initialize all "by ref" arguments.
4282    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4283         E = BlockByRefDecls.end(); I != E; ++I) {
4284      std::string Name = (*I)->getNameAsString();
4285      if (firsTime) {
4286        Constructor += " : ";
4287        firsTime = false;
4288      }
4289      else
4290        Constructor += ", ";
4291      if (isTopLevelBlockPointerType((*I)->getType()))
4292        Constructor += Name + "((struct __block_impl *)_"
4293                        + Name + "->__forwarding)";
4294      else
4295        Constructor += Name + "(_" + Name + "->__forwarding)";
4296    }
4297
4298    Constructor += " {\n";
4299    if (GlobalVarDecl)
4300      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4301    else
4302      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4303    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4304
4305    Constructor += "    Desc = desc;\n";
4306  } else {
4307    // Finish writing the constructor.
4308    Constructor += ", int flags=0) {\n";
4309    if (GlobalVarDecl)
4310      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4311    else
4312      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4313    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4314    Constructor += "    Desc = desc;\n";
4315  }
4316  Constructor += "  ";
4317  Constructor += "}\n";
4318  S += Constructor;
4319  S += "};\n";
4320  return S;
4321}
4322
4323std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4324                                                   std::string ImplTag, int i,
4325                                                   llvm::StringRef FunName,
4326                                                   unsigned hasCopy) {
4327  std::string S = "\nstatic struct " + DescTag;
4328
4329  S += " {\n  unsigned long reserved;\n";
4330  S += "  unsigned long Block_size;\n";
4331  if (hasCopy) {
4332    S += "  void (*copy)(struct ";
4333    S += ImplTag; S += "*, struct ";
4334    S += ImplTag; S += "*);\n";
4335
4336    S += "  void (*dispose)(struct ";
4337    S += ImplTag; S += "*);\n";
4338  }
4339  S += "} ";
4340
4341  S += DescTag + "_DATA = { 0, sizeof(struct ";
4342  S += ImplTag + ")";
4343  if (hasCopy) {
4344    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4345    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4346  }
4347  S += "};\n";
4348  return S;
4349}
4350
4351void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4352                                          llvm::StringRef FunName) {
4353  // Insert declaration for the function in which block literal is used.
4354  if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4355    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4356  bool RewriteSC = (GlobalVarDecl &&
4357                    !Blocks.empty() &&
4358                    GlobalVarDecl->getStorageClass() == SC_Static &&
4359                    GlobalVarDecl->getType().getCVRQualifiers());
4360  if (RewriteSC) {
4361    std::string SC(" void __");
4362    SC += GlobalVarDecl->getNameAsString();
4363    SC += "() {}";
4364    InsertText(FunLocStart, SC);
4365  }
4366
4367  // Insert closures that were part of the function.
4368  for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4369    CollectBlockDeclRefInfo(Blocks[i]);
4370    // Need to copy-in the inner copied-in variables not actually used in this
4371    // block.
4372    for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4373      BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4374      ValueDecl *VD = Exp->getDecl();
4375      BlockDeclRefs.push_back(Exp);
4376      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4377        BlockByCopyDeclsPtrSet.insert(VD);
4378        BlockByCopyDecls.push_back(VD);
4379      }
4380      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4381        BlockByRefDeclsPtrSet.insert(VD);
4382        BlockByRefDecls.push_back(VD);
4383      }
4384      // imported objects in the inner blocks not used in the outer
4385      // blocks must be copied/disposed in the outer block as well.
4386      if (Exp->isByRef() ||
4387          VD->getType()->isObjCObjectPointerType() ||
4388          VD->getType()->isBlockPointerType())
4389        ImportedBlockDecls.insert(VD);
4390    }
4391
4392    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4393    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4394
4395    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4396
4397    InsertText(FunLocStart, CI);
4398
4399    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4400
4401    InsertText(FunLocStart, CF);
4402
4403    if (ImportedBlockDecls.size()) {
4404      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4405      InsertText(FunLocStart, HF);
4406    }
4407    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4408                                               ImportedBlockDecls.size() > 0);
4409    InsertText(FunLocStart, BD);
4410
4411    BlockDeclRefs.clear();
4412    BlockByRefDecls.clear();
4413    BlockByRefDeclsPtrSet.clear();
4414    BlockByCopyDecls.clear();
4415    BlockByCopyDeclsPtrSet.clear();
4416    ImportedBlockDecls.clear();
4417  }
4418  if (RewriteSC) {
4419    // Must insert any 'const/volatile/static here. Since it has been
4420    // removed as result of rewriting of block literals.
4421    std::string SC;
4422    if (GlobalVarDecl->getStorageClass() == SC_Static)
4423      SC = "static ";
4424    if (GlobalVarDecl->getType().isConstQualified())
4425      SC += "const ";
4426    if (GlobalVarDecl->getType().isVolatileQualified())
4427      SC += "volatile ";
4428    if (GlobalVarDecl->getType().isRestrictQualified())
4429      SC += "restrict ";
4430    InsertText(FunLocStart, SC);
4431  }
4432
4433  Blocks.clear();
4434  InnerDeclRefsCount.clear();
4435  InnerDeclRefs.clear();
4436  RewrittenBlockExprs.clear();
4437}
4438
4439void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4440  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4441  llvm::StringRef FuncName = FD->getName();
4442
4443  SynthesizeBlockLiterals(FunLocStart, FuncName);
4444}
4445
4446static void BuildUniqueMethodName(std::string &Name,
4447                                  ObjCMethodDecl *MD) {
4448  ObjCInterfaceDecl *IFace = MD->getClassInterface();
4449  Name = IFace->getName();
4450  Name += "__" + MD->getSelector().getAsString();
4451  // Convert colons to underscores.
4452  std::string::size_type loc = 0;
4453  while ((loc = Name.find(":", loc)) != std::string::npos)
4454    Name.replace(loc, 1, "_");
4455}
4456
4457void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4458  //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4459  //SourceLocation FunLocStart = MD->getLocStart();
4460  SourceLocation FunLocStart = MD->getLocStart();
4461  std::string FuncName;
4462  BuildUniqueMethodName(FuncName, MD);
4463  SynthesizeBlockLiterals(FunLocStart, FuncName);
4464}
4465
4466void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4467  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4468       CI != E; ++CI)
4469    if (*CI) {
4470      if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4471        GetBlockDeclRefExprs(CBE->getBody());
4472      else
4473        GetBlockDeclRefExprs(*CI);
4474    }
4475  // Handle specific things.
4476  if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4477    // FIXME: Handle enums.
4478    if (!isa<FunctionDecl>(CDRE->getDecl()))
4479      BlockDeclRefs.push_back(CDRE);
4480  }
4481  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4482    if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4483        BlockDeclRefExpr *BDRE =
4484          new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4485                                        DRE->getLocation(), false);
4486        BlockDeclRefs.push_back(BDRE);
4487    }
4488
4489  return;
4490}
4491
4492void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4493                llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
4494                llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4495  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4496       CI != E; ++CI)
4497    if (*CI) {
4498      if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4499        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4500        GetInnerBlockDeclRefExprs(CBE->getBody(),
4501                                  InnerBlockDeclRefs,
4502                                  InnerContexts);
4503      }
4504      else
4505        GetInnerBlockDeclRefExprs(*CI,
4506                                  InnerBlockDeclRefs,
4507                                  InnerContexts);
4508
4509    }
4510  // Handle specific things.
4511  if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4512    if (!isa<FunctionDecl>(CDRE->getDecl()) &&
4513        !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
4514      InnerBlockDeclRefs.push_back(CDRE);
4515  }
4516  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4517    if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4518      if (Var->isFunctionOrMethodVarDecl())
4519        ImportedLocalExternalDecls.insert(Var);
4520  }
4521
4522  return;
4523}
4524
4525/// convertFunctionTypeOfBlocks - This routine converts a function type
4526/// whose result type may be a block pointer or whose argument type(s)
4527/// might be block pointers to an equivalent funtion type replacing
4528/// all block pointers to function pointers.
4529QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4530  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4531  // FTP will be null for closures that don't take arguments.
4532  // Generate a funky cast.
4533  llvm::SmallVector<QualType, 8> ArgTypes;
4534  QualType Res = FT->getResultType();
4535  bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
4536
4537  if (FTP) {
4538    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4539         E = FTP->arg_type_end(); I && (I != E); ++I) {
4540      QualType t = *I;
4541      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4542      if (convertBlockPointerToFunctionPointer(t))
4543        HasBlockType = true;
4544      ArgTypes.push_back(t);
4545    }
4546  }
4547  QualType FuncType;
4548  // FIXME. Does this work if block takes no argument but has a return type
4549  // which is of block type?
4550  if (HasBlockType)
4551    FuncType = Context->getFunctionType(Res,
4552                        &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4553                        false, false, 0, 0, FunctionType::ExtInfo());
4554  else FuncType = QualType(FT, 0);
4555  return FuncType;
4556}
4557
4558Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4559  // Navigate to relevant type information.
4560  const BlockPointerType *CPT = 0;
4561
4562  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4563    CPT = DRE->getType()->getAs<BlockPointerType>();
4564  } else if (const BlockDeclRefExpr *CDRE =
4565              dyn_cast<BlockDeclRefExpr>(BlockExp)) {
4566    CPT = CDRE->getType()->getAs<BlockPointerType>();
4567  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4568    CPT = MExpr->getType()->getAs<BlockPointerType>();
4569  }
4570  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4571    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4572  }
4573  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4574    CPT = IEXPR->getType()->getAs<BlockPointerType>();
4575  else if (const ConditionalOperator *CEXPR =
4576            dyn_cast<ConditionalOperator>(BlockExp)) {
4577    Expr *LHSExp = CEXPR->getLHS();
4578    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4579    Expr *RHSExp = CEXPR->getRHS();
4580    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4581    Expr *CONDExp = CEXPR->getCond();
4582    ConditionalOperator *CondExpr =
4583      new (Context) ConditionalOperator(CONDExp,
4584                                      SourceLocation(), cast<Expr>(LHSStmt),
4585                                      SourceLocation(), cast<Expr>(RHSStmt),
4586                                      (Expr*)0,
4587                                      Exp->getType());
4588    return CondExpr;
4589  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4590    CPT = IRE->getType()->getAs<BlockPointerType>();
4591  } else {
4592    assert(1 && "RewriteBlockClass: Bad type");
4593  }
4594  assert(CPT && "RewriteBlockClass: Bad type");
4595  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4596  assert(FT && "RewriteBlockClass: Bad type");
4597  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4598  // FTP will be null for closures that don't take arguments.
4599
4600  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4601                                      SourceLocation(),
4602                                      &Context->Idents.get("__block_impl"));
4603  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4604
4605  // Generate a funky cast.
4606  llvm::SmallVector<QualType, 8> ArgTypes;
4607
4608  // Push the block argument type.
4609  ArgTypes.push_back(PtrBlock);
4610  if (FTP) {
4611    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4612         E = FTP->arg_type_end(); I && (I != E); ++I) {
4613      QualType t = *I;
4614      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4615      (void)convertBlockPointerToFunctionPointer(t);
4616      ArgTypes.push_back(t);
4617    }
4618  }
4619  // Now do the pointer to function cast.
4620  QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
4621    &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4622                                                        false, false, 0, 0,
4623                                                       FunctionType::ExtInfo());
4624
4625  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4626
4627  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4628                                               CK_Unknown,
4629                                               const_cast<Expr*>(BlockExp));
4630  // Don't forget the parens to enforce the proper binding.
4631  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4632                                          BlkCast);
4633  //PE->dump();
4634
4635  FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4636                     &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
4637                                    /*BitWidth=*/0, /*Mutable=*/true);
4638  MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4639                                            FD->getType());
4640
4641  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4642                                                CK_Unknown, ME);
4643  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4644
4645  llvm::SmallVector<Expr*, 8> BlkExprs;
4646  // Add the implicit argument.
4647  BlkExprs.push_back(BlkCast);
4648  // Add the user arguments.
4649  for (CallExpr::arg_iterator I = Exp->arg_begin(),
4650       E = Exp->arg_end(); I != E; ++I) {
4651    BlkExprs.push_back(*I);
4652  }
4653  CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4654                                        BlkExprs.size(),
4655                                        Exp->getType(), SourceLocation());
4656  return CE;
4657}
4658
4659// We need to return the rewritten expression to handle cases where the
4660// BlockDeclRefExpr is embedded in another expression being rewritten.
4661// For example:
4662//
4663// int main() {
4664//    __block Foo *f;
4665//    __block int i;
4666//
4667//    void (^myblock)() = ^() {
4668//        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4669//        i = 77;
4670//    };
4671//}
4672Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
4673  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4674  // for each DeclRefExp where BYREFVAR is name of the variable.
4675  ValueDecl *VD;
4676  bool isArrow = true;
4677  if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4678    VD = BDRE->getDecl();
4679  else {
4680    VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4681    isArrow = false;
4682  }
4683
4684  FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4685                                    &Context->Idents.get("__forwarding"),
4686                                    Context->VoidPtrTy, 0,
4687                                    /*BitWidth=*/0, /*Mutable=*/true);
4688  MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4689                                            FD, SourceLocation(),
4690                                            FD->getType());
4691
4692  llvm::StringRef Name = VD->getName();
4693  FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4694                         &Context->Idents.get(Name),
4695                         Context->VoidPtrTy, 0,
4696                         /*BitWidth=*/0, /*Mutable=*/true);
4697  ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4698                                DeclRefExp->getType());
4699
4700
4701
4702  // Need parens to enforce precedence.
4703  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4704                                          ME);
4705  ReplaceStmt(DeclRefExp, PE);
4706  return PE;
4707}
4708
4709// Rewrites the imported local variable V with external storage
4710// (static, extern, etc.) as *V
4711//
4712Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4713  ValueDecl *VD = DRE->getDecl();
4714  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4715    if (!ImportedLocalExternalDecls.count(Var))
4716      return DRE;
4717  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
4718                                    DRE->getType(), DRE->getLocation());
4719  // Need parens to enforce precedence.
4720  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4721                                          Exp);
4722  ReplaceStmt(DRE, PE);
4723  return PE;
4724}
4725
4726void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4727  SourceLocation LocStart = CE->getLParenLoc();
4728  SourceLocation LocEnd = CE->getRParenLoc();
4729
4730  // Need to avoid trying to rewrite synthesized casts.
4731  if (LocStart.isInvalid())
4732    return;
4733  // Need to avoid trying to rewrite casts contained in macros.
4734  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4735    return;
4736
4737  const char *startBuf = SM->getCharacterData(LocStart);
4738  const char *endBuf = SM->getCharacterData(LocEnd);
4739  QualType QT = CE->getType();
4740  const Type* TypePtr = QT->getAs<Type>();
4741  if (isa<TypeOfExprType>(TypePtr)) {
4742    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4743    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4744    std::string TypeAsString = "(";
4745    RewriteBlockPointerType(TypeAsString, QT);
4746    TypeAsString += ")";
4747    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4748    return;
4749  }
4750  // advance the location to startArgList.
4751  const char *argPtr = startBuf;
4752
4753  while (*argPtr++ && (argPtr < endBuf)) {
4754    switch (*argPtr) {
4755    case '^':
4756      // Replace the '^' with '*'.
4757      LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4758      ReplaceText(LocStart, 1, "*");
4759      break;
4760    }
4761  }
4762  return;
4763}
4764
4765void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4766  SourceLocation DeclLoc = FD->getLocation();
4767  unsigned parenCount = 0;
4768
4769  // We have 1 or more arguments that have closure pointers.
4770  const char *startBuf = SM->getCharacterData(DeclLoc);
4771  const char *startArgList = strchr(startBuf, '(');
4772
4773  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4774
4775  parenCount++;
4776  // advance the location to startArgList.
4777  DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4778  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4779
4780  const char *argPtr = startArgList;
4781
4782  while (*argPtr++ && parenCount) {
4783    switch (*argPtr) {
4784    case '^':
4785      // Replace the '^' with '*'.
4786      DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4787      ReplaceText(DeclLoc, 1, "*");
4788      break;
4789    case '(':
4790      parenCount++;
4791      break;
4792    case ')':
4793      parenCount--;
4794      break;
4795    }
4796  }
4797  return;
4798}
4799
4800bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4801  const FunctionProtoType *FTP;
4802  const PointerType *PT = QT->getAs<PointerType>();
4803  if (PT) {
4804    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4805  } else {
4806    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4807    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4808    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4809  }
4810  if (FTP) {
4811    for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4812         E = FTP->arg_type_end(); I != E; ++I)
4813      if (isTopLevelBlockPointerType(*I))
4814        return true;
4815  }
4816  return false;
4817}
4818
4819void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4820                                     const char *&RParen) {
4821  const char *argPtr = strchr(Name, '(');
4822  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4823
4824  LParen = argPtr; // output the start.
4825  argPtr++; // skip past the left paren.
4826  unsigned parenCount = 1;
4827
4828  while (*argPtr && parenCount) {
4829    switch (*argPtr) {
4830    case '(': parenCount++; break;
4831    case ')': parenCount--; break;
4832    default: break;
4833    }
4834    if (parenCount) argPtr++;
4835  }
4836  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4837  RParen = argPtr; // output the end
4838}
4839
4840void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4841  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4842    RewriteBlockPointerFunctionArgs(FD);
4843    return;
4844  }
4845  // Handle Variables and Typedefs.
4846  SourceLocation DeclLoc = ND->getLocation();
4847  QualType DeclT;
4848  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4849    DeclT = VD->getType();
4850  else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4851    DeclT = TDD->getUnderlyingType();
4852  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4853    DeclT = FD->getType();
4854  else
4855    assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4856
4857  const char *startBuf = SM->getCharacterData(DeclLoc);
4858  const char *endBuf = startBuf;
4859  // scan backward (from the decl location) for the end of the previous decl.
4860  while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4861    startBuf--;
4862
4863  // *startBuf != '^' if we are dealing with a pointer to function that
4864  // may take block argument types (which will be handled below).
4865  if (*startBuf == '^') {
4866    // Replace the '^' with '*', computing a negative offset.
4867    DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4868    ReplaceText(DeclLoc, 1, "*");
4869  }
4870  if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4871    // Replace the '^' with '*' for arguments.
4872    DeclLoc = ND->getLocation();
4873    startBuf = SM->getCharacterData(DeclLoc);
4874    const char *argListBegin, *argListEnd;
4875    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4876    while (argListBegin < argListEnd) {
4877      if (*argListBegin == '^') {
4878        SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4879        ReplaceText(CaretLoc, 1, "*");
4880      }
4881      argListBegin++;
4882    }
4883  }
4884  return;
4885}
4886
4887
4888/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4889/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4890///                    struct Block_byref_id_object *src) {
4891///  _Block_object_assign (&_dest->object, _src->object,
4892///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4893///                        [|BLOCK_FIELD_IS_WEAK]) // object
4894///  _Block_object_assign(&_dest->object, _src->object,
4895///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4896///                       [|BLOCK_FIELD_IS_WEAK]) // block
4897/// }
4898/// And:
4899/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4900///  _Block_object_dispose(_src->object,
4901///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4902///                        [|BLOCK_FIELD_IS_WEAK]) // object
4903///  _Block_object_dispose(_src->object,
4904///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4905///                         [|BLOCK_FIELD_IS_WEAK]) // block
4906/// }
4907
4908std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4909                                                          int flag) {
4910  std::string S;
4911  if (CopyDestroyCache.count(flag))
4912    return S;
4913  CopyDestroyCache.insert(flag);
4914  S = "static void __Block_byref_id_object_copy_";
4915  S += utostr(flag);
4916  S += "(void *dst, void *src) {\n";
4917
4918  // offset into the object pointer is computed as:
4919  // void * + void* + int + int + void* + void *
4920  unsigned IntSize =
4921  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4922  unsigned VoidPtrSize =
4923  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4924
4925  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4926  S += " _Block_object_assign((char*)dst + ";
4927  S += utostr(offset);
4928  S += ", *(void * *) ((char*)src + ";
4929  S += utostr(offset);
4930  S += "), ";
4931  S += utostr(flag);
4932  S += ");\n}\n";
4933
4934  S += "static void __Block_byref_id_object_dispose_";
4935  S += utostr(flag);
4936  S += "(void *src) {\n";
4937  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4938  S += utostr(offset);
4939  S += "), ";
4940  S += utostr(flag);
4941  S += ");\n}\n";
4942  return S;
4943}
4944
4945/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4946/// the declaration into:
4947/// struct __Block_byref_ND {
4948/// void *__isa;                  // NULL for everything except __weak pointers
4949/// struct __Block_byref_ND *__forwarding;
4950/// int32_t __flags;
4951/// int32_t __size;
4952/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4953/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4954/// typex ND;
4955/// };
4956///
4957/// It then replaces declaration of ND variable with:
4958/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4959///                               __size=sizeof(struct __Block_byref_ND),
4960///                               ND=initializer-if-any};
4961///
4962///
4963void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4964  // Insert declaration for the function in which block literal is
4965  // used.
4966  if (CurFunctionDeclToDeclareForBlock)
4967    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4968  int flag = 0;
4969  int isa = 0;
4970  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4971  if (DeclLoc.isInvalid())
4972    // If type location is missing, it is because of missing type (a warning).
4973    // Use variable's location which is good for this case.
4974    DeclLoc = ND->getLocation();
4975  const char *startBuf = SM->getCharacterData(DeclLoc);
4976  SourceLocation X = ND->getLocEnd();
4977  X = SM->getInstantiationLoc(X);
4978  const char *endBuf = SM->getCharacterData(X);
4979  std::string Name(ND->getNameAsString());
4980  std::string ByrefType;
4981  RewriteByRefString(ByrefType, Name, ND);
4982  ByrefType += " {\n";
4983  ByrefType += "  void *__isa;\n";
4984  RewriteByRefString(ByrefType, Name, ND);
4985  ByrefType += " *__forwarding;\n";
4986  ByrefType += " int __flags;\n";
4987  ByrefType += " int __size;\n";
4988  // Add void *__Block_byref_id_object_copy;
4989  // void *__Block_byref_id_object_dispose; if needed.
4990  QualType Ty = ND->getType();
4991  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4992  if (HasCopyAndDispose) {
4993    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4994    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4995  }
4996
4997  Ty.getAsStringInternal(Name, Context->PrintingPolicy);
4998  ByrefType += " " + Name + ";\n";
4999  ByrefType += "};\n";
5000  // Insert this type in global scope. It is needed by helper function.
5001  SourceLocation FunLocStart;
5002  if (CurFunctionDef)
5003     FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5004  else {
5005    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5006    FunLocStart = CurMethodDef->getLocStart();
5007  }
5008  InsertText(FunLocStart, ByrefType);
5009  if (Ty.isObjCGCWeak()) {
5010    flag |= BLOCK_FIELD_IS_WEAK;
5011    isa = 1;
5012  }
5013
5014  if (HasCopyAndDispose) {
5015    flag = BLOCK_BYREF_CALLER;
5016    QualType Ty = ND->getType();
5017    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5018    if (Ty->isBlockPointerType())
5019      flag |= BLOCK_FIELD_IS_BLOCK;
5020    else
5021      flag |= BLOCK_FIELD_IS_OBJECT;
5022    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5023    if (!HF.empty())
5024      InsertText(FunLocStart, HF);
5025  }
5026
5027  // struct __Block_byref_ND ND =
5028  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5029  //  initializer-if-any};
5030  bool hasInit = (ND->getInit() != 0);
5031  unsigned flags = 0;
5032  if (HasCopyAndDispose)
5033    flags |= BLOCK_HAS_COPY_DISPOSE;
5034  Name = ND->getNameAsString();
5035  ByrefType.clear();
5036  RewriteByRefString(ByrefType, Name, ND);
5037  std::string ForwardingCastType("(");
5038  ForwardingCastType += ByrefType + " *)";
5039  if (!hasInit) {
5040    ByrefType += " " + Name + " = {(void*)";
5041    ByrefType += utostr(isa);
5042    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5043    ByrefType += utostr(flags);
5044    ByrefType += ", ";
5045    ByrefType += "sizeof(";
5046    RewriteByRefString(ByrefType, Name, ND);
5047    ByrefType += ")";
5048    if (HasCopyAndDispose) {
5049      ByrefType += ", __Block_byref_id_object_copy_";
5050      ByrefType += utostr(flag);
5051      ByrefType += ", __Block_byref_id_object_dispose_";
5052      ByrefType += utostr(flag);
5053    }
5054    ByrefType += "};\n";
5055    ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
5056  }
5057  else {
5058    SourceLocation startLoc;
5059    Expr *E = ND->getInit();
5060    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5061      startLoc = ECE->getLParenLoc();
5062    else
5063      startLoc = E->getLocStart();
5064    startLoc = SM->getInstantiationLoc(startLoc);
5065    endBuf = SM->getCharacterData(startLoc);
5066    ByrefType += " " + Name;
5067    ByrefType += " = {(void*)";
5068    ByrefType += utostr(isa);
5069    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5070    ByrefType += utostr(flags);
5071    ByrefType += ", ";
5072    ByrefType += "sizeof(";
5073    RewriteByRefString(ByrefType, Name, ND);
5074    ByrefType += "), ";
5075    if (HasCopyAndDispose) {
5076      ByrefType += "__Block_byref_id_object_copy_";
5077      ByrefType += utostr(flag);
5078      ByrefType += ", __Block_byref_id_object_dispose_";
5079      ByrefType += utostr(flag);
5080      ByrefType += ", ";
5081    }
5082    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5083
5084    // Complete the newly synthesized compound expression by inserting a right
5085    // curly brace before the end of the declaration.
5086    // FIXME: This approach avoids rewriting the initializer expression. It
5087    // also assumes there is only one declarator. For example, the following
5088    // isn't currently supported by this routine (in general):
5089    //
5090    // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5091    //
5092    const char *startInitializerBuf = SM->getCharacterData(startLoc);
5093    const char *semiBuf = strchr(startInitializerBuf, ';');
5094    assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5095    SourceLocation semiLoc =
5096      startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
5097
5098    InsertText(semiLoc, "}");
5099  }
5100  return;
5101}
5102
5103void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5104  // Add initializers for any closure decl refs.
5105  GetBlockDeclRefExprs(Exp->getBody());
5106  if (BlockDeclRefs.size()) {
5107    // Unique all "by copy" declarations.
5108    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5109      if (!BlockDeclRefs[i]->isByRef()) {
5110        if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5111          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5112          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5113        }
5114      }
5115    // Unique all "by ref" declarations.
5116    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5117      if (BlockDeclRefs[i]->isByRef()) {
5118        if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5119          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5120          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5121        }
5122      }
5123    // Find any imported blocks...they will need special attention.
5124    for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5125      if (BlockDeclRefs[i]->isByRef() ||
5126          BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5127          BlockDeclRefs[i]->getType()->isBlockPointerType())
5128        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5129  }
5130}
5131
5132FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
5133  IdentifierInfo *ID = &Context->Idents.get(name);
5134  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5135  return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
5136                              ID, FType, 0, SC_Extern,
5137                              SC_None, false, false);
5138}
5139
5140Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5141          const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
5142  Blocks.push_back(Exp);
5143
5144  CollectBlockDeclRefInfo(Exp);
5145
5146  // Add inner imported variables now used in current block.
5147 int countOfInnerDecls = 0;
5148  if (!InnerBlockDeclRefs.empty()) {
5149    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5150      BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5151      ValueDecl *VD = Exp->getDecl();
5152      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
5153      // We need to save the copied-in variables in nested
5154      // blocks because it is needed at the end for some of the API generations.
5155      // See SynthesizeBlockLiterals routine.
5156        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5157        BlockDeclRefs.push_back(Exp);
5158        BlockByCopyDeclsPtrSet.insert(VD);
5159        BlockByCopyDecls.push_back(VD);
5160      }
5161      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5162        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5163        BlockDeclRefs.push_back(Exp);
5164        BlockByRefDeclsPtrSet.insert(VD);
5165        BlockByRefDecls.push_back(VD);
5166      }
5167    }
5168    // Find any imported blocks...they will need special attention.
5169    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5170      if (InnerBlockDeclRefs[i]->isByRef() ||
5171          InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5172          InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5173        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5174  }
5175  InnerDeclRefsCount.push_back(countOfInnerDecls);
5176
5177  std::string FuncName;
5178
5179  if (CurFunctionDef)
5180    FuncName = CurFunctionDef->getNameAsString();
5181  else if (CurMethodDef)
5182    BuildUniqueMethodName(FuncName, CurMethodDef);
5183  else if (GlobalVarDecl)
5184    FuncName = std::string(GlobalVarDecl->getNameAsString());
5185
5186  std::string BlockNumber = utostr(Blocks.size()-1);
5187
5188  std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5189  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5190
5191  // Get a pointer to the function type so we can cast appropriately.
5192  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5193  QualType FType = Context->getPointerType(BFT);
5194
5195  FunctionDecl *FD;
5196  Expr *NewRep;
5197
5198  // Simulate a contructor call...
5199  FD = SynthBlockInitFunctionDecl(Tag);
5200  DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
5201
5202  llvm::SmallVector<Expr*, 4> InitExprs;
5203
5204  // Initialize the block function.
5205  FD = SynthBlockInitFunctionDecl(Func);
5206  DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5207                                               SourceLocation());
5208  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5209                                                CK_Unknown, Arg);
5210  InitExprs.push_back(castExpr);
5211
5212  // Initialize the block descriptor.
5213  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5214
5215  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5216                                    &Context->Idents.get(DescData.c_str()),
5217                                    Context->VoidPtrTy, 0,
5218                                    SC_Static, SC_None);
5219  UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5220                                  new (Context) DeclRefExpr(NewVD,
5221                                    Context->VoidPtrTy, SourceLocation()),
5222                                  UO_AddrOf,
5223                                  Context->getPointerType(Context->VoidPtrTy),
5224                                  SourceLocation());
5225  InitExprs.push_back(DescRefExpr);
5226
5227  // Add initializers for any closure decl refs.
5228  if (BlockDeclRefs.size()) {
5229    Expr *Exp;
5230    // Output all "by copy" declarations.
5231    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5232         E = BlockByCopyDecls.end(); I != E; ++I) {
5233      if (isObjCType((*I)->getType())) {
5234        // FIXME: Conform to ABI ([[obj retain] autorelease]).
5235        FD = SynthBlockInitFunctionDecl((*I)->getName());
5236        Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5237        if (HasLocalVariableExternalStorage(*I)) {
5238          QualType QT = (*I)->getType();
5239          QT = Context->getPointerType(QT);
5240          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
5241                                            SourceLocation());
5242        }
5243      } else if (isTopLevelBlockPointerType((*I)->getType())) {
5244        FD = SynthBlockInitFunctionDecl((*I)->getName());
5245        Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5246        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5247                                       CK_Unknown, Arg);
5248      } else {
5249        FD = SynthBlockInitFunctionDecl((*I)->getName());
5250        Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5251        if (HasLocalVariableExternalStorage(*I)) {
5252          QualType QT = (*I)->getType();
5253          QT = Context->getPointerType(QT);
5254          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
5255                                            SourceLocation());
5256        }
5257
5258      }
5259      InitExprs.push_back(Exp);
5260    }
5261    // Output all "by ref" declarations.
5262    for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5263         E = BlockByRefDecls.end(); I != E; ++I) {
5264      ValueDecl *ND = (*I);
5265      std::string Name(ND->getNameAsString());
5266      std::string RecName;
5267      RewriteByRefString(RecName, Name, ND);
5268      IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5269                                                + sizeof("struct"));
5270      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5271                                          SourceLocation(), II);
5272      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5273      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5274
5275      FD = SynthBlockInitFunctionDecl((*I)->getName());
5276      Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5277      Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5278                              Context->getPointerType(Exp->getType()),
5279                              SourceLocation());
5280      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
5281      InitExprs.push_back(Exp);
5282    }
5283  }
5284  if (ImportedBlockDecls.size()) {
5285    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5286    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5287    unsigned IntSize =
5288      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5289    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5290                                           Context->IntTy, SourceLocation());
5291    InitExprs.push_back(FlagExp);
5292  }
5293  NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5294                                  FType, SourceLocation());
5295  NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5296                             Context->getPointerType(NewRep->getType()),
5297                             SourceLocation());
5298  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
5299                                    NewRep);
5300  BlockDeclRefs.clear();
5301  BlockByRefDecls.clear();
5302  BlockByRefDeclsPtrSet.clear();
5303  BlockByCopyDecls.clear();
5304  BlockByCopyDeclsPtrSet.clear();
5305  ImportedBlockDecls.clear();
5306  return NewRep;
5307}
5308
5309//===----------------------------------------------------------------------===//
5310// Function Body / Expression rewriting
5311//===----------------------------------------------------------------------===//
5312
5313// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5314// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5315// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5316// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5317// Since the rewriter isn't capable of rewriting rewritten code, it's important
5318// we get this right.
5319void RewriteObjC::CollectPropertySetters(Stmt *S) {
5320  // Perform a bottom up traversal of all children.
5321  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5322       CI != E; ++CI)
5323    if (*CI)
5324      CollectPropertySetters(*CI);
5325
5326  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5327    if (BinOp->isAssignmentOp()) {
5328      if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5329        PropSetters[PRE] = BinOp;
5330    }
5331  }
5332}
5333
5334Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5335  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5336      isa<DoStmt>(S) || isa<ForStmt>(S))
5337    Stmts.push_back(S);
5338  else if (isa<ObjCForCollectionStmt>(S)) {
5339    Stmts.push_back(S);
5340    ObjCBcLabelNo.push_back(++BcLabelCount);
5341  }
5342
5343  SourceRange OrigStmtRange = S->getSourceRange();
5344
5345  // Perform a bottom up rewrite of all children.
5346  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5347       CI != E; ++CI)
5348    if (*CI) {
5349      Stmt *newStmt;
5350      Stmt *S = (*CI);
5351      if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5352        Expr *OldBase = IvarRefExpr->getBase();
5353        bool replaced = false;
5354        newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5355        if (replaced) {
5356          if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5357            ReplaceStmt(OldBase, IRE->getBase());
5358          else
5359            ReplaceStmt(S, newStmt);
5360        }
5361      }
5362      else
5363        newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
5364      if (newStmt)
5365        *CI = newStmt;
5366      // If dealing with an assignment with LHS being a property reference
5367      // expression, the entire assignment tree is rewritten into a property
5368      // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5369      // RHS again.
5370      if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(S))
5371        if (PropSetters[PRE]) {
5372          ++CI;
5373          continue;
5374        }
5375    }
5376
5377  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5378    llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
5379    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5380    InnerContexts.insert(BE->getBlockDecl());
5381    ImportedLocalExternalDecls.clear();
5382    GetInnerBlockDeclRefExprs(BE->getBody(),
5383                              InnerBlockDeclRefs, InnerContexts);
5384    // Rewrite the block body in place.
5385    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5386    ImportedLocalExternalDecls.clear();
5387    // Now we snarf the rewritten text and stash it away for later use.
5388    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5389    RewrittenBlockExprs[BE] = Str;
5390
5391    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5392
5393    //blockTranscribed->dump();
5394    ReplaceStmt(S, blockTranscribed);
5395    return blockTranscribed;
5396  }
5397  // Handle specific things.
5398  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5399    return RewriteAtEncode(AtEncode);
5400
5401  if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5402    BinaryOperator *BinOp = PropSetters[PropRefExpr];
5403    if (BinOp) {
5404      // Because the rewriter doesn't allow us to rewrite rewritten code,
5405      // we need to rewrite the right hand side prior to rewriting the setter.
5406      DisableReplaceStmt = true;
5407      // Save the source range. Even if we disable the replacement, the
5408      // rewritten node will have been inserted into the tree. If the synthesized
5409      // node is at the 'end', the rewriter will fail. Consider this:
5410      //    self.errorHandler = handler ? handler :
5411      //              ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5412      SourceRange SrcRange = BinOp->getSourceRange();
5413      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
5414      DisableReplaceStmt = false;
5415      //
5416      // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5417      // we changed the RHS of BinOp, the rewriter would fail (since it needs
5418      // to see the original expression). Consider this example:
5419      //
5420      // Foo *obj1, *obj2;
5421      //
5422      // obj1.i = [obj2 rrrr];
5423      //
5424      // 'BinOp' for the previous expression looks like:
5425      //
5426      // (BinaryOperator 0x231ccf0 'int' '='
5427      //   (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5428      //     (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5429      //   (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5430      //     (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5431      //
5432      // 'newStmt' represents the rewritten message expression. For example:
5433      //
5434      // (CallExpr 0x231d300 'id':'struct objc_object *'
5435      //   (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5436      //     (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5437      //       (CStyleCastExpr 0x231d220 'void *'
5438      //         (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5439      //
5440      // Note that 'newStmt' is passed to RewritePropertySetter so that it
5441      // can be used as the setter argument. ReplaceStmt() will still 'see'
5442      // the original RHS (since we haven't altered BinOp).
5443      //
5444      // This implies the Rewrite* routines can no longer delete the original
5445      // node. As a result, we now leak the original AST nodes.
5446      //
5447      return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
5448    } else {
5449      return RewritePropertyGetter(PropRefExpr);
5450    }
5451  }
5452  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5453    return RewriteAtSelector(AtSelector);
5454
5455  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5456    return RewriteObjCStringLiteral(AtString);
5457
5458  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5459#if 0
5460    // Before we rewrite it, put the original message expression in a comment.
5461    SourceLocation startLoc = MessExpr->getLocStart();
5462    SourceLocation endLoc = MessExpr->getLocEnd();
5463
5464    const char *startBuf = SM->getCharacterData(startLoc);
5465    const char *endBuf = SM->getCharacterData(endLoc);
5466
5467    std::string messString;
5468    messString += "// ";
5469    messString.append(startBuf, endBuf-startBuf+1);
5470    messString += "\n";
5471
5472    // FIXME: Missing definition of
5473    // InsertText(clang::SourceLocation, char const*, unsigned int).
5474    // InsertText(startLoc, messString.c_str(), messString.size());
5475    // Tried this, but it didn't work either...
5476    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5477#endif
5478    return RewriteMessageExpr(MessExpr);
5479  }
5480
5481  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5482    return RewriteObjCTryStmt(StmtTry);
5483
5484  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5485    return RewriteObjCSynchronizedStmt(StmtTry);
5486
5487  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5488    return RewriteObjCThrowStmt(StmtThrow);
5489
5490  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5491    return RewriteObjCProtocolExpr(ProtocolExp);
5492
5493  if (ObjCForCollectionStmt *StmtForCollection =
5494        dyn_cast<ObjCForCollectionStmt>(S))
5495    return RewriteObjCForCollectionStmt(StmtForCollection,
5496                                        OrigStmtRange.getEnd());
5497  if (BreakStmt *StmtBreakStmt =
5498      dyn_cast<BreakStmt>(S))
5499    return RewriteBreakStmt(StmtBreakStmt);
5500  if (ContinueStmt *StmtContinueStmt =
5501      dyn_cast<ContinueStmt>(S))
5502    return RewriteContinueStmt(StmtContinueStmt);
5503
5504  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5505  // and cast exprs.
5506  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5507    // FIXME: What we're doing here is modifying the type-specifier that
5508    // precedes the first Decl.  In the future the DeclGroup should have
5509    // a separate type-specifier that we can rewrite.
5510    // NOTE: We need to avoid rewriting the DeclStmt if it is within
5511    // the context of an ObjCForCollectionStmt. For example:
5512    //   NSArray *someArray;
5513    //   for (id <FooProtocol> index in someArray) ;
5514    // This is because RewriteObjCForCollectionStmt() does textual rewriting
5515    // and it depends on the original text locations/positions.
5516    if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
5517      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5518
5519    // Blocks rewrite rules.
5520    for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5521         DI != DE; ++DI) {
5522      Decl *SD = *DI;
5523      if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5524        if (isTopLevelBlockPointerType(ND->getType()))
5525          RewriteBlockPointerDecl(ND);
5526        else if (ND->getType()->isFunctionPointerType())
5527          CheckFunctionPointerDecl(ND->getType(), ND);
5528        if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5529          if (VD->hasAttr<BlocksAttr>()) {
5530            static unsigned uniqueByrefDeclCount = 0;
5531            assert(!BlockByRefDeclNo.count(ND) &&
5532              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5533            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5534            RewriteByRefVar(VD);
5535          }
5536          else
5537            RewriteTypeOfDecl(VD);
5538        }
5539      }
5540      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
5541        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5542          RewriteBlockPointerDecl(TD);
5543        else if (TD->getUnderlyingType()->isFunctionPointerType())
5544          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5545      }
5546    }
5547  }
5548
5549  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5550    RewriteObjCQualifiedInterfaceTypes(CE);
5551
5552  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5553      isa<DoStmt>(S) || isa<ForStmt>(S)) {
5554    assert(!Stmts.empty() && "Statement stack is empty");
5555    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5556             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5557            && "Statement stack mismatch");
5558    Stmts.pop_back();
5559  }
5560  // Handle blocks rewriting.
5561  if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5562    if (BDRE->isByRef())
5563      return RewriteBlockDeclRefExpr(BDRE);
5564  }
5565  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5566    ValueDecl *VD = DRE->getDecl();
5567    if (VD->hasAttr<BlocksAttr>())
5568      return RewriteBlockDeclRefExpr(DRE);
5569    if (HasLocalVariableExternalStorage(VD))
5570      return RewriteLocalVariableExternalStorage(DRE);
5571  }
5572
5573  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5574    if (CE->getCallee()->getType()->isBlockPointerType()) {
5575      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5576      ReplaceStmt(S, BlockCall);
5577      return BlockCall;
5578    }
5579  }
5580  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5581    RewriteCastExpr(CE);
5582  }
5583#if 0
5584  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5585    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5586                                                   ICE->getSubExpr(),
5587                                                   SourceLocation());
5588    // Get the new text.
5589    std::string SStr;
5590    llvm::raw_string_ostream Buf(SStr);
5591    Replacement->printPretty(Buf, *Context);
5592    const std::string &Str = Buf.str();
5593
5594    printf("CAST = %s\n", &Str[0]);
5595    InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5596    delete S;
5597    return Replacement;
5598  }
5599#endif
5600  // Return this stmt unmodified.
5601  return S;
5602}
5603
5604void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5605  for (RecordDecl::field_iterator i = RD->field_begin(),
5606                                  e = RD->field_end(); i != e; ++i) {
5607    FieldDecl *FD = *i;
5608    if (isTopLevelBlockPointerType(FD->getType()))
5609      RewriteBlockPointerDecl(FD);
5610    if (FD->getType()->isObjCQualifiedIdType() ||
5611        FD->getType()->isObjCQualifiedInterfaceType())
5612      RewriteObjCQualifiedInterfaceTypes(FD);
5613  }
5614}
5615
5616/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5617/// main file of the input.
5618void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5619  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5620    if (FD->isOverloadedOperator())
5621      return;
5622
5623    // Since function prototypes don't have ParmDecl's, we check the function
5624    // prototype. This enables us to rewrite function declarations and
5625    // definitions using the same code.
5626    RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5627
5628    // FIXME: If this should support Obj-C++, support CXXTryStmt
5629    if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5630      CurFunctionDef = FD;
5631      CurFunctionDeclToDeclareForBlock = FD;
5632      CollectPropertySetters(Body);
5633      CurrentBody = Body;
5634      Body =
5635       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5636      FD->setBody(Body);
5637      CurrentBody = 0;
5638      if (PropParentMap) {
5639        delete PropParentMap;
5640        PropParentMap = 0;
5641      }
5642      // This synthesizes and inserts the block "impl" struct, invoke function,
5643      // and any copy/dispose helper functions.
5644      InsertBlockLiteralsWithinFunction(FD);
5645      CurFunctionDef = 0;
5646      CurFunctionDeclToDeclareForBlock = 0;
5647    }
5648    return;
5649  }
5650  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
5651    if (CompoundStmt *Body = MD->getCompoundBody()) {
5652      CurMethodDef = MD;
5653      CollectPropertySetters(Body);
5654      CurrentBody = Body;
5655      Body =
5656       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5657      MD->setBody(Body);
5658      CurrentBody = 0;
5659      if (PropParentMap) {
5660        delete PropParentMap;
5661        PropParentMap = 0;
5662      }
5663      InsertBlockLiteralsWithinMethod(MD);
5664      CurMethodDef = 0;
5665    }
5666  }
5667  if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5668    ClassImplementation.push_back(CI);
5669  else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5670    CategoryImplementation.push_back(CI);
5671  else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5672    RewriteForwardClassDecl(CD);
5673  else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5674    RewriteObjCQualifiedInterfaceTypes(VD);
5675    if (isTopLevelBlockPointerType(VD->getType()))
5676      RewriteBlockPointerDecl(VD);
5677    else if (VD->getType()->isFunctionPointerType()) {
5678      CheckFunctionPointerDecl(VD->getType(), VD);
5679      if (VD->getInit()) {
5680        if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5681          RewriteCastExpr(CE);
5682        }
5683      }
5684    } else if (VD->getType()->isRecordType()) {
5685      RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5686      if (RD->isDefinition())
5687        RewriteRecordBody(RD);
5688    }
5689    if (VD->getInit()) {
5690      GlobalVarDecl = VD;
5691      CollectPropertySetters(VD->getInit());
5692      CurrentBody = VD->getInit();
5693      RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5694      CurrentBody = 0;
5695      if (PropParentMap) {
5696        delete PropParentMap;
5697        PropParentMap = 0;
5698      }
5699      SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
5700                              VD->getName());
5701      GlobalVarDecl = 0;
5702
5703      // This is needed for blocks.
5704      if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5705        RewriteCastExpr(CE);
5706      }
5707    }
5708    return;
5709  }
5710  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
5711    if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5712      RewriteBlockPointerDecl(TD);
5713    else if (TD->getUnderlyingType()->isFunctionPointerType())
5714      CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5715    return;
5716  }
5717  if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
5718    if (RD->isDefinition())
5719      RewriteRecordBody(RD);
5720    return;
5721  }
5722  // Nothing yet.
5723}
5724
5725void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
5726  if (Diags.hasErrorOccurred())
5727    return;
5728
5729  RewriteInclude();
5730
5731  // Here's a great place to add any extra declarations that may be needed.
5732  // Write out meta data for each @protocol(<expr>).
5733  for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5734       E = ProtocolExprDecls.end(); I != E; ++I)
5735    RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5736
5737  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5738  if (ClassImplementation.size() || CategoryImplementation.size())
5739    RewriteImplementations();
5740
5741  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5742  // we are done.
5743  if (const RewriteBuffer *RewriteBuf =
5744      Rewrite.getRewriteBufferFor(MainFileID)) {
5745    //printf("Changed:\n");
5746    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5747  } else {
5748    llvm::errs() << "No changes\n";
5749  }
5750
5751  if (ClassImplementation.size() || CategoryImplementation.size() ||
5752      ProtocolExprDecls.size()) {
5753    // Rewrite Objective-c meta data*
5754    std::string ResultStr;
5755    SynthesizeMetaDataIntoBuffer(ResultStr);
5756    // Emit metadata.
5757    *OutFile << ResultStr;
5758  }
5759  OutFile->flush();
5760}
5761