clang API Documentation

RewriteObjC.cpp
Go to the documentation of this file.
00001 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Hacks and fun related to the code rewriter.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Rewrite/ASTConsumers.h"
00015 #include "clang/Rewrite/Rewriter.h"
00016 #include "clang/AST/AST.h"
00017 #include "clang/AST/ASTConsumer.h"
00018 #include "clang/AST/ParentMap.h"
00019 #include "clang/Basic/SourceManager.h"
00020 #include "clang/Basic/IdentifierTable.h"
00021 #include "clang/Basic/Diagnostic.h"
00022 #include "clang/Lex/Lexer.h"
00023 #include "llvm/Support/MemoryBuffer.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/ADT/SmallPtrSet.h"
00027 #include "llvm/ADT/OwningPtr.h"
00028 #include "llvm/ADT/DenseSet.h"
00029 
00030 using namespace clang;
00031 using llvm::utostr;
00032 
00033 namespace {
00034   class RewriteObjC : public ASTConsumer {
00035   protected:
00036     
00037     enum {
00038       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
00039                                         block, ... */
00040       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
00041       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the 
00042                                         __block variable */
00043       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
00044                                         helpers */
00045       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
00046                                         support routines */
00047       BLOCK_BYREF_CURRENT_MAX = 256
00048     };
00049     
00050     enum {
00051       BLOCK_NEEDS_FREE =        (1 << 24),
00052       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
00053       BLOCK_HAS_CXX_OBJ =       (1 << 26),
00054       BLOCK_IS_GC =             (1 << 27),
00055       BLOCK_IS_GLOBAL =         (1 << 28),
00056       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
00057     };
00058     static const int OBJC_ABI_VERSION = 7;
00059     
00060     Rewriter Rewrite;
00061     DiagnosticsEngine &Diags;
00062     const LangOptions &LangOpts;
00063     ASTContext *Context;
00064     SourceManager *SM;
00065     TranslationUnitDecl *TUDecl;
00066     FileID MainFileID;
00067     const char *MainFileStart, *MainFileEnd;
00068     Stmt *CurrentBody;
00069     ParentMap *PropParentMap; // created lazily.
00070     std::string InFileName;
00071     raw_ostream* OutFile;
00072     std::string Preamble;
00073     
00074     TypeDecl *ProtocolTypeDecl;
00075     VarDecl *GlobalVarDecl;
00076     unsigned RewriteFailedDiag;
00077     // ObjC string constant support.
00078     unsigned NumObjCStringLiterals;
00079     VarDecl *ConstantStringClassReference;
00080     RecordDecl *NSStringRecord;
00081 
00082     // ObjC foreach break/continue generation support.
00083     int BcLabelCount;
00084     
00085     unsigned TryFinallyContainsReturnDiag;
00086     // Needed for super.
00087     ObjCMethodDecl *CurMethodDef;
00088     RecordDecl *SuperStructDecl;
00089     RecordDecl *ConstantStringDecl;
00090     
00091     FunctionDecl *MsgSendFunctionDecl;
00092     FunctionDecl *MsgSendSuperFunctionDecl;
00093     FunctionDecl *MsgSendStretFunctionDecl;
00094     FunctionDecl *MsgSendSuperStretFunctionDecl;
00095     FunctionDecl *MsgSendFpretFunctionDecl;
00096     FunctionDecl *GetClassFunctionDecl;
00097     FunctionDecl *GetMetaClassFunctionDecl;
00098     FunctionDecl *GetSuperClassFunctionDecl;
00099     FunctionDecl *SelGetUidFunctionDecl;
00100     FunctionDecl *CFStringFunctionDecl;
00101     FunctionDecl *SuperContructorFunctionDecl;
00102     FunctionDecl *CurFunctionDef;
00103     FunctionDecl *CurFunctionDeclToDeclareForBlock;
00104 
00105     /* Misc. containers needed for meta-data rewrite. */
00106     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
00107     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
00108     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
00109     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
00110     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
00111     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
00112     SmallVector<Stmt *, 32> Stmts;
00113     SmallVector<int, 8> ObjCBcLabelNo;
00114     // Remember all the @protocol(<expr>) expressions.
00115     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
00116     
00117     llvm::DenseSet<uint64_t> CopyDestroyCache;
00118 
00119     // Block expressions.
00120     SmallVector<BlockExpr *, 32> Blocks;
00121     SmallVector<int, 32> InnerDeclRefsCount;
00122     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
00123     
00124     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
00125 
00126     // Block related declarations.
00127     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
00128     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
00129     SmallVector<ValueDecl *, 8> BlockByRefDecls;
00130     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
00131     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
00132     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
00133     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
00134     
00135     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
00136 
00137     // This maps an original source AST to it's rewritten form. This allows
00138     // us to avoid rewriting the same node twice (which is very uncommon).
00139     // This is needed to support some of the exotic property rewriting.
00140     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
00141 
00142     // Needed for header files being rewritten
00143     bool IsHeader;
00144     bool SilenceRewriteMacroWarning;
00145     bool objc_impl_method;
00146     
00147     bool DisableReplaceStmt;
00148     class DisableReplaceStmtScope {
00149       RewriteObjC &R;
00150       bool SavedValue;
00151     
00152     public:
00153       DisableReplaceStmtScope(RewriteObjC &R)
00154         : R(R), SavedValue(R.DisableReplaceStmt) {
00155         R.DisableReplaceStmt = true;
00156       }
00157       ~DisableReplaceStmtScope() {
00158         R.DisableReplaceStmt = SavedValue;
00159       }
00160     };
00161     void InitializeCommon(ASTContext &context);
00162 
00163   public:
00164 
00165     // Top Level Driver code.
00166     virtual bool HandleTopLevelDecl(DeclGroupRef D) {
00167       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
00168         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
00169           if (!Class->isThisDeclarationADefinition()) {
00170             RewriteForwardClassDecl(D);
00171             break;
00172           }
00173         }
00174 
00175         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
00176           if (!Proto->isThisDeclarationADefinition()) {
00177             RewriteForwardProtocolDecl(D);
00178             break;
00179           }
00180         }
00181 
00182         HandleTopLevelSingleDecl(*I);
00183       }
00184       return true;
00185     }
00186     void HandleTopLevelSingleDecl(Decl *D);
00187     void HandleDeclInMainFile(Decl *D);
00188     RewriteObjC(std::string inFile, raw_ostream *OS,
00189                 DiagnosticsEngine &D, const LangOptions &LOpts,
00190                 bool silenceMacroWarn);
00191 
00192     ~RewriteObjC() {}
00193 
00194     virtual void HandleTranslationUnit(ASTContext &C);
00195 
00196     void ReplaceStmt(Stmt *Old, Stmt *New) {
00197       Stmt *ReplacingStmt = ReplacedNodes[Old];
00198 
00199       if (ReplacingStmt)
00200         return; // We can't rewrite the same node twice.
00201 
00202       if (DisableReplaceStmt)
00203         return;
00204 
00205       // If replacement succeeded or warning disabled return with no warning.
00206       if (!Rewrite.ReplaceStmt(Old, New)) {
00207         ReplacedNodes[Old] = New;
00208         return;
00209       }
00210       if (SilenceRewriteMacroWarning)
00211         return;
00212       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
00213                    << Old->getSourceRange();
00214     }
00215 
00216     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
00217       if (DisableReplaceStmt)
00218         return;
00219 
00220       // Measure the old text.
00221       int Size = Rewrite.getRangeSize(SrcRange);
00222       if (Size == -1) {
00223         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
00224                      << Old->getSourceRange();
00225         return;
00226       }
00227       // Get the new text.
00228       std::string SStr;
00229       llvm::raw_string_ostream S(SStr);
00230       New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
00231       const std::string &Str = S.str();
00232 
00233       // If replacement succeeded or warning disabled return with no warning.
00234       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
00235         ReplacedNodes[Old] = New;
00236         return;
00237       }
00238       if (SilenceRewriteMacroWarning)
00239         return;
00240       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
00241                    << Old->getSourceRange();
00242     }
00243 
00244     void InsertText(SourceLocation Loc, StringRef Str,
00245                     bool InsertAfter = true) {
00246       // If insertion succeeded or warning disabled return with no warning.
00247       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
00248           SilenceRewriteMacroWarning)
00249         return;
00250 
00251       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
00252     }
00253 
00254     void ReplaceText(SourceLocation Start, unsigned OrigLength,
00255                      StringRef Str) {
00256       // If removal succeeded or warning disabled return with no warning.
00257       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
00258           SilenceRewriteMacroWarning)
00259         return;
00260 
00261       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
00262     }
00263 
00264     // Syntactic Rewriting.
00265     void RewriteRecordBody(RecordDecl *RD);
00266     void RewriteInclude();
00267     void RewriteForwardClassDecl(DeclGroupRef D);
00268     void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
00269     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 
00270                                      const std::string &typedefString);
00271     void RewriteImplementations();
00272     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
00273                                  ObjCImplementationDecl *IMD,
00274                                  ObjCCategoryImplDecl *CID);
00275     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
00276     void RewriteImplementationDecl(Decl *Dcl);
00277     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
00278                                ObjCMethodDecl *MDecl, std::string &ResultStr);
00279     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
00280                                const FunctionType *&FPRetType);
00281     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
00282                             ValueDecl *VD, bool def=false);
00283     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
00284     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
00285     void RewriteForwardProtocolDecl(DeclGroupRef D);
00286     void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
00287     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
00288     void RewriteProperty(ObjCPropertyDecl *prop);
00289     void RewriteFunctionDecl(FunctionDecl *FD);
00290     void RewriteBlockPointerType(std::string& Str, QualType Type);
00291     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
00292     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
00293     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
00294     void RewriteTypeOfDecl(VarDecl *VD);
00295     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
00296   
00297     // Expression Rewriting.
00298     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
00299     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
00300     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
00301     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
00302     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
00303     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
00304     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
00305     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
00306     void RewriteTryReturnStmts(Stmt *S);
00307     void RewriteSyncReturnStmts(Stmt *S, std::string buf);
00308     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
00309     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
00310     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
00311     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
00312                                        SourceLocation OrigEnd);
00313     Stmt *RewriteBreakStmt(BreakStmt *S);
00314     Stmt *RewriteContinueStmt(ContinueStmt *S);
00315     void RewriteCastExpr(CStyleCastExpr *CE);
00316     
00317     // Block rewriting.
00318     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
00319     
00320     // Block specific rewrite rules.
00321     void RewriteBlockPointerDecl(NamedDecl *VD);
00322     void RewriteByRefVar(VarDecl *VD);
00323     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
00324     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
00325     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
00326     
00327     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
00328                                       std::string &Result);
00329     
00330     virtual void Initialize(ASTContext &context) = 0;
00331     
00332     // Metadata Rewriting.
00333     virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
00334     virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
00335                                                  StringRef prefix,
00336                                                  StringRef ClassName,
00337                                                  std::string &Result) = 0;
00338     virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
00339                                              std::string &Result) = 0;
00340     virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
00341                                      StringRef prefix,
00342                                      StringRef ClassName,
00343                                      std::string &Result) = 0;
00344     virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
00345                                           std::string &Result) = 0;
00346     
00347     // Rewriting ivar access
00348     virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
00349     virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
00350                                          std::string &Result) = 0;
00351     
00352     // Misc. AST transformation routines. Somtimes they end up calling
00353     // rewriting routines on the new ASTs.
00354     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
00355                                            Expr **args, unsigned nargs,
00356                                            SourceLocation StartLoc=SourceLocation(),
00357                                            SourceLocation EndLoc=SourceLocation());
00358 
00359     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
00360                            SourceLocation StartLoc=SourceLocation(),
00361                            SourceLocation EndLoc=SourceLocation());
00362     
00363     void SynthCountByEnumWithState(std::string &buf);
00364     void SynthMsgSendFunctionDecl();
00365     void SynthMsgSendSuperFunctionDecl();
00366     void SynthMsgSendStretFunctionDecl();
00367     void SynthMsgSendFpretFunctionDecl();
00368     void SynthMsgSendSuperStretFunctionDecl();
00369     void SynthGetClassFunctionDecl();
00370     void SynthGetMetaClassFunctionDecl();
00371     void SynthGetSuperClassFunctionDecl();
00372     void SynthSelGetUidFunctionDecl();
00373     void SynthSuperContructorFunctionDecl();
00374     
00375     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
00376     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
00377                                       StringRef funcName, std::string Tag);
00378     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
00379                                       StringRef funcName, std::string Tag);
00380     std::string SynthesizeBlockImpl(BlockExpr *CE, 
00381                                     std::string Tag, std::string Desc);
00382     std::string SynthesizeBlockDescriptor(std::string DescTag, 
00383                                           std::string ImplTag,
00384                                           int i, StringRef funcName,
00385                                           unsigned hasCopy);
00386     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
00387     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
00388                                  StringRef FunName);
00389     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
00390     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
00391             const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
00392 
00393     // Misc. helper routines.
00394     QualType getProtocolType();
00395     void WarnAboutReturnGotoStmts(Stmt *S);
00396     void HasReturnStmts(Stmt *S, bool &hasReturns);
00397     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
00398     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
00399     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
00400 
00401     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
00402     void CollectBlockDeclRefInfo(BlockExpr *Exp);
00403     void GetBlockDeclRefExprs(Stmt *S);
00404     void GetInnerBlockDeclRefExprs(Stmt *S, 
00405                 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
00406                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
00407 
00408     // We avoid calling Type::isBlockPointerType(), since it operates on the
00409     // canonical type. We only care if the top-level type is a closure pointer.
00410     bool isTopLevelBlockPointerType(QualType T) {
00411       return isa<BlockPointerType>(T);
00412     }
00413 
00414     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
00415     /// to a function pointer type and upon success, returns true; false
00416     /// otherwise.
00417     bool convertBlockPointerToFunctionPointer(QualType &T) {
00418       if (isTopLevelBlockPointerType(T)) {
00419         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
00420         T = Context->getPointerType(BPT->getPointeeType());
00421         return true;
00422       }
00423       return false;
00424     }
00425     
00426     bool needToScanForQualifiers(QualType T);
00427     QualType getSuperStructType();
00428     QualType getConstantStringStructType();
00429     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
00430     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
00431     
00432     void convertToUnqualifiedObjCType(QualType &T) {
00433       if (T->isObjCQualifiedIdType())
00434         T = Context->getObjCIdType();
00435       else if (T->isObjCQualifiedClassType())
00436         T = Context->getObjCClassType();
00437       else if (T->isObjCObjectPointerType() &&
00438                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
00439         if (const ObjCObjectPointerType * OBJPT =
00440               T->getAsObjCInterfacePointerType()) {
00441           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
00442           T = QualType(IFaceT, 0);
00443           T = Context->getPointerType(T);
00444         }
00445      }
00446     }
00447     
00448     // FIXME: This predicate seems like it would be useful to add to ASTContext.
00449     bool isObjCType(QualType T) {
00450       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
00451         return false;
00452 
00453       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
00454 
00455       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
00456           OCT == Context->getCanonicalType(Context->getObjCClassType()))
00457         return true;
00458 
00459       if (const PointerType *PT = OCT->getAs<PointerType>()) {
00460         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
00461             PT->getPointeeType()->isObjCQualifiedIdType())
00462           return true;
00463       }
00464       return false;
00465     }
00466     bool PointerTypeTakesAnyBlockArguments(QualType QT);
00467     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
00468     void GetExtentOfArgList(const char *Name, const char *&LParen,
00469                             const char *&RParen);
00470     
00471     void QuoteDoublequotes(std::string &From, std::string &To) {
00472       for (unsigned i = 0; i < From.length(); i++) {
00473         if (From[i] == '"')
00474           To += "\\\"";
00475         else
00476           To += From[i];
00477       }
00478     }
00479 
00480     QualType getSimpleFunctionType(QualType result,
00481                                    const QualType *args,
00482                                    unsigned numArgs,
00483                                    bool variadic = false) {
00484       if (result == Context->getObjCInstanceType())
00485         result =  Context->getObjCIdType();
00486       FunctionProtoType::ExtProtoInfo fpi;
00487       fpi.Variadic = variadic;
00488       return Context->getFunctionType(result, args, numArgs, fpi);
00489     }
00490 
00491     // Helper function: create a CStyleCastExpr with trivial type source info.
00492     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
00493                                              CastKind Kind, Expr *E) {
00494       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
00495       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
00496                                     SourceLocation(), SourceLocation());
00497     }
00498   };
00499   
00500   class RewriteObjCFragileABI : public RewriteObjC {
00501   public:
00502     
00503     RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
00504                 DiagnosticsEngine &D, const LangOptions &LOpts,
00505                 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
00506                                                      D, LOpts,
00507                                                      silenceMacroWarn) {}
00508     
00509     ~RewriteObjCFragileABI() {}
00510     virtual void Initialize(ASTContext &context);
00511     
00512     // Rewriting metadata
00513     template<typename MethodIterator>
00514     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
00515                                     MethodIterator MethodEnd,
00516                                     bool IsInstanceMethod,
00517                                     StringRef prefix,
00518                                     StringRef ClassName,
00519                                     std::string &Result);
00520     virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
00521                                              StringRef prefix,
00522                                              StringRef ClassName,
00523                                              std::string &Result);
00524     virtual void RewriteObjCProtocolListMetaData(
00525                   const ObjCList<ObjCProtocolDecl> &Prots,
00526                   StringRef prefix, StringRef ClassName, std::string &Result);
00527     virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
00528                                           std::string &Result);
00529     virtual void RewriteMetaDataIntoBuffer(std::string &Result);
00530     virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
00531                                              std::string &Result);
00532     
00533     // Rewriting ivar
00534     virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
00535                                               std::string &Result);
00536     virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
00537   };
00538 }
00539 
00540 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
00541                                                    NamedDecl *D) {
00542   if (const FunctionProtoType *fproto
00543       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
00544     for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
00545          E = fproto->arg_type_end(); I && (I != E); ++I)
00546       if (isTopLevelBlockPointerType(*I)) {
00547         // All the args are checked/rewritten. Don't call twice!
00548         RewriteBlockPointerDecl(D);
00549         break;
00550       }
00551   }
00552 }
00553 
00554 void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
00555   const PointerType *PT = funcType->getAs<PointerType>();
00556   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
00557     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
00558 }
00559 
00560 static bool IsHeaderFile(const std::string &Filename) {
00561   std::string::size_type DotPos = Filename.rfind('.');
00562 
00563   if (DotPos == std::string::npos) {
00564     // no file extension
00565     return false;
00566   }
00567 
00568   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
00569   // C header: .h
00570   // C++ header: .hh or .H;
00571   return Ext == "h" || Ext == "hh" || Ext == "H";
00572 }
00573 
00574 RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
00575                          DiagnosticsEngine &D, const LangOptions &LOpts,
00576                          bool silenceMacroWarn)
00577       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
00578         SilenceRewriteMacroWarning(silenceMacroWarn) {
00579   IsHeader = IsHeaderFile(inFile);
00580   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
00581                "rewriting sub-expression within a macro (may not be correct)");
00582   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
00583                DiagnosticsEngine::Warning,
00584                "rewriter doesn't support user-specified control flow semantics "
00585                "for @try/@finally (code may not execute properly)");
00586 }
00587 
00588 ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
00589                                        raw_ostream* OS,
00590                                        DiagnosticsEngine &Diags,
00591                                        const LangOptions &LOpts,
00592                                        bool SilenceRewriteMacroWarning) {
00593   return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
00594 }
00595 
00596 void RewriteObjC::InitializeCommon(ASTContext &context) {
00597   Context = &context;
00598   SM = &Context->getSourceManager();
00599   TUDecl = Context->getTranslationUnitDecl();
00600   MsgSendFunctionDecl = 0;
00601   MsgSendSuperFunctionDecl = 0;
00602   MsgSendStretFunctionDecl = 0;
00603   MsgSendSuperStretFunctionDecl = 0;
00604   MsgSendFpretFunctionDecl = 0;
00605   GetClassFunctionDecl = 0;
00606   GetMetaClassFunctionDecl = 0;
00607   GetSuperClassFunctionDecl = 0;
00608   SelGetUidFunctionDecl = 0;
00609   CFStringFunctionDecl = 0;
00610   ConstantStringClassReference = 0;
00611   NSStringRecord = 0;
00612   CurMethodDef = 0;
00613   CurFunctionDef = 0;
00614   CurFunctionDeclToDeclareForBlock = 0;
00615   GlobalVarDecl = 0;
00616   SuperStructDecl = 0;
00617   ProtocolTypeDecl = 0;
00618   ConstantStringDecl = 0;
00619   BcLabelCount = 0;
00620   SuperContructorFunctionDecl = 0;
00621   NumObjCStringLiterals = 0;
00622   PropParentMap = 0;
00623   CurrentBody = 0;
00624   DisableReplaceStmt = false;
00625   objc_impl_method = false;
00626 
00627   // Get the ID and start/end of the main file.
00628   MainFileID = SM->getMainFileID();
00629   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
00630   MainFileStart = MainBuf->getBufferStart();
00631   MainFileEnd = MainBuf->getBufferEnd();
00632 
00633   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
00634 }
00635 
00636 //===----------------------------------------------------------------------===//
00637 // Top Level Driver Code
00638 //===----------------------------------------------------------------------===//
00639 
00640 void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
00641   if (Diags.hasErrorOccurred())
00642     return;
00643 
00644   // Two cases: either the decl could be in the main file, or it could be in a
00645   // #included file.  If the former, rewrite it now.  If the later, check to see
00646   // if we rewrote the #include/#import.
00647   SourceLocation Loc = D->getLocation();
00648   Loc = SM->getExpansionLoc(Loc);
00649 
00650   // If this is for a builtin, ignore it.
00651   if (Loc.isInvalid()) return;
00652 
00653   // Look for built-in declarations that we need to refer during the rewrite.
00654   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00655     RewriteFunctionDecl(FD);
00656   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
00657     // declared in <Foundation/NSString.h>
00658     if (FVD->getName() == "_NSConstantStringClassReference") {
00659       ConstantStringClassReference = FVD;
00660       return;
00661     }
00662   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
00663     if (ID->isThisDeclarationADefinition())
00664       RewriteInterfaceDecl(ID);
00665   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
00666     RewriteCategoryDecl(CD);
00667   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
00668     if (PD->isThisDeclarationADefinition())
00669       RewriteProtocolDecl(PD);
00670   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
00671     // Recurse into linkage specifications
00672     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
00673                                  DIEnd = LSD->decls_end();
00674          DI != DIEnd; ) {
00675       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
00676         if (!IFace->isThisDeclarationADefinition()) {
00677           SmallVector<Decl *, 8> DG;
00678           SourceLocation StartLoc = IFace->getLocStart();
00679           do {
00680             if (isa<ObjCInterfaceDecl>(*DI) &&
00681                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
00682                 StartLoc == (*DI)->getLocStart())
00683               DG.push_back(*DI);
00684             else
00685               break;
00686             
00687             ++DI;
00688           } while (DI != DIEnd);
00689           RewriteForwardClassDecl(DG);
00690           continue;
00691         }
00692       }
00693 
00694       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
00695         if (!Proto->isThisDeclarationADefinition()) {
00696           SmallVector<Decl *, 8> DG;
00697           SourceLocation StartLoc = Proto->getLocStart();
00698           do {
00699             if (isa<ObjCProtocolDecl>(*DI) &&
00700                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
00701                 StartLoc == (*DI)->getLocStart())
00702               DG.push_back(*DI);
00703             else
00704               break;
00705             
00706             ++DI;
00707           } while (DI != DIEnd);
00708           RewriteForwardProtocolDecl(DG);
00709           continue;
00710         }
00711       }
00712       
00713       HandleTopLevelSingleDecl(*DI);
00714       ++DI;
00715     }
00716   }
00717   // If we have a decl in the main file, see if we should rewrite it.
00718   if (SM->isFromMainFile(Loc))
00719     return HandleDeclInMainFile(D);
00720 }
00721 
00722 //===----------------------------------------------------------------------===//
00723 // Syntactic (non-AST) Rewriting Code
00724 //===----------------------------------------------------------------------===//
00725 
00726 void RewriteObjC::RewriteInclude() {
00727   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
00728   StringRef MainBuf = SM->getBufferData(MainFileID);
00729   const char *MainBufStart = MainBuf.begin();
00730   const char *MainBufEnd = MainBuf.end();
00731   size_t ImportLen = strlen("import");
00732 
00733   // Loop over the whole file, looking for includes.
00734   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
00735     if (*BufPtr == '#') {
00736       if (++BufPtr == MainBufEnd)
00737         return;
00738       while (*BufPtr == ' ' || *BufPtr == '\t')
00739         if (++BufPtr == MainBufEnd)
00740           return;
00741       if (!strncmp(BufPtr, "import", ImportLen)) {
00742         // replace import with include
00743         SourceLocation ImportLoc =
00744           LocStart.getLocWithOffset(BufPtr-MainBufStart);
00745         ReplaceText(ImportLoc, ImportLen, "include");
00746         BufPtr += ImportLen;
00747       }
00748     }
00749   }
00750 }
00751 
00752 static std::string getIvarAccessString(ObjCIvarDecl *OID) {
00753   const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
00754   std::string S;
00755   S = "((struct ";
00756   S += ClassDecl->getIdentifier()->getName();
00757   S += "_IMPL *)self)->";
00758   S += OID->getName();
00759   return S;
00760 }
00761 
00762 void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
00763                                           ObjCImplementationDecl *IMD,
00764                                           ObjCCategoryImplDecl *CID) {
00765   static bool objcGetPropertyDefined = false;
00766   static bool objcSetPropertyDefined = false;
00767   SourceLocation startLoc = PID->getLocStart();
00768   InsertText(startLoc, "// ");
00769   const char *startBuf = SM->getCharacterData(startLoc);
00770   assert((*startBuf == '@') && "bogus @synthesize location");
00771   const char *semiBuf = strchr(startBuf, ';');
00772   assert((*semiBuf == ';') && "@synthesize: can't find ';'");
00773   SourceLocation onePastSemiLoc =
00774     startLoc.getLocWithOffset(semiBuf-startBuf+1);
00775 
00776   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
00777     return; // FIXME: is this correct?
00778 
00779   // Generate the 'getter' function.
00780   ObjCPropertyDecl *PD = PID->getPropertyDecl();
00781   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
00782 
00783   if (!OID)
00784     return;
00785   unsigned Attributes = PD->getPropertyAttributes();
00786   if (!PD->getGetterMethodDecl()->isDefined()) {
00787     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
00788                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
00789                                          ObjCPropertyDecl::OBJC_PR_copy));
00790     std::string Getr;
00791     if (GenGetProperty && !objcGetPropertyDefined) {
00792       objcGetPropertyDefined = true;
00793       // FIXME. Is this attribute correct in all cases?
00794       Getr = "\nextern \"C\" __declspec(dllimport) "
00795             "id objc_getProperty(id, SEL, long, bool);\n";
00796     }
00797     RewriteObjCMethodDecl(OID->getContainingInterface(),  
00798                           PD->getGetterMethodDecl(), Getr);
00799     Getr += "{ ";
00800     // Synthesize an explicit cast to gain access to the ivar.
00801     // See objc-act.c:objc_synthesize_new_getter() for details.
00802     if (GenGetProperty) {
00803       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
00804       Getr += "typedef ";
00805       const FunctionType *FPRetType = 0;
00806       RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr, 
00807                             FPRetType);
00808       Getr += " _TYPE";
00809       if (FPRetType) {
00810         Getr += ")"; // close the precedence "scope" for "*".
00811       
00812         // Now, emit the argument types (if any).
00813         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
00814           Getr += "(";
00815           for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
00816             if (i) Getr += ", ";
00817             std::string ParamStr = FT->getArgType(i).getAsString(
00818                                                           Context->getPrintingPolicy());
00819             Getr += ParamStr;
00820           }
00821           if (FT->isVariadic()) {
00822             if (FT->getNumArgs()) Getr += ", ";
00823             Getr += "...";
00824           }
00825           Getr += ")";
00826         } else
00827           Getr += "()";
00828       }
00829       Getr += ";\n";
00830       Getr += "return (_TYPE)";
00831       Getr += "objc_getProperty(self, _cmd, ";
00832       RewriteIvarOffsetComputation(OID, Getr);
00833       Getr += ", 1)";
00834     }
00835     else
00836       Getr += "return " + getIvarAccessString(OID);
00837     Getr += "; }";
00838     InsertText(onePastSemiLoc, Getr);
00839   }
00840   
00841   if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
00842     return;
00843 
00844   // Generate the 'setter' function.
00845   std::string Setr;
00846   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
00847                                       ObjCPropertyDecl::OBJC_PR_copy);
00848   if (GenSetProperty && !objcSetPropertyDefined) {
00849     objcSetPropertyDefined = true;
00850     // FIXME. Is this attribute correct in all cases?
00851     Setr = "\nextern \"C\" __declspec(dllimport) "
00852     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
00853   }
00854   
00855   RewriteObjCMethodDecl(OID->getContainingInterface(), 
00856                         PD->getSetterMethodDecl(), Setr);
00857   Setr += "{ ";
00858   // Synthesize an explicit cast to initialize the ivar.
00859   // See objc-act.c:objc_synthesize_new_setter() for details.
00860   if (GenSetProperty) {
00861     Setr += "objc_setProperty (self, _cmd, ";
00862     RewriteIvarOffsetComputation(OID, Setr);
00863     Setr += ", (id)";
00864     Setr += PD->getName();
00865     Setr += ", ";
00866     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
00867       Setr += "0, ";
00868     else
00869       Setr += "1, ";
00870     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
00871       Setr += "1)";
00872     else
00873       Setr += "0)";
00874   }
00875   else {
00876     Setr += getIvarAccessString(OID) + " = ";
00877     Setr += PD->getName();
00878   }
00879   Setr += "; }";
00880   InsertText(onePastSemiLoc, Setr);
00881 }
00882 
00883 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
00884                                        std::string &typedefString) {
00885   typedefString += "#ifndef _REWRITER_typedef_";
00886   typedefString += ForwardDecl->getNameAsString();
00887   typedefString += "\n";
00888   typedefString += "#define _REWRITER_typedef_";
00889   typedefString += ForwardDecl->getNameAsString();
00890   typedefString += "\n";
00891   typedefString += "typedef struct objc_object ";
00892   typedefString += ForwardDecl->getNameAsString();
00893   typedefString += ";\n#endif\n";
00894 }
00895 
00896 void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
00897                                               const std::string &typedefString) {
00898     SourceLocation startLoc = ClassDecl->getLocStart();
00899     const char *startBuf = SM->getCharacterData(startLoc);
00900     const char *semiPtr = strchr(startBuf, ';'); 
00901     // Replace the @class with typedefs corresponding to the classes.
00902     ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);  
00903 }
00904 
00905 void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
00906   std::string typedefString;
00907   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
00908     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
00909     if (I == D.begin()) {
00910       // Translate to typedef's that forward reference structs with the same name
00911       // as the class. As a convenience, we include the original declaration
00912       // as a comment.
00913       typedefString += "// @class ";
00914       typedefString += ForwardDecl->getNameAsString();
00915       typedefString += ";\n";
00916     }
00917     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
00918   }
00919   DeclGroupRef::iterator I = D.begin();
00920   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
00921 }
00922 
00923 void RewriteObjC::RewriteForwardClassDecl(
00924                                 const llvm::SmallVector<Decl*, 8> &D) {
00925   std::string typedefString;
00926   for (unsigned i = 0; i < D.size(); i++) {
00927     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
00928     if (i == 0) {
00929       typedefString += "// @class ";
00930       typedefString += ForwardDecl->getNameAsString();
00931       typedefString += ";\n";
00932     }
00933     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
00934   }
00935   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
00936 }
00937 
00938 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
00939   // When method is a synthesized one, such as a getter/setter there is
00940   // nothing to rewrite.
00941   if (Method->isImplicit())
00942     return;
00943   SourceLocation LocStart = Method->getLocStart();
00944   SourceLocation LocEnd = Method->getLocEnd();
00945 
00946   if (SM->getExpansionLineNumber(LocEnd) >
00947       SM->getExpansionLineNumber(LocStart)) {
00948     InsertText(LocStart, "#if 0\n");
00949     ReplaceText(LocEnd, 1, ";\n#endif\n");
00950   } else {
00951     InsertText(LocStart, "// ");
00952   }
00953 }
00954 
00955 void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
00956   SourceLocation Loc = prop->getAtLoc();
00957 
00958   ReplaceText(Loc, 0, "// ");
00959   // FIXME: handle properties that are declared across multiple lines.
00960 }
00961 
00962 void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
00963   SourceLocation LocStart = CatDecl->getLocStart();
00964 
00965   // FIXME: handle category headers that are declared across multiple lines.
00966   ReplaceText(LocStart, 0, "// ");
00967 
00968   for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
00969        E = CatDecl->prop_end(); I != E; ++I)
00970     RewriteProperty(&*I);
00971   
00972   for (ObjCCategoryDecl::instmeth_iterator
00973          I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
00974        I != E; ++I)
00975     RewriteMethodDeclaration(*I);
00976   for (ObjCCategoryDecl::classmeth_iterator
00977          I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
00978        I != E; ++I)
00979     RewriteMethodDeclaration(*I);
00980 
00981   // Lastly, comment out the @end.
00982   ReplaceText(CatDecl->getAtEndRange().getBegin(), 
00983               strlen("@end"), "/* @end */");
00984 }
00985 
00986 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
00987   SourceLocation LocStart = PDecl->getLocStart();
00988   assert(PDecl->isThisDeclarationADefinition());
00989   
00990   // FIXME: handle protocol headers that are declared across multiple lines.
00991   ReplaceText(LocStart, 0, "// ");
00992 
00993   for (ObjCProtocolDecl::instmeth_iterator
00994          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
00995        I != E; ++I)
00996     RewriteMethodDeclaration(*I);
00997   for (ObjCProtocolDecl::classmeth_iterator
00998          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
00999        I != E; ++I)
01000     RewriteMethodDeclaration(*I);
01001 
01002   for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
01003        E = PDecl->prop_end(); I != E; ++I)
01004     RewriteProperty(&*I);
01005   
01006   // Lastly, comment out the @end.
01007   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
01008   ReplaceText(LocEnd, strlen("@end"), "/* @end */");
01009 
01010   // Must comment out @optional/@required
01011   const char *startBuf = SM->getCharacterData(LocStart);
01012   const char *endBuf = SM->getCharacterData(LocEnd);
01013   for (const char *p = startBuf; p < endBuf; p++) {
01014     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
01015       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
01016       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
01017 
01018     }
01019     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
01020       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
01021       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
01022 
01023     }
01024   }
01025 }
01026 
01027 void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
01028   SourceLocation LocStart = (*D.begin())->getLocStart();
01029   if (LocStart.isInvalid())
01030     llvm_unreachable("Invalid SourceLocation");
01031   // FIXME: handle forward protocol that are declared across multiple lines.
01032   ReplaceText(LocStart, 0, "// ");
01033 }
01034 
01035 void 
01036 RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
01037   SourceLocation LocStart = DG[0]->getLocStart();
01038   if (LocStart.isInvalid())
01039     llvm_unreachable("Invalid SourceLocation");
01040   // FIXME: handle forward protocol that are declared across multiple lines.
01041   ReplaceText(LocStart, 0, "// ");
01042 }
01043 
01044 void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
01045                                         const FunctionType *&FPRetType) {
01046   if (T->isObjCQualifiedIdType())
01047     ResultStr += "id";
01048   else if (T->isFunctionPointerType() ||
01049            T->isBlockPointerType()) {
01050     // needs special handling, since pointer-to-functions have special
01051     // syntax (where a decaration models use).
01052     QualType retType = T;
01053     QualType PointeeTy;
01054     if (const PointerType* PT = retType->getAs<PointerType>())
01055       PointeeTy = PT->getPointeeType();
01056     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
01057       PointeeTy = BPT->getPointeeType();
01058     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
01059       ResultStr += FPRetType->getResultType().getAsString(
01060         Context->getPrintingPolicy());
01061       ResultStr += "(*";
01062     }
01063   } else
01064     ResultStr += T.getAsString(Context->getPrintingPolicy());
01065 }
01066 
01067 void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
01068                                         ObjCMethodDecl *OMD,
01069                                         std::string &ResultStr) {
01070   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
01071   const FunctionType *FPRetType = 0;
01072   ResultStr += "\nstatic ";
01073   RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
01074   ResultStr += " ";
01075 
01076   // Unique method name
01077   std::string NameStr;
01078 
01079   if (OMD->isInstanceMethod())
01080     NameStr += "_I_";
01081   else
01082     NameStr += "_C_";
01083 
01084   NameStr += IDecl->getNameAsString();
01085   NameStr += "_";
01086 
01087   if (ObjCCategoryImplDecl *CID =
01088       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
01089     NameStr += CID->getNameAsString();
01090     NameStr += "_";
01091   }
01092   // Append selector names, replacing ':' with '_'
01093   {
01094     std::string selString = OMD->getSelector().getAsString();
01095     int len = selString.size();
01096     for (int i = 0; i < len; i++)
01097       if (selString[i] == ':')
01098         selString[i] = '_';
01099     NameStr += selString;
01100   }
01101   // Remember this name for metadata emission
01102   MethodInternalNames[OMD] = NameStr;
01103   ResultStr += NameStr;
01104 
01105   // Rewrite arguments
01106   ResultStr += "(";
01107 
01108   // invisible arguments
01109   if (OMD->isInstanceMethod()) {
01110     QualType selfTy = Context->getObjCInterfaceType(IDecl);
01111     selfTy = Context->getPointerType(selfTy);
01112     if (!LangOpts.MicrosoftExt) {
01113       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
01114         ResultStr += "struct ";
01115     }
01116     // When rewriting for Microsoft, explicitly omit the structure name.
01117     ResultStr += IDecl->getNameAsString();
01118     ResultStr += " *";
01119   }
01120   else
01121     ResultStr += Context->getObjCClassType().getAsString(
01122       Context->getPrintingPolicy());
01123 
01124   ResultStr += " self, ";
01125   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
01126   ResultStr += " _cmd";
01127 
01128   // Method arguments.
01129   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
01130        E = OMD->param_end(); PI != E; ++PI) {
01131     ParmVarDecl *PDecl = *PI;
01132     ResultStr += ", ";
01133     if (PDecl->getType()->isObjCQualifiedIdType()) {
01134       ResultStr += "id ";
01135       ResultStr += PDecl->getNameAsString();
01136     } else {
01137       std::string Name = PDecl->getNameAsString();
01138       QualType QT = PDecl->getType();
01139       // Make sure we convert "t (^)(...)" to "t (*)(...)".
01140       (void)convertBlockPointerToFunctionPointer(QT);
01141       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
01142       ResultStr += Name;
01143     }
01144   }
01145   if (OMD->isVariadic())
01146     ResultStr += ", ...";
01147   ResultStr += ") ";
01148 
01149   if (FPRetType) {
01150     ResultStr += ")"; // close the precedence "scope" for "*".
01151 
01152     // Now, emit the argument types (if any).
01153     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
01154       ResultStr += "(";
01155       for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
01156         if (i) ResultStr += ", ";
01157         std::string ParamStr = FT->getArgType(i).getAsString(
01158           Context->getPrintingPolicy());
01159         ResultStr += ParamStr;
01160       }
01161       if (FT->isVariadic()) {
01162         if (FT->getNumArgs()) ResultStr += ", ";
01163         ResultStr += "...";
01164       }
01165       ResultStr += ")";
01166     } else {
01167       ResultStr += "()";
01168     }
01169   }
01170 }
01171 void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
01172   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
01173   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
01174 
01175   InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
01176 
01177   for (ObjCCategoryImplDecl::instmeth_iterator
01178        I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
01179        E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
01180        I != E; ++I) {
01181     std::string ResultStr;
01182     ObjCMethodDecl *OMD = *I;
01183     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
01184     SourceLocation LocStart = OMD->getLocStart();
01185     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
01186 
01187     const char *startBuf = SM->getCharacterData(LocStart);
01188     const char *endBuf = SM->getCharacterData(LocEnd);
01189     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
01190   }
01191 
01192   for (ObjCCategoryImplDecl::classmeth_iterator
01193        I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
01194        E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
01195        I != E; ++I) {
01196     std::string ResultStr;
01197     ObjCMethodDecl *OMD = *I;
01198     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
01199     SourceLocation LocStart = OMD->getLocStart();
01200     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
01201 
01202     const char *startBuf = SM->getCharacterData(LocStart);
01203     const char *endBuf = SM->getCharacterData(LocEnd);
01204     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
01205   }
01206   for (ObjCCategoryImplDecl::propimpl_iterator
01207        I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
01208        E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
01209        I != E; ++I) {
01210     RewritePropertyImplDecl(&*I, IMD, CID);
01211   }
01212 
01213   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
01214 }
01215 
01216 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
01217   std::string ResultStr;
01218   if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
01219     // we haven't seen a forward decl - generate a typedef.
01220     ResultStr = "#ifndef _REWRITER_typedef_";
01221     ResultStr += ClassDecl->getNameAsString();
01222     ResultStr += "\n";
01223     ResultStr += "#define _REWRITER_typedef_";
01224     ResultStr += ClassDecl->getNameAsString();
01225     ResultStr += "\n";
01226     ResultStr += "typedef struct objc_object ";
01227     ResultStr += ClassDecl->getNameAsString();
01228     ResultStr += ";\n#endif\n";
01229     // Mark this typedef as having been generated.
01230     ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
01231   }
01232   RewriteObjCInternalStruct(ClassDecl, ResultStr);
01233 
01234   for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
01235          E = ClassDecl->prop_end(); I != E; ++I)
01236     RewriteProperty(&*I);
01237   for (ObjCInterfaceDecl::instmeth_iterator
01238          I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
01239        I != E; ++I)
01240     RewriteMethodDeclaration(*I);
01241   for (ObjCInterfaceDecl::classmeth_iterator
01242          I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
01243        I != E; ++I)
01244     RewriteMethodDeclaration(*I);
01245 
01246   // Lastly, comment out the @end.
01247   ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), 
01248               "/* @end */");
01249 }
01250 
01251 Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
01252   SourceRange OldRange = PseudoOp->getSourceRange();
01253 
01254   // We just magically know some things about the structure of this
01255   // expression.
01256   ObjCMessageExpr *OldMsg =
01257     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
01258                             PseudoOp->getNumSemanticExprs() - 1));
01259 
01260   // Because the rewriter doesn't allow us to rewrite rewritten code,
01261   // we need to suppress rewriting the sub-statements.
01262   Expr *Base, *RHS;
01263   {
01264     DisableReplaceStmtScope S(*this);
01265 
01266     // Rebuild the base expression if we have one.
01267     Base = 0;
01268     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
01269       Base = OldMsg->getInstanceReceiver();
01270       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
01271       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
01272     }
01273 
01274     // Rebuild the RHS.
01275     RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
01276     RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
01277     RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
01278   }
01279 
01280   // TODO: avoid this copy.
01281   SmallVector<SourceLocation, 1> SelLocs;
01282   OldMsg->getSelectorLocs(SelLocs);
01283 
01284   ObjCMessageExpr *NewMsg = 0;
01285   switch (OldMsg->getReceiverKind()) {
01286   case ObjCMessageExpr::Class:
01287     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01288                                      OldMsg->getValueKind(),
01289                                      OldMsg->getLeftLoc(),
01290                                      OldMsg->getClassReceiverTypeInfo(),
01291                                      OldMsg->getSelector(),
01292                                      SelLocs,
01293                                      OldMsg->getMethodDecl(),
01294                                      RHS,
01295                                      OldMsg->getRightLoc(),
01296                                      OldMsg->isImplicit());
01297     break;
01298 
01299   case ObjCMessageExpr::Instance:
01300     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01301                                      OldMsg->getValueKind(),
01302                                      OldMsg->getLeftLoc(),
01303                                      Base,
01304                                      OldMsg->getSelector(),
01305                                      SelLocs,
01306                                      OldMsg->getMethodDecl(),
01307                                      RHS,
01308                                      OldMsg->getRightLoc(),
01309                                      OldMsg->isImplicit());
01310     break;
01311 
01312   case ObjCMessageExpr::SuperClass:
01313   case ObjCMessageExpr::SuperInstance:
01314     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01315                                      OldMsg->getValueKind(),
01316                                      OldMsg->getLeftLoc(),
01317                                      OldMsg->getSuperLoc(),
01318                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
01319                                      OldMsg->getSuperType(),
01320                                      OldMsg->getSelector(),
01321                                      SelLocs,
01322                                      OldMsg->getMethodDecl(),
01323                                      RHS,
01324                                      OldMsg->getRightLoc(),
01325                                      OldMsg->isImplicit());
01326     break;
01327   }
01328 
01329   Stmt *Replacement = SynthMessageExpr(NewMsg);
01330   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
01331   return Replacement;
01332 }
01333 
01334 Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
01335   SourceRange OldRange = PseudoOp->getSourceRange();
01336 
01337   // We just magically know some things about the structure of this
01338   // expression.
01339   ObjCMessageExpr *OldMsg =
01340     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
01341 
01342   // Because the rewriter doesn't allow us to rewrite rewritten code,
01343   // we need to suppress rewriting the sub-statements.
01344   Expr *Base = 0;
01345   {
01346     DisableReplaceStmtScope S(*this);
01347 
01348     // Rebuild the base expression if we have one.
01349     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
01350       Base = OldMsg->getInstanceReceiver();
01351       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
01352       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
01353     }
01354   }
01355 
01356   // Intentionally empty.
01357   SmallVector<SourceLocation, 1> SelLocs;
01358   SmallVector<Expr*, 1> Args;
01359 
01360   ObjCMessageExpr *NewMsg = 0;
01361   switch (OldMsg->getReceiverKind()) {
01362   case ObjCMessageExpr::Class:
01363     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01364                                      OldMsg->getValueKind(),
01365                                      OldMsg->getLeftLoc(),
01366                                      OldMsg->getClassReceiverTypeInfo(),
01367                                      OldMsg->getSelector(),
01368                                      SelLocs,
01369                                      OldMsg->getMethodDecl(),
01370                                      Args,
01371                                      OldMsg->getRightLoc(),
01372                                      OldMsg->isImplicit());
01373     break;
01374 
01375   case ObjCMessageExpr::Instance:
01376     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01377                                      OldMsg->getValueKind(),
01378                                      OldMsg->getLeftLoc(),
01379                                      Base,
01380                                      OldMsg->getSelector(),
01381                                      SelLocs,
01382                                      OldMsg->getMethodDecl(),
01383                                      Args,
01384                                      OldMsg->getRightLoc(),
01385                                      OldMsg->isImplicit());
01386     break;
01387 
01388   case ObjCMessageExpr::SuperClass:
01389   case ObjCMessageExpr::SuperInstance:
01390     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
01391                                      OldMsg->getValueKind(),
01392                                      OldMsg->getLeftLoc(),
01393                                      OldMsg->getSuperLoc(),
01394                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
01395                                      OldMsg->getSuperType(),
01396                                      OldMsg->getSelector(),
01397                                      SelLocs,
01398                                      OldMsg->getMethodDecl(),
01399                                      Args,
01400                                      OldMsg->getRightLoc(),
01401                                      OldMsg->isImplicit());
01402     break;
01403   }
01404 
01405   Stmt *Replacement = SynthMessageExpr(NewMsg);
01406   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
01407   return Replacement;
01408 }
01409 
01410 /// SynthCountByEnumWithState - To print:
01411 /// ((unsigned int (*)
01412 ///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
01413 ///  (void *)objc_msgSend)((id)l_collection,
01414 ///                        sel_registerName(
01415 ///                          "countByEnumeratingWithState:objects:count:"),
01416 ///                        &enumState,
01417 ///                        (id *)__rw_items, (unsigned int)16)
01418 ///
01419 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
01420   buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
01421   "id *, unsigned int))(void *)objc_msgSend)";
01422   buf += "\n\t\t";
01423   buf += "((id)l_collection,\n\t\t";
01424   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
01425   buf += "\n\t\t";
01426   buf += "&enumState, "
01427          "(id *)__rw_items, (unsigned int)16)";
01428 }
01429 
01430 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
01431 /// statement to exit to its outer synthesized loop.
01432 ///
01433 Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
01434   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
01435     return S;
01436   // replace break with goto __break_label
01437   std::string buf;
01438 
01439   SourceLocation startLoc = S->getLocStart();
01440   buf = "goto __break_label_";
01441   buf += utostr(ObjCBcLabelNo.back());
01442   ReplaceText(startLoc, strlen("break"), buf);
01443 
01444   return 0;
01445 }
01446 
01447 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
01448 /// statement to continue with its inner synthesized loop.
01449 ///
01450 Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
01451   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
01452     return S;
01453   // replace continue with goto __continue_label
01454   std::string buf;
01455 
01456   SourceLocation startLoc = S->getLocStart();
01457   buf = "goto __continue_label_";
01458   buf += utostr(ObjCBcLabelNo.back());
01459   ReplaceText(startLoc, strlen("continue"), buf);
01460 
01461   return 0;
01462 }
01463 
01464 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
01465 ///  It rewrites:
01466 /// for ( type elem in collection) { stmts; }
01467 
01468 /// Into:
01469 /// {
01470 ///   type elem;
01471 ///   struct __objcFastEnumerationState enumState = { 0 };
01472 ///   id __rw_items[16];
01473 ///   id l_collection = (id)collection;
01474 ///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
01475 ///                                       objects:__rw_items count:16];
01476 /// if (limit) {
01477 ///   unsigned long startMutations = *enumState.mutationsPtr;
01478 ///   do {
01479 ///        unsigned long counter = 0;
01480 ///        do {
01481 ///             if (startMutations != *enumState.mutationsPtr)
01482 ///               objc_enumerationMutation(l_collection);
01483 ///             elem = (type)enumState.itemsPtr[counter++];
01484 ///             stmts;
01485 ///             __continue_label: ;
01486 ///        } while (counter < limit);
01487 ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
01488 ///                                  objects:__rw_items count:16]);
01489 ///   elem = nil;
01490 ///   __break_label: ;
01491 ///  }
01492 ///  else
01493 ///       elem = nil;
01494 ///  }
01495 ///
01496 Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
01497                                                 SourceLocation OrigEnd) {
01498   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
01499   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
01500          "ObjCForCollectionStmt Statement stack mismatch");
01501   assert(!ObjCBcLabelNo.empty() &&
01502          "ObjCForCollectionStmt - Label No stack empty");
01503 
01504   SourceLocation startLoc = S->getLocStart();
01505   const char *startBuf = SM->getCharacterData(startLoc);
01506   StringRef elementName;
01507   std::string elementTypeAsString;
01508   std::string buf;
01509   buf = "\n{\n\t";
01510   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
01511     // type elem;
01512     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
01513     QualType ElementType = cast<ValueDecl>(D)->getType();
01514     if (ElementType->isObjCQualifiedIdType() ||
01515         ElementType->isObjCQualifiedInterfaceType())
01516       // Simply use 'id' for all qualified types.
01517       elementTypeAsString = "id";
01518     else
01519       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
01520     buf += elementTypeAsString;
01521     buf += " ";
01522     elementName = D->getName();
01523     buf += elementName;
01524     buf += ";\n\t";
01525   }
01526   else {
01527     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
01528     elementName = DR->getDecl()->getName();
01529     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
01530     if (VD->getType()->isObjCQualifiedIdType() ||
01531         VD->getType()->isObjCQualifiedInterfaceType())
01532       // Simply use 'id' for all qualified types.
01533       elementTypeAsString = "id";
01534     else
01535       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
01536   }
01537 
01538   // struct __objcFastEnumerationState enumState = { 0 };
01539   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
01540   // id __rw_items[16];
01541   buf += "id __rw_items[16];\n\t";
01542   // id l_collection = (id)
01543   buf += "id l_collection = (id)";
01544   // Find start location of 'collection' the hard way!
01545   const char *startCollectionBuf = startBuf;
01546   startCollectionBuf += 3;  // skip 'for'
01547   startCollectionBuf = strchr(startCollectionBuf, '(');
01548   startCollectionBuf++; // skip '('
01549   // find 'in' and skip it.
01550   while (*startCollectionBuf != ' ' ||
01551          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
01552          (*(startCollectionBuf+3) != ' ' &&
01553           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
01554     startCollectionBuf++;
01555   startCollectionBuf += 3;
01556 
01557   // Replace: "for (type element in" with string constructed thus far.
01558   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
01559   // Replace ')' in for '(' type elem in collection ')' with ';'
01560   SourceLocation rightParenLoc = S->getRParenLoc();
01561   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
01562   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
01563   buf = ";\n\t";
01564 
01565   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
01566   //                                   objects:__rw_items count:16];
01567   // which is synthesized into:
01568   // unsigned int limit =
01569   // ((unsigned int (*)
01570   //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
01571   //  (void *)objc_msgSend)((id)l_collection,
01572   //                        sel_registerName(
01573   //                          "countByEnumeratingWithState:objects:count:"),
01574   //                        (struct __objcFastEnumerationState *)&state,
01575   //                        (id *)__rw_items, (unsigned int)16);
01576   buf += "unsigned long limit =\n\t\t";
01577   SynthCountByEnumWithState(buf);
01578   buf += ";\n\t";
01579   /// if (limit) {
01580   ///   unsigned long startMutations = *enumState.mutationsPtr;
01581   ///   do {
01582   ///        unsigned long counter = 0;
01583   ///        do {
01584   ///             if (startMutations != *enumState.mutationsPtr)
01585   ///               objc_enumerationMutation(l_collection);
01586   ///             elem = (type)enumState.itemsPtr[counter++];
01587   buf += "if (limit) {\n\t";
01588   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
01589   buf += "do {\n\t\t";
01590   buf += "unsigned long counter = 0;\n\t\t";
01591   buf += "do {\n\t\t\t";
01592   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
01593   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
01594   buf += elementName;
01595   buf += " = (";
01596   buf += elementTypeAsString;
01597   buf += ")enumState.itemsPtr[counter++];";
01598   // Replace ')' in for '(' type elem in collection ')' with all of these.
01599   ReplaceText(lparenLoc, 1, buf);
01600 
01601   ///            __continue_label: ;
01602   ///        } while (counter < limit);
01603   ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
01604   ///                                  objects:__rw_items count:16]);
01605   ///   elem = nil;
01606   ///   __break_label: ;
01607   ///  }
01608   ///  else
01609   ///       elem = nil;
01610   ///  }
01611   ///
01612   buf = ";\n\t";
01613   buf += "__continue_label_";
01614   buf += utostr(ObjCBcLabelNo.back());
01615   buf += ": ;";
01616   buf += "\n\t\t";
01617   buf += "} while (counter < limit);\n\t";
01618   buf += "} while (limit = ";
01619   SynthCountByEnumWithState(buf);
01620   buf += ");\n\t";
01621   buf += elementName;
01622   buf += " = ((";
01623   buf += elementTypeAsString;
01624   buf += ")0);\n\t";
01625   buf += "__break_label_";
01626   buf += utostr(ObjCBcLabelNo.back());
01627   buf += ": ;\n\t";
01628   buf += "}\n\t";
01629   buf += "else\n\t\t";
01630   buf += elementName;
01631   buf += " = ((";
01632   buf += elementTypeAsString;
01633   buf += ")0);\n\t";
01634   buf += "}\n";
01635 
01636   // Insert all these *after* the statement body.
01637   // FIXME: If this should support Obj-C++, support CXXTryStmt
01638   if (isa<CompoundStmt>(S->getBody())) {
01639     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
01640     InsertText(endBodyLoc, buf);
01641   } else {
01642     /* Need to treat single statements specially. For example:
01643      *
01644      *     for (A *a in b) if (stuff()) break;
01645      *     for (A *a in b) xxxyy;
01646      *
01647      * The following code simply scans ahead to the semi to find the actual end.
01648      */
01649     const char *stmtBuf = SM->getCharacterData(OrigEnd);
01650     const char *semiBuf = strchr(stmtBuf, ';');
01651     assert(semiBuf && "Can't find ';'");
01652     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
01653     InsertText(endBodyLoc, buf);
01654   }
01655   Stmts.pop_back();
01656   ObjCBcLabelNo.pop_back();
01657   return 0;
01658 }
01659 
01660 /// RewriteObjCSynchronizedStmt -
01661 /// This routine rewrites @synchronized(expr) stmt;
01662 /// into:
01663 /// objc_sync_enter(expr);
01664 /// @try stmt @finally { objc_sync_exit(expr); }
01665 ///
01666 Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
01667   // Get the start location and compute the semi location.
01668   SourceLocation startLoc = S->getLocStart();
01669   const char *startBuf = SM->getCharacterData(startLoc);
01670 
01671   assert((*startBuf == '@') && "bogus @synchronized location");
01672 
01673   std::string buf;
01674   buf = "objc_sync_enter((id)";
01675   const char *lparenBuf = startBuf;
01676   while (*lparenBuf != '(') lparenBuf++;
01677   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
01678   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
01679   // the sync expression is typically a message expression that's already
01680   // been rewritten! (which implies the SourceLocation's are invalid).
01681   SourceLocation endLoc = S->getSynchBody()->getLocStart();
01682   const char *endBuf = SM->getCharacterData(endLoc);
01683   while (*endBuf != ')') endBuf--;
01684   SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
01685   buf = ");\n";
01686   // declare a new scope with two variables, _stack and _rethrow.
01687   buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
01688   buf += "int buf[18/*32-bit i386*/];\n";
01689   buf += "char *pointers[4];} _stack;\n";
01690   buf += "id volatile _rethrow = 0;\n";
01691   buf += "objc_exception_try_enter(&_stack);\n";
01692   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
01693   ReplaceText(rparenLoc, 1, buf);
01694   startLoc = S->getSynchBody()->getLocEnd();
01695   startBuf = SM->getCharacterData(startLoc);
01696 
01697   assert((*startBuf == '}') && "bogus @synchronized block");
01698   SourceLocation lastCurlyLoc = startLoc;
01699   buf = "}\nelse {\n";
01700   buf += "  _rethrow = objc_exception_extract(&_stack);\n";
01701   buf += "}\n";
01702   buf += "{ /* implicit finally clause */\n";
01703   buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
01704   
01705   std::string syncBuf;
01706   syncBuf += " objc_sync_exit(";
01707 
01708   Expr *syncExpr = S->getSynchExpr();
01709   CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
01710                   ? CK_BitCast :
01711                 syncExpr->getType()->isBlockPointerType()
01712                   ? CK_BlockPointerToObjCPointerCast
01713                   : CK_CPointerToObjCPointerCast;
01714   syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
01715                                       CK, syncExpr);
01716   std::string syncExprBufS;
01717   llvm::raw_string_ostream syncExprBuf(syncExprBufS);
01718   syncExpr->printPretty(syncExprBuf, *Context, 0,
01719                         PrintingPolicy(LangOpts));
01720   syncBuf += syncExprBuf.str();
01721   syncBuf += ");";
01722   
01723   buf += syncBuf;
01724   buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
01725   buf += "}\n";
01726   buf += "}";
01727 
01728   ReplaceText(lastCurlyLoc, 1, buf);
01729 
01730   bool hasReturns = false;
01731   HasReturnStmts(S->getSynchBody(), hasReturns);
01732   if (hasReturns)
01733     RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
01734 
01735   return 0;
01736 }
01737 
01738 void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
01739 {
01740   // Perform a bottom up traversal of all children.
01741   for (Stmt::child_range CI = S->children(); CI; ++CI)
01742     if (*CI)
01743       WarnAboutReturnGotoStmts(*CI);
01744 
01745   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
01746     Diags.Report(Context->getFullLoc(S->getLocStart()),
01747                  TryFinallyContainsReturnDiag);
01748   }
01749   return;
01750 }
01751 
01752 void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) 
01753 {  
01754   // Perform a bottom up traversal of all children.
01755   for (Stmt::child_range CI = S->children(); CI; ++CI)
01756    if (*CI)
01757      HasReturnStmts(*CI, hasReturns);
01758 
01759  if (isa<ReturnStmt>(S))
01760    hasReturns = true;
01761  return;
01762 }
01763 
01764 void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
01765  // Perform a bottom up traversal of all children.
01766  for (Stmt::child_range CI = S->children(); CI; ++CI)
01767    if (*CI) {
01768      RewriteTryReturnStmts(*CI);
01769    }
01770  if (isa<ReturnStmt>(S)) {
01771    SourceLocation startLoc = S->getLocStart();
01772    const char *startBuf = SM->getCharacterData(startLoc);
01773 
01774    const char *semiBuf = strchr(startBuf, ';');
01775    assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
01776    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
01777 
01778    std::string buf;
01779    buf = "{ objc_exception_try_exit(&_stack); return";
01780    
01781    ReplaceText(startLoc, 6, buf);
01782    InsertText(onePastSemiLoc, "}");
01783  }
01784  return;
01785 }
01786 
01787 void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
01788   // Perform a bottom up traversal of all children.
01789   for (Stmt::child_range CI = S->children(); CI; ++CI)
01790     if (*CI) {
01791       RewriteSyncReturnStmts(*CI, syncExitBuf);
01792     }
01793   if (isa<ReturnStmt>(S)) {
01794     SourceLocation startLoc = S->getLocStart();
01795     const char *startBuf = SM->getCharacterData(startLoc);
01796 
01797     const char *semiBuf = strchr(startBuf, ';');
01798     assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
01799     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
01800 
01801     std::string buf;
01802     buf = "{ objc_exception_try_exit(&_stack);";
01803     buf += syncExitBuf;
01804     buf += " return";
01805     
01806     ReplaceText(startLoc, 6, buf);
01807     InsertText(onePastSemiLoc, "}");
01808   }
01809   return;
01810 }
01811 
01812 Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
01813   // Get the start location and compute the semi location.
01814   SourceLocation startLoc = S->getLocStart();
01815   const char *startBuf = SM->getCharacterData(startLoc);
01816 
01817   assert((*startBuf == '@') && "bogus @try location");
01818 
01819   std::string buf;
01820   // declare a new scope with two variables, _stack and _rethrow.
01821   buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
01822   buf += "int buf[18/*32-bit i386*/];\n";
01823   buf += "char *pointers[4];} _stack;\n";
01824   buf += "id volatile _rethrow = 0;\n";
01825   buf += "objc_exception_try_enter(&_stack);\n";
01826   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
01827 
01828   ReplaceText(startLoc, 4, buf);
01829 
01830   startLoc = S->getTryBody()->getLocEnd();
01831   startBuf = SM->getCharacterData(startLoc);
01832 
01833   assert((*startBuf == '}') && "bogus @try block");
01834 
01835   SourceLocation lastCurlyLoc = startLoc;
01836   if (S->getNumCatchStmts()) {
01837     startLoc = startLoc.getLocWithOffset(1);
01838     buf = " /* @catch begin */ else {\n";
01839     buf += " id _caught = objc_exception_extract(&_stack);\n";
01840     buf += " objc_exception_try_enter (&_stack);\n";
01841     buf += " if (_setjmp(_stack.buf))\n";
01842     buf += "   _rethrow = objc_exception_extract(&_stack);\n";
01843     buf += " else { /* @catch continue */";
01844 
01845     InsertText(startLoc, buf);
01846   } else { /* no catch list */
01847     buf = "}\nelse {\n";
01848     buf += "  _rethrow = objc_exception_extract(&_stack);\n";
01849     buf += "}";
01850     ReplaceText(lastCurlyLoc, 1, buf);
01851   }
01852   Stmt *lastCatchBody = 0;
01853   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
01854     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
01855     VarDecl *catchDecl = Catch->getCatchParamDecl();
01856 
01857     if (I == 0)
01858       buf = "if ("; // we are generating code for the first catch clause
01859     else
01860       buf = "else if (";
01861     startLoc = Catch->getLocStart();
01862     startBuf = SM->getCharacterData(startLoc);
01863 
01864     assert((*startBuf == '@') && "bogus @catch location");
01865 
01866     const char *lParenLoc = strchr(startBuf, '(');
01867 
01868     if (Catch->hasEllipsis()) {
01869       // Now rewrite the body...
01870       lastCatchBody = Catch->getCatchBody();
01871       SourceLocation bodyLoc = lastCatchBody->getLocStart();
01872       const char *bodyBuf = SM->getCharacterData(bodyLoc);
01873       assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
01874              "bogus @catch paren location");
01875       assert((*bodyBuf == '{') && "bogus @catch body location");
01876 
01877       buf += "1) { id _tmp = _caught;";
01878       Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
01879     } else if (catchDecl) {
01880       QualType t = catchDecl->getType();
01881       if (t == Context->getObjCIdType()) {
01882         buf += "1) { ";
01883         ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
01884       } else if (const ObjCObjectPointerType *Ptr =
01885                    t->getAs<ObjCObjectPointerType>()) {
01886         // Should be a pointer to a class.
01887         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
01888         if (IDecl) {
01889           buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
01890           buf += IDecl->getNameAsString();
01891           buf += "\"), (struct objc_object *)_caught)) { ";
01892           ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
01893         }
01894       }
01895       // Now rewrite the body...
01896       lastCatchBody = Catch->getCatchBody();
01897       SourceLocation rParenLoc = Catch->getRParenLoc();
01898       SourceLocation bodyLoc = lastCatchBody->getLocStart();
01899       const char *bodyBuf = SM->getCharacterData(bodyLoc);
01900       const char *rParenBuf = SM->getCharacterData(rParenLoc);
01901       assert((*rParenBuf == ')') && "bogus @catch paren location");
01902       assert((*bodyBuf == '{') && "bogus @catch body location");
01903 
01904       // Here we replace ") {" with "= _caught;" (which initializes and
01905       // declares the @catch parameter).
01906       ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
01907     } else {
01908       llvm_unreachable("@catch rewrite bug");
01909     }
01910   }
01911   // Complete the catch list...
01912   if (lastCatchBody) {
01913     SourceLocation bodyLoc = lastCatchBody->getLocEnd();
01914     assert(*SM->getCharacterData(bodyLoc) == '}' &&
01915            "bogus @catch body location");
01916 
01917     // Insert the last (implicit) else clause *before* the right curly brace.
01918     bodyLoc = bodyLoc.getLocWithOffset(-1);
01919     buf = "} /* last catch end */\n";
01920     buf += "else {\n";
01921     buf += " _rethrow = _caught;\n";
01922     buf += " objc_exception_try_exit(&_stack);\n";
01923     buf += "} } /* @catch end */\n";
01924     if (!S->getFinallyStmt())
01925       buf += "}\n";
01926     InsertText(bodyLoc, buf);
01927 
01928     // Set lastCurlyLoc
01929     lastCurlyLoc = lastCatchBody->getLocEnd();
01930   }
01931   if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
01932     startLoc = finalStmt->getLocStart();
01933     startBuf = SM->getCharacterData(startLoc);
01934     assert((*startBuf == '@') && "bogus @finally start");
01935 
01936     ReplaceText(startLoc, 8, "/* @finally */");
01937 
01938     Stmt *body = finalStmt->getFinallyBody();
01939     SourceLocation startLoc = body->getLocStart();
01940     SourceLocation endLoc = body->getLocEnd();
01941     assert(*SM->getCharacterData(startLoc) == '{' &&
01942            "bogus @finally body location");
01943     assert(*SM->getCharacterData(endLoc) == '}' &&
01944            "bogus @finally body location");
01945 
01946     startLoc = startLoc.getLocWithOffset(1);
01947     InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
01948     endLoc = endLoc.getLocWithOffset(-1);
01949     InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
01950 
01951     // Set lastCurlyLoc
01952     lastCurlyLoc = body->getLocEnd();
01953 
01954     // Now check for any return/continue/go statements within the @try.
01955     WarnAboutReturnGotoStmts(S->getTryBody());
01956   } else { /* no finally clause - make sure we synthesize an implicit one */
01957     buf = "{ /* implicit finally clause */\n";
01958     buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
01959     buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
01960     buf += "}";
01961     ReplaceText(lastCurlyLoc, 1, buf);
01962     
01963     // Now check for any return/continue/go statements within the @try.
01964     // The implicit finally clause won't called if the @try contains any
01965     // jump statements.
01966     bool hasReturns = false;
01967     HasReturnStmts(S->getTryBody(), hasReturns);
01968     if (hasReturns)
01969       RewriteTryReturnStmts(S->getTryBody());
01970   }
01971   // Now emit the final closing curly brace...
01972   lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
01973   InsertText(lastCurlyLoc, " } /* @try scope end */\n");
01974   return 0;
01975 }
01976 
01977 // This can't be done with ReplaceStmt(S, ThrowExpr), since
01978 // the throw expression is typically a message expression that's already
01979 // been rewritten! (which implies the SourceLocation's are invalid).
01980 Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
01981   // Get the start location and compute the semi location.
01982   SourceLocation startLoc = S->getLocStart();
01983   const char *startBuf = SM->getCharacterData(startLoc);
01984 
01985   assert((*startBuf == '@') && "bogus @throw location");
01986 
01987   std::string buf;
01988   /* void objc_exception_throw(id) __attribute__((noreturn)); */
01989   if (S->getThrowExpr())
01990     buf = "objc_exception_throw(";
01991   else // add an implicit argument
01992     buf = "objc_exception_throw(_caught";
01993 
01994   // handle "@  throw" correctly.
01995   const char *wBuf = strchr(startBuf, 'w');
01996   assert((*wBuf == 'w') && "@throw: can't find 'w'");
01997   ReplaceText(startLoc, wBuf-startBuf+1, buf);
01998 
01999   const char *semiBuf = strchr(startBuf, ';');
02000   assert((*semiBuf == ';') && "@throw: can't find ';'");
02001   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
02002   ReplaceText(semiLoc, 1, ");");
02003   return 0;
02004 }
02005 
02006 Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
02007   // Create a new string expression.
02008   QualType StrType = Context->getPointerType(Context->CharTy);
02009   std::string StrEncoding;
02010   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
02011   Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
02012                                             StringLiteral::Ascii, false,
02013                                             StrType, SourceLocation());
02014   ReplaceStmt(Exp, Replacement);
02015 
02016   // Replace this subexpr in the parent.
02017   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02018   return Replacement;
02019 }
02020 
02021 Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
02022   if (!SelGetUidFunctionDecl)
02023     SynthSelGetUidFunctionDecl();
02024   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
02025   // Create a call to sel_registerName("selName").
02026   SmallVector<Expr*, 8> SelExprs;
02027   QualType argType = Context->getPointerType(Context->CharTy);
02028   SelExprs.push_back(StringLiteral::Create(*Context,
02029                                            Exp->getSelector().getAsString(),
02030                                            StringLiteral::Ascii, false,
02031                                            argType, SourceLocation()));
02032   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02033                                                  &SelExprs[0], SelExprs.size());
02034   ReplaceStmt(Exp, SelExp);
02035   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02036   return SelExp;
02037 }
02038 
02039 CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
02040   FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
02041                                                     SourceLocation EndLoc) {
02042   // Get the type, we will need to reference it in a couple spots.
02043   QualType msgSendType = FD->getType();
02044 
02045   // Create a reference to the objc_msgSend() declaration.
02046   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
02047                                                VK_LValue, SourceLocation());
02048 
02049   // Now, we cast the reference to a pointer to the objc_msgSend type.
02050   QualType pToFunc = Context->getPointerType(msgSendType);
02051   ImplicitCastExpr *ICE = 
02052     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
02053                              DRE, 0, VK_RValue);
02054 
02055   const FunctionType *FT = msgSendType->getAs<FunctionType>();
02056 
02057   CallExpr *Exp =  
02058     new (Context) CallExpr(*Context, ICE, args, nargs, 
02059                            FT->getCallResultType(*Context),
02060                            VK_RValue, EndLoc);
02061   return Exp;
02062 }
02063 
02064 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
02065                                 const char *&startRef, const char *&endRef) {
02066   while (startBuf < endBuf) {
02067     if (*startBuf == '<')
02068       startRef = startBuf; // mark the start.
02069     if (*startBuf == '>') {
02070       if (startRef && *startRef == '<') {
02071         endRef = startBuf; // mark the end.
02072         return true;
02073       }
02074       return false;
02075     }
02076     startBuf++;
02077   }
02078   return false;
02079 }
02080 
02081 static void scanToNextArgument(const char *&argRef) {
02082   int angle = 0;
02083   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
02084     if (*argRef == '<')
02085       angle++;
02086     else if (*argRef == '>')
02087       angle--;
02088     argRef++;
02089   }
02090   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
02091 }
02092 
02093 bool RewriteObjC::needToScanForQualifiers(QualType T) {
02094   if (T->isObjCQualifiedIdType())
02095     return true;
02096   if (const PointerType *PT = T->getAs<PointerType>()) {
02097     if (PT->getPointeeType()->isObjCQualifiedIdType())
02098       return true;
02099   }
02100   if (T->isObjCObjectPointerType()) {
02101     T = T->getPointeeType();
02102     return T->isObjCQualifiedInterfaceType();
02103   }
02104   if (T->isArrayType()) {
02105     QualType ElemTy = Context->getBaseElementType(T);
02106     return needToScanForQualifiers(ElemTy);
02107   }
02108   return false;
02109 }
02110 
02111 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
02112   QualType Type = E->getType();
02113   if (needToScanForQualifiers(Type)) {
02114     SourceLocation Loc, EndLoc;
02115 
02116     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
02117       Loc = ECE->getLParenLoc();
02118       EndLoc = ECE->getRParenLoc();
02119     } else {
02120       Loc = E->getLocStart();
02121       EndLoc = E->getLocEnd();
02122     }
02123     // This will defend against trying to rewrite synthesized expressions.
02124     if (Loc.isInvalid() || EndLoc.isInvalid())
02125       return;
02126 
02127     const char *startBuf = SM->getCharacterData(Loc);
02128     const char *endBuf = SM->getCharacterData(EndLoc);
02129     const char *startRef = 0, *endRef = 0;
02130     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02131       // Get the locations of the startRef, endRef.
02132       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
02133       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
02134       // Comment out the protocol references.
02135       InsertText(LessLoc, "/*");
02136       InsertText(GreaterLoc, "*/");
02137     }
02138   }
02139 }
02140 
02141 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
02142   SourceLocation Loc;
02143   QualType Type;
02144   const FunctionProtoType *proto = 0;
02145   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
02146     Loc = VD->getLocation();
02147     Type = VD->getType();
02148   }
02149   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
02150     Loc = FD->getLocation();
02151     // Check for ObjC 'id' and class types that have been adorned with protocol
02152     // information (id<p>, C<p>*). The protocol references need to be rewritten!
02153     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
02154     assert(funcType && "missing function type");
02155     proto = dyn_cast<FunctionProtoType>(funcType);
02156     if (!proto)
02157       return;
02158     Type = proto->getResultType();
02159   }
02160   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
02161     Loc = FD->getLocation();
02162     Type = FD->getType();
02163   }
02164   else
02165     return;
02166 
02167   if (needToScanForQualifiers(Type)) {
02168     // Since types are unique, we need to scan the buffer.
02169 
02170     const char *endBuf = SM->getCharacterData(Loc);
02171     const char *startBuf = endBuf;
02172     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
02173       startBuf--; // scan backward (from the decl location) for return type.
02174     const char *startRef = 0, *endRef = 0;
02175     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02176       // Get the locations of the startRef, endRef.
02177       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
02178       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
02179       // Comment out the protocol references.
02180       InsertText(LessLoc, "/*");
02181       InsertText(GreaterLoc, "*/");
02182     }
02183   }
02184   if (!proto)
02185       return; // most likely, was a variable
02186   // Now check arguments.
02187   const char *startBuf = SM->getCharacterData(Loc);
02188   const char *startFuncBuf = startBuf;
02189   for (unsigned i = 0; i < proto->getNumArgs(); i++) {
02190     if (needToScanForQualifiers(proto->getArgType(i))) {
02191       // Since types are unique, we need to scan the buffer.
02192 
02193       const char *endBuf = startBuf;
02194       // scan forward (from the decl location) for argument types.
02195       scanToNextArgument(endBuf);
02196       const char *startRef = 0, *endRef = 0;
02197       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
02198         // Get the locations of the startRef, endRef.
02199         SourceLocation LessLoc =
02200           Loc.getLocWithOffset(startRef-startFuncBuf);
02201         SourceLocation GreaterLoc =
02202           Loc.getLocWithOffset(endRef-startFuncBuf+1);
02203         // Comment out the protocol references.
02204         InsertText(LessLoc, "/*");
02205         InsertText(GreaterLoc, "*/");
02206       }
02207       startBuf = ++endBuf;
02208     }
02209     else {
02210       // If the function name is derived from a macro expansion, then the
02211       // argument buffer will not follow the name. Need to speak with Chris.
02212       while (*startBuf && *startBuf != ')' && *startBuf != ',')
02213         startBuf++; // scan forward (from the decl location) for argument types.
02214       startBuf++;
02215     }
02216   }
02217 }
02218 
02219 void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
02220   QualType QT = ND->getType();
02221   const Type* TypePtr = QT->getAs<Type>();
02222   if (!isa<TypeOfExprType>(TypePtr))
02223     return;
02224   while (isa<TypeOfExprType>(TypePtr)) {
02225     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
02226     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
02227     TypePtr = QT->getAs<Type>();
02228   }
02229   // FIXME. This will not work for multiple declarators; as in:
02230   // __typeof__(a) b,c,d;
02231   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
02232   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
02233   const char *startBuf = SM->getCharacterData(DeclLoc);
02234   if (ND->getInit()) {
02235     std::string Name(ND->getNameAsString());
02236     TypeAsString += " " + Name + " = ";
02237     Expr *E = ND->getInit();
02238     SourceLocation startLoc;
02239     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
02240       startLoc = ECE->getLParenLoc();
02241     else
02242       startLoc = E->getLocStart();
02243     startLoc = SM->getExpansionLoc(startLoc);
02244     const char *endBuf = SM->getCharacterData(startLoc);
02245     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
02246   }
02247   else {
02248     SourceLocation X = ND->getLocEnd();
02249     X = SM->getExpansionLoc(X);
02250     const char *endBuf = SM->getCharacterData(X);
02251     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
02252   }
02253 }
02254 
02255 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
02256 void RewriteObjC::SynthSelGetUidFunctionDecl() {
02257   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
02258   SmallVector<QualType, 16> ArgTys;
02259   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02260   QualType getFuncType =
02261     getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
02262   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02263                                            SourceLocation(),
02264                                            SourceLocation(),
02265                                            SelGetUidIdent, getFuncType, 0,
02266                                            SC_Extern,
02267                                            SC_None, false);
02268 }
02269 
02270 void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
02271   // declared in <objc/objc.h>
02272   if (FD->getIdentifier() &&
02273       FD->getName() == "sel_registerName") {
02274     SelGetUidFunctionDecl = FD;
02275     return;
02276   }
02277   RewriteObjCQualifiedInterfaceTypes(FD);
02278 }
02279 
02280 void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
02281   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
02282   const char *argPtr = TypeString.c_str();
02283   if (!strchr(argPtr, '^')) {
02284     Str += TypeString;
02285     return;
02286   }
02287   while (*argPtr) {
02288     Str += (*argPtr == '^' ? '*' : *argPtr);
02289     argPtr++;
02290   }
02291 }
02292 
02293 // FIXME. Consolidate this routine with RewriteBlockPointerType.
02294 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
02295                                                   ValueDecl *VD) {
02296   QualType Type = VD->getType();
02297   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
02298   const char *argPtr = TypeString.c_str();
02299   int paren = 0;
02300   while (*argPtr) {
02301     switch (*argPtr) {
02302       case '(':
02303         Str += *argPtr;
02304         paren++;
02305         break;
02306       case ')':
02307         Str += *argPtr;
02308         paren--;
02309         break;
02310       case '^':
02311         Str += '*';
02312         if (paren == 1)
02313           Str += VD->getNameAsString();
02314         break;
02315       default:
02316         Str += *argPtr;
02317         break;
02318     }
02319     argPtr++;
02320   }
02321 }
02322 
02323 
02324 void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
02325   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
02326   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
02327   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
02328   if (!proto)
02329     return;
02330   QualType Type = proto->getResultType();
02331   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
02332   FdStr += " ";
02333   FdStr += FD->getName();
02334   FdStr +=  "(";
02335   unsigned numArgs = proto->getNumArgs();
02336   for (unsigned i = 0; i < numArgs; i++) {
02337     QualType ArgType = proto->getArgType(i);
02338     RewriteBlockPointerType(FdStr, ArgType);
02339     if (i+1 < numArgs)
02340       FdStr += ", ";
02341   }
02342   FdStr +=  ");\n";
02343   InsertText(FunLocStart, FdStr);
02344   CurFunctionDeclToDeclareForBlock = 0;
02345 }
02346 
02347 // SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
02348 void RewriteObjC::SynthSuperContructorFunctionDecl() {
02349   if (SuperContructorFunctionDecl)
02350     return;
02351   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
02352   SmallVector<QualType, 16> ArgTys;
02353   QualType argT = Context->getObjCIdType();
02354   assert(!argT.isNull() && "Can't find 'id' type");
02355   ArgTys.push_back(argT);
02356   ArgTys.push_back(argT);
02357   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02358                                                &ArgTys[0], ArgTys.size());
02359   SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02360                                          SourceLocation(),
02361                                          SourceLocation(),
02362                                          msgSendIdent, msgSendType, 0,
02363                                          SC_Extern,
02364                                          SC_None, false);
02365 }
02366 
02367 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
02368 void RewriteObjC::SynthMsgSendFunctionDecl() {
02369   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
02370   SmallVector<QualType, 16> ArgTys;
02371   QualType argT = Context->getObjCIdType();
02372   assert(!argT.isNull() && "Can't find 'id' type");
02373   ArgTys.push_back(argT);
02374   argT = Context->getObjCSelType();
02375   assert(!argT.isNull() && "Can't find 'SEL' type");
02376   ArgTys.push_back(argT);
02377   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02378                                                &ArgTys[0], ArgTys.size(),
02379                                                true /*isVariadic*/);
02380   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02381                                          SourceLocation(),
02382                                          SourceLocation(),
02383                                          msgSendIdent, msgSendType, 0,
02384                                          SC_Extern,
02385                                          SC_None, false);
02386 }
02387 
02388 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
02389 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
02390   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
02391   SmallVector<QualType, 16> ArgTys;
02392   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
02393                                       SourceLocation(), SourceLocation(),
02394                                       &Context->Idents.get("objc_super"));
02395   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
02396   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
02397   ArgTys.push_back(argT);
02398   argT = Context->getObjCSelType();
02399   assert(!argT.isNull() && "Can't find 'SEL' type");
02400   ArgTys.push_back(argT);
02401   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02402                                                &ArgTys[0], ArgTys.size(),
02403                                                true /*isVariadic*/);
02404   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02405                                               SourceLocation(),
02406                                               SourceLocation(),
02407                                               msgSendIdent, msgSendType, 0,
02408                                               SC_Extern,
02409                                               SC_None, false);
02410 }
02411 
02412 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
02413 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
02414   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
02415   SmallVector<QualType, 16> ArgTys;
02416   QualType argT = Context->getObjCIdType();
02417   assert(!argT.isNull() && "Can't find 'id' type");
02418   ArgTys.push_back(argT);
02419   argT = Context->getObjCSelType();
02420   assert(!argT.isNull() && "Can't find 'SEL' type");
02421   ArgTys.push_back(argT);
02422   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02423                                                &ArgTys[0], ArgTys.size(),
02424                                                true /*isVariadic*/);
02425   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02426                                          SourceLocation(),
02427                                          SourceLocation(),
02428                                          msgSendIdent, msgSendType, 0,
02429                                          SC_Extern,
02430                                          SC_None, false);
02431 }
02432 
02433 // SynthMsgSendSuperStretFunctionDecl -
02434 // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
02435 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
02436   IdentifierInfo *msgSendIdent =
02437     &Context->Idents.get("objc_msgSendSuper_stret");
02438   SmallVector<QualType, 16> ArgTys;
02439   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
02440                                       SourceLocation(), SourceLocation(),
02441                                       &Context->Idents.get("objc_super"));
02442   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
02443   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
02444   ArgTys.push_back(argT);
02445   argT = Context->getObjCSelType();
02446   assert(!argT.isNull() && "Can't find 'SEL' type");
02447   ArgTys.push_back(argT);
02448   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
02449                                                &ArgTys[0], ArgTys.size(),
02450                                                true /*isVariadic*/);
02451   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02452                                                        SourceLocation(),
02453                                                        SourceLocation(),
02454                                               msgSendIdent, msgSendType, 0,
02455                                               SC_Extern,
02456                                               SC_None, false);
02457 }
02458 
02459 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
02460 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
02461   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
02462   SmallVector<QualType, 16> ArgTys;
02463   QualType argT = Context->getObjCIdType();
02464   assert(!argT.isNull() && "Can't find 'id' type");
02465   ArgTys.push_back(argT);
02466   argT = Context->getObjCSelType();
02467   assert(!argT.isNull() && "Can't find 'SEL' type");
02468   ArgTys.push_back(argT);
02469   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
02470                                                &ArgTys[0], ArgTys.size(),
02471                                                true /*isVariadic*/);
02472   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02473                                               SourceLocation(),
02474                                               SourceLocation(),
02475                                               msgSendIdent, msgSendType, 0,
02476                                               SC_Extern,
02477                                               SC_None, false);
02478 }
02479 
02480 // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
02481 void RewriteObjC::SynthGetClassFunctionDecl() {
02482   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
02483   SmallVector<QualType, 16> ArgTys;
02484   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02485   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
02486                                                 &ArgTys[0], ArgTys.size());
02487   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02488                                           SourceLocation(),
02489                                           SourceLocation(),
02490                                           getClassIdent, getClassType, 0,
02491                                           SC_Extern,
02492                                           SC_None, false);
02493 }
02494 
02495 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
02496 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
02497   IdentifierInfo *getSuperClassIdent = 
02498     &Context->Idents.get("class_getSuperclass");
02499   SmallVector<QualType, 16> ArgTys;
02500   ArgTys.push_back(Context->getObjCClassType());
02501   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
02502                                                 &ArgTys[0], ArgTys.size());
02503   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02504                                                    SourceLocation(),
02505                                                    SourceLocation(),
02506                                                    getSuperClassIdent,
02507                                                    getClassType, 0,
02508                                                    SC_Extern,
02509                                                    SC_None,
02510                                                    false);
02511 }
02512 
02513 // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
02514 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
02515   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
02516   SmallVector<QualType, 16> ArgTys;
02517   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
02518   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
02519                                                 &ArgTys[0], ArgTys.size());
02520   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
02521                                               SourceLocation(),
02522                                               SourceLocation(),
02523                                               getClassIdent, getClassType, 0,
02524                                               SC_Extern,
02525                                               SC_None, false);
02526 }
02527 
02528 Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
02529   QualType strType = getConstantStringStructType();
02530 
02531   std::string S = "__NSConstantStringImpl_";
02532 
02533   std::string tmpName = InFileName;
02534   unsigned i;
02535   for (i=0; i < tmpName.length(); i++) {
02536     char c = tmpName.at(i);
02537     // replace any non alphanumeric characters with '_'.
02538     if (!isalpha(c) && (c < '0' || c > '9'))
02539       tmpName[i] = '_';
02540   }
02541   S += tmpName;
02542   S += "_";
02543   S += utostr(NumObjCStringLiterals++);
02544 
02545   Preamble += "static __NSConstantStringImpl " + S;
02546   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
02547   Preamble += "0x000007c8,"; // utf8_str
02548   // The pretty printer for StringLiteral handles escape characters properly.
02549   std::string prettyBufS;
02550   llvm::raw_string_ostream prettyBuf(prettyBufS);
02551   Exp->getString()->printPretty(prettyBuf, *Context, 0,
02552                                 PrintingPolicy(LangOpts));
02553   Preamble += prettyBuf.str();
02554   Preamble += ",";
02555   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
02556 
02557   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
02558                                    SourceLocation(), &Context->Idents.get(S),
02559                                    strType, 0, SC_Static, SC_None);
02560   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
02561                                                SourceLocation());
02562   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
02563                                  Context->getPointerType(DRE->getType()),
02564                                            VK_RValue, OK_Ordinary,
02565                                            SourceLocation());
02566   // cast to NSConstantString *
02567   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
02568                                             CK_CPointerToObjCPointerCast, Unop);
02569   ReplaceStmt(Exp, cast);
02570   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
02571   return cast;
02572 }
02573 
02574 // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
02575 QualType RewriteObjC::getSuperStructType() {
02576   if (!SuperStructDecl) {
02577     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
02578                                          SourceLocation(), SourceLocation(),
02579                                          &Context->Idents.get("objc_super"));
02580     QualType FieldTypes[2];
02581 
02582     // struct objc_object *receiver;
02583     FieldTypes[0] = Context->getObjCIdType();
02584     // struct objc_class *super;
02585     FieldTypes[1] = Context->getObjCClassType();
02586 
02587     // Create fields
02588     for (unsigned i = 0; i < 2; ++i) {
02589       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
02590                                                  SourceLocation(),
02591                                                  SourceLocation(), 0,
02592                                                  FieldTypes[i], 0,
02593                                                  /*BitWidth=*/0,
02594                                                  /*Mutable=*/false,
02595                                                  /*HasInit=*/false));
02596     }
02597 
02598     SuperStructDecl->completeDefinition();
02599   }
02600   return Context->getTagDeclType(SuperStructDecl);
02601 }
02602 
02603 QualType RewriteObjC::getConstantStringStructType() {
02604   if (!ConstantStringDecl) {
02605     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
02606                                             SourceLocation(), SourceLocation(),
02607                          &Context->Idents.get("__NSConstantStringImpl"));
02608     QualType FieldTypes[4];
02609 
02610     // struct objc_object *receiver;
02611     FieldTypes[0] = Context->getObjCIdType();
02612     // int flags;
02613     FieldTypes[1] = Context->IntTy;
02614     // char *str;
02615     FieldTypes[2] = Context->getPointerType(Context->CharTy);
02616     // long length;
02617     FieldTypes[3] = Context->LongTy;
02618 
02619     // Create fields
02620     for (unsigned i = 0; i < 4; ++i) {
02621       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
02622                                                     ConstantStringDecl,
02623                                                     SourceLocation(),
02624                                                     SourceLocation(), 0,
02625                                                     FieldTypes[i], 0,
02626                                                     /*BitWidth=*/0,
02627                                                     /*Mutable=*/true,
02628                                                     /*HasInit=*/false));
02629     }
02630 
02631     ConstantStringDecl->completeDefinition();
02632   }
02633   return Context->getTagDeclType(ConstantStringDecl);
02634 }
02635 
02636 Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
02637                                     SourceLocation StartLoc,
02638                                     SourceLocation EndLoc) {
02639   if (!SelGetUidFunctionDecl)
02640     SynthSelGetUidFunctionDecl();
02641   if (!MsgSendFunctionDecl)
02642     SynthMsgSendFunctionDecl();
02643   if (!MsgSendSuperFunctionDecl)
02644     SynthMsgSendSuperFunctionDecl();
02645   if (!MsgSendStretFunctionDecl)
02646     SynthMsgSendStretFunctionDecl();
02647   if (!MsgSendSuperStretFunctionDecl)
02648     SynthMsgSendSuperStretFunctionDecl();
02649   if (!MsgSendFpretFunctionDecl)
02650     SynthMsgSendFpretFunctionDecl();
02651   if (!GetClassFunctionDecl)
02652     SynthGetClassFunctionDecl();
02653   if (!GetSuperClassFunctionDecl)
02654     SynthGetSuperClassFunctionDecl();
02655   if (!GetMetaClassFunctionDecl)
02656     SynthGetMetaClassFunctionDecl();
02657 
02658   // default to objc_msgSend().
02659   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
02660   // May need to use objc_msgSend_stret() as well.
02661   FunctionDecl *MsgSendStretFlavor = 0;
02662   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
02663     QualType resultType = mDecl->getResultType();
02664     if (resultType->isRecordType())
02665       MsgSendStretFlavor = MsgSendStretFunctionDecl;
02666     else if (resultType->isRealFloatingType())
02667       MsgSendFlavor = MsgSendFpretFunctionDecl;
02668   }
02669 
02670   // Synthesize a call to objc_msgSend().
02671   SmallVector<Expr*, 8> MsgExprs;
02672   switch (Exp->getReceiverKind()) {
02673   case ObjCMessageExpr::SuperClass: {
02674     MsgSendFlavor = MsgSendSuperFunctionDecl;
02675     if (MsgSendStretFlavor)
02676       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
02677     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
02678 
02679     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
02680 
02681     SmallVector<Expr*, 4> InitExprs;
02682 
02683     // set the receiver to self, the first argument to all methods.
02684     InitExprs.push_back(
02685       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
02686                                CK_BitCast,
02687                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
02688                                              false,
02689                                              Context->getObjCIdType(),
02690                                              VK_RValue,
02691                                              SourceLocation()))
02692                         ); // set the 'receiver'.
02693 
02694     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
02695     SmallVector<Expr*, 8> ClsExprs;
02696     QualType argType = Context->getPointerType(Context->CharTy);
02697     ClsExprs.push_back(StringLiteral::Create(*Context,
02698                                    ClassDecl->getIdentifier()->getName(),
02699                                    StringLiteral::Ascii, false,
02700                                    argType, SourceLocation()));
02701     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
02702                                                  &ClsExprs[0],
02703                                                  ClsExprs.size(),
02704                                                  StartLoc,
02705                                                  EndLoc);
02706     // (Class)objc_getClass("CurrentClass")
02707     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
02708                                              Context->getObjCClassType(),
02709                                              CK_BitCast, Cls);
02710     ClsExprs.clear();
02711     ClsExprs.push_back(ArgExpr);
02712     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
02713                                        &ClsExprs[0], ClsExprs.size(),
02714                                        StartLoc, EndLoc);
02715     
02716     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
02717     // To turn off a warning, type-cast to 'id'
02718     InitExprs.push_back( // set 'super class', using class_getSuperclass().
02719                         NoTypeInfoCStyleCastExpr(Context,
02720                                                  Context->getObjCIdType(),
02721                                                  CK_BitCast, Cls));
02722     // struct objc_super
02723     QualType superType = getSuperStructType();
02724     Expr *SuperRep;
02725 
02726     if (LangOpts.MicrosoftExt) {
02727       SynthSuperContructorFunctionDecl();
02728       // Simulate a contructor call...
02729       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
02730                                                    false, superType, VK_LValue,
02731                                                    SourceLocation());
02732       SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
02733                                         InitExprs.size(),
02734                                         superType, VK_LValue,
02735                                         SourceLocation());
02736       // The code for super is a little tricky to prevent collision with
02737       // the structure definition in the header. The rewriter has it's own
02738       // internal definition (__rw_objc_super) that is uses. This is why
02739       // we need the cast below. For example:
02740       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
02741       //
02742       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
02743                                Context->getPointerType(SuperRep->getType()),
02744                                              VK_RValue, OK_Ordinary,
02745                                              SourceLocation());
02746       SuperRep = NoTypeInfoCStyleCastExpr(Context,
02747                                           Context->getPointerType(superType),
02748                                           CK_BitCast, SuperRep);
02749     } else {
02750       // (struct objc_super) { <exprs from above> }
02751       InitListExpr *ILE =
02752         new (Context) InitListExpr(*Context, SourceLocation(),
02753                                    &InitExprs[0], InitExprs.size(),
02754                                    SourceLocation());
02755       TypeSourceInfo *superTInfo
02756         = Context->getTrivialTypeSourceInfo(superType);
02757       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
02758                                                    superType, VK_LValue,
02759                                                    ILE, false);
02760       // struct objc_super *
02761       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
02762                                Context->getPointerType(SuperRep->getType()),
02763                                              VK_RValue, OK_Ordinary,
02764                                              SourceLocation());
02765     }
02766     MsgExprs.push_back(SuperRep);
02767     break;
02768   }
02769 
02770   case ObjCMessageExpr::Class: {
02771     SmallVector<Expr*, 8> ClsExprs;
02772     QualType argType = Context->getPointerType(Context->CharTy);
02773     ObjCInterfaceDecl *Class
02774       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
02775     IdentifierInfo *clsName = Class->getIdentifier();
02776     ClsExprs.push_back(StringLiteral::Create(*Context,
02777                                              clsName->getName(),
02778                                              StringLiteral::Ascii, false,
02779                                              argType, SourceLocation()));
02780     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
02781                                                  &ClsExprs[0],
02782                                                  ClsExprs.size(), 
02783                                                  StartLoc, EndLoc);
02784     MsgExprs.push_back(Cls);
02785     break;
02786   }
02787 
02788   case ObjCMessageExpr::SuperInstance:{
02789     MsgSendFlavor = MsgSendSuperFunctionDecl;
02790     if (MsgSendStretFlavor)
02791       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
02792     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
02793     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
02794     SmallVector<Expr*, 4> InitExprs;
02795 
02796     InitExprs.push_back(
02797       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
02798                                CK_BitCast,
02799                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
02800                                              false,
02801                                              Context->getObjCIdType(),
02802                                              VK_RValue, SourceLocation()))
02803                         ); // set the 'receiver'.
02804     
02805     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
02806     SmallVector<Expr*, 8> ClsExprs;
02807     QualType argType = Context->getPointerType(Context->CharTy);
02808     ClsExprs.push_back(StringLiteral::Create(*Context,
02809                                    ClassDecl->getIdentifier()->getName(),
02810                                    StringLiteral::Ascii, false, argType,
02811                                    SourceLocation()));
02812     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
02813                                                  &ClsExprs[0],
02814                                                  ClsExprs.size(), 
02815                                                  StartLoc, EndLoc);
02816     // (Class)objc_getClass("CurrentClass")
02817     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
02818                                                  Context->getObjCClassType(),
02819                                                  CK_BitCast, Cls);
02820     ClsExprs.clear();
02821     ClsExprs.push_back(ArgExpr);
02822     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
02823                                        &ClsExprs[0], ClsExprs.size(),
02824                                        StartLoc, EndLoc);
02825     
02826     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
02827     // To turn off a warning, type-cast to 'id'
02828     InitExprs.push_back(
02829       // set 'super class', using class_getSuperclass().
02830       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
02831                                CK_BitCast, Cls));
02832     // struct objc_super
02833     QualType superType = getSuperStructType();
02834     Expr *SuperRep;
02835 
02836     if (LangOpts.MicrosoftExt) {
02837       SynthSuperContructorFunctionDecl();
02838       // Simulate a contructor call...
02839       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
02840                                                    false, superType, VK_LValue,
02841                                                    SourceLocation());
02842       SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
02843                                         InitExprs.size(),
02844                                         superType, VK_LValue, SourceLocation());
02845       // The code for super is a little tricky to prevent collision with
02846       // the structure definition in the header. The rewriter has it's own
02847       // internal definition (__rw_objc_super) that is uses. This is why
02848       // we need the cast below. For example:
02849       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
02850       //
02851       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
02852                                Context->getPointerType(SuperRep->getType()),
02853                                VK_RValue, OK_Ordinary,
02854                                SourceLocation());
02855       SuperRep = NoTypeInfoCStyleCastExpr(Context,
02856                                Context->getPointerType(superType),
02857                                CK_BitCast, SuperRep);
02858     } else {
02859       // (struct objc_super) { <exprs from above> }
02860       InitListExpr *ILE =
02861         new (Context) InitListExpr(*Context, SourceLocation(),
02862                                    &InitExprs[0], InitExprs.size(),
02863                                    SourceLocation());
02864       TypeSourceInfo *superTInfo
02865         = Context->getTrivialTypeSourceInfo(superType);
02866       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
02867                                                    superType, VK_RValue, ILE,
02868                                                    false);
02869     }
02870     MsgExprs.push_back(SuperRep);
02871     break;
02872   }
02873 
02874   case ObjCMessageExpr::Instance: {
02875     // Remove all type-casts because it may contain objc-style types; e.g.
02876     // Foo<Proto> *.
02877     Expr *recExpr = Exp->getInstanceReceiver();
02878     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
02879       recExpr = CE->getSubExpr();
02880     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
02881                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
02882                                      ? CK_BlockPointerToObjCPointerCast
02883                                      : CK_CPointerToObjCPointerCast;
02884 
02885     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
02886                                        CK, recExpr);
02887     MsgExprs.push_back(recExpr);
02888     break;
02889   }
02890   }
02891 
02892   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
02893   SmallVector<Expr*, 8> SelExprs;
02894   QualType argType = Context->getPointerType(Context->CharTy);
02895   SelExprs.push_back(StringLiteral::Create(*Context,
02896                                        Exp->getSelector().getAsString(),
02897                                        StringLiteral::Ascii, false,
02898                                        argType, SourceLocation()));
02899   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
02900                                                  &SelExprs[0], SelExprs.size(),
02901                                                   StartLoc,
02902                                                   EndLoc);
02903   MsgExprs.push_back(SelExp);
02904 
02905   // Now push any user supplied arguments.
02906   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
02907     Expr *userExpr = Exp->getArg(i);
02908     // Make all implicit casts explicit...ICE comes in handy:-)
02909     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
02910       // Reuse the ICE type, it is exactly what the doctor ordered.
02911       QualType type = ICE->getType();
02912       if (needToScanForQualifiers(type))
02913         type = Context->getObjCIdType();
02914       // Make sure we convert "type (^)(...)" to "type (*)(...)".
02915       (void)convertBlockPointerToFunctionPointer(type);
02916       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
02917       CastKind CK;
02918       if (SubExpr->getType()->isIntegralType(*Context) && 
02919           type->isBooleanType()) {
02920         CK = CK_IntegralToBoolean;
02921       } else if (type->isObjCObjectPointerType()) {
02922         if (SubExpr->getType()->isBlockPointerType()) {
02923           CK = CK_BlockPointerToObjCPointerCast;
02924         } else if (SubExpr->getType()->isPointerType()) {
02925           CK = CK_CPointerToObjCPointerCast;
02926         } else {
02927           CK = CK_BitCast;
02928         }
02929       } else {
02930         CK = CK_BitCast;
02931       }
02932 
02933       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
02934     }
02935     // Make id<P...> cast into an 'id' cast.
02936     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
02937       if (CE->getType()->isObjCQualifiedIdType()) {
02938         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
02939           userExpr = CE->getSubExpr();
02940         CastKind CK;
02941         if (userExpr->getType()->isIntegralType(*Context)) {
02942           CK = CK_IntegralToPointer;
02943         } else if (userExpr->getType()->isBlockPointerType()) {
02944           CK = CK_BlockPointerToObjCPointerCast;
02945         } else if (userExpr->getType()->isPointerType()) {
02946           CK = CK_CPointerToObjCPointerCast;
02947         } else {
02948           CK = CK_BitCast;
02949         }
02950         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
02951                                             CK, userExpr);
02952       }
02953     }
02954     MsgExprs.push_back(userExpr);
02955     // We've transferred the ownership to MsgExprs. For now, we *don't* null
02956     // out the argument in the original expression (since we aren't deleting
02957     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
02958     //Exp->setArg(i, 0);
02959   }
02960   // Generate the funky cast.
02961   CastExpr *cast;
02962   SmallVector<QualType, 8> ArgTypes;
02963   QualType returnType;
02964 
02965   // Push 'id' and 'SEL', the 2 implicit arguments.
02966   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
02967     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
02968   else
02969     ArgTypes.push_back(Context->getObjCIdType());
02970   ArgTypes.push_back(Context->getObjCSelType());
02971   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
02972     // Push any user argument types.
02973     for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
02974          E = OMD->param_end(); PI != E; ++PI) {
02975       QualType t = (*PI)->getType()->isObjCQualifiedIdType()
02976                      ? Context->getObjCIdType()
02977                      : (*PI)->getType();
02978       // Make sure we convert "t (^)(...)" to "t (*)(...)".
02979       (void)convertBlockPointerToFunctionPointer(t);
02980       ArgTypes.push_back(t);
02981     }
02982     returnType = Exp->getType();
02983     convertToUnqualifiedObjCType(returnType);
02984     (void)convertBlockPointerToFunctionPointer(returnType);
02985   } else {
02986     returnType = Context->getObjCIdType();
02987   }
02988   // Get the type, we will need to reference it in a couple spots.
02989   QualType msgSendType = MsgSendFlavor->getType();
02990 
02991   // Create a reference to the objc_msgSend() declaration.
02992   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
02993                                                VK_LValue, SourceLocation());
02994 
02995   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
02996   // If we don't do this cast, we get the following bizarre warning/note:
02997   // xx.m:13: warning: function called through a non-compatible type
02998   // xx.m:13: note: if this code is reached, the program will abort
02999   cast = NoTypeInfoCStyleCastExpr(Context,
03000                                   Context->getPointerType(Context->VoidTy),
03001                                   CK_BitCast, DRE);
03002 
03003   // Now do the "normal" pointer to function cast.
03004   QualType castType =
03005     getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
03006       // If we don't have a method decl, force a variadic cast.
03007       Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
03008   castType = Context->getPointerType(castType);
03009   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
03010                                   cast);
03011 
03012   // Don't forget the parens to enforce the proper binding.
03013   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
03014 
03015   const FunctionType *FT = msgSendType->getAs<FunctionType>();
03016   CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
03017                                         MsgExprs.size(),
03018                                         FT->getResultType(), VK_RValue,
03019                                         EndLoc);
03020   Stmt *ReplacingStmt = CE;
03021   if (MsgSendStretFlavor) {
03022     // We have the method which returns a struct/union. Must also generate
03023     // call to objc_msgSend_stret and hang both varieties on a conditional
03024     // expression which dictate which one to envoke depending on size of
03025     // method's return type.
03026 
03027     // Create a reference to the objc_msgSend_stret() declaration.
03028     DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
03029                                                    false, msgSendType,
03030                                                    VK_LValue, SourceLocation());
03031     // Need to cast objc_msgSend_stret to "void *" (see above comment).
03032     cast = NoTypeInfoCStyleCastExpr(Context,
03033                                     Context->getPointerType(Context->VoidTy),
03034                                     CK_BitCast, STDRE);
03035     // Now do the "normal" pointer to function cast.
03036     castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
03037       Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
03038     castType = Context->getPointerType(castType);
03039     cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
03040                                     cast);
03041 
03042     // Don't forget the parens to enforce the proper binding.
03043     PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
03044 
03045     FT = msgSendType->getAs<FunctionType>();
03046     CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
03047                                             MsgExprs.size(),
03048                                             FT->getResultType(), VK_RValue,
03049                                             SourceLocation());
03050 
03051     // Build sizeof(returnType)
03052     UnaryExprOrTypeTraitExpr *sizeofExpr =
03053        new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
03054                                  Context->getTrivialTypeSourceInfo(returnType),
03055                                  Context->getSizeType(), SourceLocation(),
03056                                  SourceLocation());
03057     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
03058     // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
03059     // For X86 it is more complicated and some kind of target specific routine
03060     // is needed to decide what to do.
03061     unsigned IntSize =
03062       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
03063     IntegerLiteral *limit = IntegerLiteral::Create(*Context,
03064                                                    llvm::APInt(IntSize, 8),
03065                                                    Context->IntTy,
03066                                                    SourceLocation());
03067     BinaryOperator *lessThanExpr = 
03068       new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
03069                                    VK_RValue, OK_Ordinary, SourceLocation());
03070     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
03071     ConditionalOperator *CondExpr =
03072       new (Context) ConditionalOperator(lessThanExpr,
03073                                         SourceLocation(), CE,
03074                                         SourceLocation(), STCE,
03075                                         returnType, VK_RValue, OK_Ordinary);
03076     ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
03077                                             CondExpr);
03078   }
03079   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03080   return ReplacingStmt;
03081 }
03082 
03083 Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
03084   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
03085                                          Exp->getLocEnd());
03086 
03087   // Now do the actual rewrite.
03088   ReplaceStmt(Exp, ReplacingStmt);
03089 
03090   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03091   return ReplacingStmt;
03092 }
03093 
03094 // typedef struct objc_object Protocol;
03095 QualType RewriteObjC::getProtocolType() {
03096   if (!ProtocolTypeDecl) {
03097     TypeSourceInfo *TInfo
03098       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
03099     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
03100                                            SourceLocation(), SourceLocation(),
03101                                            &Context->Idents.get("Protocol"),
03102                                            TInfo);
03103   }
03104   return Context->getTypeDeclType(ProtocolTypeDecl);
03105 }
03106 
03107 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
03108 /// a synthesized/forward data reference (to the protocol's metadata).
03109 /// The forward references (and metadata) are generated in
03110 /// RewriteObjC::HandleTranslationUnit().
03111 Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
03112   std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
03113   IdentifierInfo *ID = &Context->Idents.get(Name);
03114   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
03115                                 SourceLocation(), ID, getProtocolType(), 0,
03116                                 SC_Extern, SC_None);
03117   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
03118                                                VK_LValue, SourceLocation());
03119   Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
03120                              Context->getPointerType(DRE->getType()),
03121                              VK_RValue, OK_Ordinary, SourceLocation());
03122   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
03123                                                 CK_BitCast,
03124                                                 DerefExpr);
03125   ReplaceStmt(Exp, castExpr);
03126   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
03127   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
03128   return castExpr;
03129 
03130 }
03131 
03132 bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
03133                                              const char *endBuf) {
03134   while (startBuf < endBuf) {
03135     if (*startBuf == '#') {
03136       // Skip whitespace.
03137       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
03138         ;
03139       if (!strncmp(startBuf, "if", strlen("if")) ||
03140           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
03141           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
03142           !strncmp(startBuf, "define", strlen("define")) ||
03143           !strncmp(startBuf, "undef", strlen("undef")) ||
03144           !strncmp(startBuf, "else", strlen("else")) ||
03145           !strncmp(startBuf, "elif", strlen("elif")) ||
03146           !strncmp(startBuf, "endif", strlen("endif")) ||
03147           !strncmp(startBuf, "pragma", strlen("pragma")) ||
03148           !strncmp(startBuf, "include", strlen("include")) ||
03149           !strncmp(startBuf, "import", strlen("import")) ||
03150           !strncmp(startBuf, "include_next", strlen("include_next")))
03151         return true;
03152     }
03153     startBuf++;
03154   }
03155   return false;
03156 }
03157 
03158 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
03159 /// an objective-c class with ivars.
03160 void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
03161                                                std::string &Result) {
03162   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
03163   assert(CDecl->getName() != "" &&
03164          "Name missing in SynthesizeObjCInternalStruct");
03165   // Do not synthesize more than once.
03166   if (ObjCSynthesizedStructs.count(CDecl))
03167     return;
03168   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
03169   int NumIvars = CDecl->ivar_size();
03170   SourceLocation LocStart = CDecl->getLocStart();
03171   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
03172 
03173   const char *startBuf = SM->getCharacterData(LocStart);
03174   const char *endBuf = SM->getCharacterData(LocEnd);
03175 
03176   // If no ivars and no root or if its root, directly or indirectly,
03177   // have no ivars (thus not synthesized) then no need to synthesize this class.
03178   if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
03179       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
03180     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
03181     ReplaceText(LocStart, endBuf-startBuf, Result);
03182     return;
03183   }
03184 
03185   // FIXME: This has potential of causing problem. If
03186   // SynthesizeObjCInternalStruct is ever called recursively.
03187   Result += "\nstruct ";
03188   Result += CDecl->getNameAsString();
03189   if (LangOpts.MicrosoftExt)
03190     Result += "_IMPL";
03191 
03192   if (NumIvars > 0) {
03193     const char *cursor = strchr(startBuf, '{');
03194     assert((cursor && endBuf)
03195            && "SynthesizeObjCInternalStruct - malformed @interface");
03196     // If the buffer contains preprocessor directives, we do more fine-grained
03197     // rewrites. This is intended to fix code that looks like (which occurs in
03198     // NSURL.h, for example):
03199     //
03200     // #ifdef XYZ
03201     // @interface Foo : NSObject
03202     // #else
03203     // @interface FooBar : NSObject
03204     // #endif
03205     // {
03206     //    int i;
03207     // }
03208     // @end
03209     //
03210     // This clause is segregated to avoid breaking the common case.
03211     if (BufferContainsPPDirectives(startBuf, cursor)) {
03212       SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
03213                                   CDecl->getAtStartLoc();
03214       const char *endHeader = SM->getCharacterData(L);
03215       endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
03216 
03217       if (CDecl->protocol_begin() != CDecl->protocol_end()) {
03218         // advance to the end of the referenced protocols.
03219         while (endHeader < cursor && *endHeader != '>') endHeader++;
03220         endHeader++;
03221       }
03222       // rewrite the original header
03223       ReplaceText(LocStart, endHeader-startBuf, Result);
03224     } else {
03225       // rewrite the original header *without* disturbing the '{'
03226       ReplaceText(LocStart, cursor-startBuf, Result);
03227     }
03228     if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
03229       Result = "\n    struct ";
03230       Result += RCDecl->getNameAsString();
03231       Result += "_IMPL ";
03232       Result += RCDecl->getNameAsString();
03233       Result += "_IVARS;\n";
03234 
03235       // insert the super class structure definition.
03236       SourceLocation OnePastCurly =
03237         LocStart.getLocWithOffset(cursor-startBuf+1);
03238       InsertText(OnePastCurly, Result);
03239     }
03240     cursor++; // past '{'
03241 
03242     // Now comment out any visibility specifiers.
03243     while (cursor < endBuf) {
03244       if (*cursor == '@') {
03245         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
03246         // Skip whitespace.
03247         for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
03248           /*scan*/;
03249 
03250         // FIXME: presence of @public, etc. inside comment results in
03251         // this transformation as well, which is still correct c-code.
03252         if (!strncmp(cursor, "public", strlen("public")) ||
03253             !strncmp(cursor, "private", strlen("private")) ||
03254             !strncmp(cursor, "package", strlen("package")) ||
03255             !strncmp(cursor, "protected", strlen("protected")))
03256           InsertText(atLoc, "// ");
03257       }
03258       // FIXME: If there are cases where '<' is used in ivar declaration part
03259       // of user code, then scan the ivar list and use needToScanForQualifiers
03260       // for type checking.
03261       else if (*cursor == '<') {
03262         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
03263         InsertText(atLoc, "/* ");
03264         cursor = strchr(cursor, '>');
03265         cursor++;
03266         atLoc = LocStart.getLocWithOffset(cursor-startBuf);
03267         InsertText(atLoc, " */");
03268       } else if (*cursor == '^') { // rewrite block specifier.
03269         SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
03270         ReplaceText(caretLoc, 1, "*");
03271       }
03272       cursor++;
03273     }
03274     // Don't forget to add a ';'!!
03275     InsertText(LocEnd.getLocWithOffset(1), ";");
03276   } else { // we don't have any instance variables - insert super struct.
03277     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
03278     Result += " {\n    struct ";
03279     Result += RCDecl->getNameAsString();
03280     Result += "_IMPL ";
03281     Result += RCDecl->getNameAsString();
03282     Result += "_IVARS;\n};\n";
03283     ReplaceText(LocStart, endBuf-startBuf, Result);
03284   }
03285   // Mark this struct as having been generated.
03286   if (!ObjCSynthesizedStructs.insert(CDecl))
03287     llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
03288 }
03289 
03290 //===----------------------------------------------------------------------===//
03291 // Meta Data Emission
03292 //===----------------------------------------------------------------------===//
03293 
03294 
03295 /// RewriteImplementations - This routine rewrites all method implementations
03296 /// and emits meta-data.
03297 
03298 void RewriteObjC::RewriteImplementations() {
03299   int ClsDefCount = ClassImplementation.size();
03300   int CatDefCount = CategoryImplementation.size();
03301 
03302   // Rewrite implemented methods
03303   for (int i = 0; i < ClsDefCount; i++)
03304     RewriteImplementationDecl(ClassImplementation[i]);
03305 
03306   for (int i = 0; i < CatDefCount; i++)
03307     RewriteImplementationDecl(CategoryImplementation[i]);
03308 }
03309 
03310 void RewriteObjC::RewriteByRefString(std::string &ResultStr, 
03311                                      const std::string &Name,
03312                                      ValueDecl *VD, bool def) {
03313   assert(BlockByRefDeclNo.count(VD) && 
03314          "RewriteByRefString: ByRef decl missing");
03315   if (def)
03316     ResultStr += "struct ";
03317   ResultStr += "__Block_byref_" + Name + 
03318     "_" + utostr(BlockByRefDeclNo[VD]) ;
03319 }
03320 
03321 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
03322   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
03323     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
03324   return false;
03325 }
03326 
03327 std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
03328                                                    StringRef funcName,
03329                                                    std::string Tag) {
03330   const FunctionType *AFT = CE->getFunctionType();
03331   QualType RT = AFT->getResultType();
03332   std::string StructRef = "struct " + Tag;
03333   std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
03334                   funcName.str() + "_" + "block_func_" + utostr(i);
03335 
03336   BlockDecl *BD = CE->getBlockDecl();
03337 
03338   if (isa<FunctionNoProtoType>(AFT)) {
03339     // No user-supplied arguments. Still need to pass in a pointer to the
03340     // block (to reference imported block decl refs).
03341     S += "(" + StructRef + " *__cself)";
03342   } else if (BD->param_empty()) {
03343     S += "(" + StructRef + " *__cself)";
03344   } else {
03345     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
03346     assert(FT && "SynthesizeBlockFunc: No function proto");
03347     S += '(';
03348     // first add the implicit argument.
03349     S += StructRef + " *__cself, ";
03350     std::string ParamStr;
03351     for (BlockDecl::param_iterator AI = BD->param_begin(),
03352          E = BD->param_end(); AI != E; ++AI) {
03353       if (AI != BD->param_begin()) S += ", ";
03354       ParamStr = (*AI)->getNameAsString();
03355       QualType QT = (*AI)->getType();
03356       (void)convertBlockPointerToFunctionPointer(QT);
03357       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
03358       S += ParamStr;
03359     }
03360     if (FT->isVariadic()) {
03361       if (!BD->param_empty()) S += ", ";
03362       S += "...";
03363     }
03364     S += ')';
03365   }
03366   S += " {\n";
03367 
03368   // Create local declarations to avoid rewriting all closure decl ref exprs.
03369   // First, emit a declaration for all "by ref" decls.
03370   for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
03371        E = BlockByRefDecls.end(); I != E; ++I) {
03372     S += "  ";
03373     std::string Name = (*I)->getNameAsString();
03374     std::string TypeString;
03375     RewriteByRefString(TypeString, Name, (*I));
03376     TypeString += " *";
03377     Name = TypeString + Name;
03378     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
03379   }
03380   // Next, emit a declaration for all "by copy" declarations.
03381   for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
03382        E = BlockByCopyDecls.end(); I != E; ++I) {
03383     S += "  ";
03384     // Handle nested closure invocation. For example:
03385     //
03386     //   void (^myImportedClosure)(void);
03387     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
03388     //
03389     //   void (^anotherClosure)(void);
03390     //   anotherClosure = ^(void) {
03391     //     myImportedClosure(); // import and invoke the closure
03392     //   };
03393     //
03394     if (isTopLevelBlockPointerType((*I)->getType())) {
03395       RewriteBlockPointerTypeVariable(S, (*I));
03396       S += " = (";
03397       RewriteBlockPointerType(S, (*I)->getType());
03398       S += ")";
03399       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
03400     }
03401     else {
03402       std::string Name = (*I)->getNameAsString();
03403       QualType QT = (*I)->getType();
03404       if (HasLocalVariableExternalStorage(*I))
03405         QT = Context->getPointerType(QT);
03406       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
03407       S += Name + " = __cself->" + 
03408                               (*I)->getNameAsString() + "; // bound by copy\n";
03409     }
03410   }
03411   std::string RewrittenStr = RewrittenBlockExprs[CE];
03412   const char *cstr = RewrittenStr.c_str();
03413   while (*cstr++ != '{') ;
03414   S += cstr;
03415   S += "\n";
03416   return S;
03417 }
03418 
03419 std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
03420                                                    StringRef funcName,
03421                                                    std::string Tag) {
03422   std::string StructRef = "struct " + Tag;
03423   std::string S = "static void __";
03424 
03425   S += funcName;
03426   S += "_block_copy_" + utostr(i);
03427   S += "(" + StructRef;
03428   S += "*dst, " + StructRef;
03429   S += "*src) {";
03430   for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
03431       E = ImportedBlockDecls.end(); I != E; ++I) {
03432     ValueDecl *VD = (*I);
03433     S += "_Block_object_assign((void*)&dst->";
03434     S += (*I)->getNameAsString();
03435     S += ", (void*)src->";
03436     S += (*I)->getNameAsString();
03437     if (BlockByRefDeclsPtrSet.count((*I)))
03438       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
03439     else if (VD->getType()->isBlockPointerType())
03440       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
03441     else
03442       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
03443   }
03444   S += "}\n";
03445   
03446   S += "\nstatic void __";
03447   S += funcName;
03448   S += "_block_dispose_" + utostr(i);
03449   S += "(" + StructRef;
03450   S += "*src) {";
03451   for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
03452       E = ImportedBlockDecls.end(); I != E; ++I) {
03453     ValueDecl *VD = (*I);
03454     S += "_Block_object_dispose((void*)src->";
03455     S += (*I)->getNameAsString();
03456     if (BlockByRefDeclsPtrSet.count((*I)))
03457       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
03458     else if (VD->getType()->isBlockPointerType())
03459       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
03460     else
03461       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
03462   }
03463   S += "}\n";
03464   return S;
03465 }
03466 
03467 std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, 
03468                                              std::string Desc) {
03469   std::string S = "\nstruct " + Tag;
03470   std::string Constructor = "  " + Tag;
03471 
03472   S += " {\n  struct __block_impl impl;\n";
03473   S += "  struct " + Desc;
03474   S += "* Desc;\n";
03475 
03476   Constructor += "(void *fp, "; // Invoke function pointer.
03477   Constructor += "struct " + Desc; // Descriptor pointer.
03478   Constructor += " *desc";
03479 
03480   if (BlockDeclRefs.size()) {
03481     // Output all "by copy" declarations.
03482     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
03483          E = BlockByCopyDecls.end(); I != E; ++I) {
03484       S += "  ";
03485       std::string FieldName = (*I)->getNameAsString();
03486       std::string ArgName = "_" + FieldName;
03487       // Handle nested closure invocation. For example:
03488       //
03489       //   void (^myImportedBlock)(void);
03490       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
03491       //
03492       //   void (^anotherBlock)(void);
03493       //   anotherBlock = ^(void) {
03494       //     myImportedBlock(); // import and invoke the closure
03495       //   };
03496       //
03497       if (isTopLevelBlockPointerType((*I)->getType())) {
03498         S += "struct __block_impl *";
03499         Constructor += ", void *" + ArgName;
03500       } else {
03501         QualType QT = (*I)->getType();
03502         if (HasLocalVariableExternalStorage(*I))
03503           QT = Context->getPointerType(QT);
03504         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
03505         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
03506         Constructor += ", " + ArgName;
03507       }
03508       S += FieldName + ";\n";
03509     }
03510     // Output all "by ref" declarations.
03511     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
03512          E = BlockByRefDecls.end(); I != E; ++I) {
03513       S += "  ";
03514       std::string FieldName = (*I)->getNameAsString();
03515       std::string ArgName = "_" + FieldName;
03516       {
03517         std::string TypeString;
03518         RewriteByRefString(TypeString, FieldName, (*I));
03519         TypeString += " *";
03520         FieldName = TypeString + FieldName;
03521         ArgName = TypeString + ArgName;
03522         Constructor += ", " + ArgName;
03523       }
03524       S += FieldName + "; // by ref\n";
03525     }
03526     // Finish writing the constructor.
03527     Constructor += ", int flags=0)";
03528     // Initialize all "by copy" arguments.
03529     bool firsTime = true;
03530     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
03531          E = BlockByCopyDecls.end(); I != E; ++I) {
03532       std::string Name = (*I)->getNameAsString();
03533         if (firsTime) {
03534           Constructor += " : ";
03535           firsTime = false;
03536         }
03537         else
03538           Constructor += ", ";
03539         if (isTopLevelBlockPointerType((*I)->getType()))
03540           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
03541         else
03542           Constructor += Name + "(_" + Name + ")";
03543     }
03544     // Initialize all "by ref" arguments.
03545     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
03546          E = BlockByRefDecls.end(); I != E; ++I) {
03547       std::string Name = (*I)->getNameAsString();
03548       if (firsTime) {
03549         Constructor += " : ";
03550         firsTime = false;
03551       }
03552       else
03553         Constructor += ", ";
03554       Constructor += Name + "(_" + Name + "->__forwarding)";
03555     }
03556     
03557     Constructor += " {\n";
03558     if (GlobalVarDecl)
03559       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
03560     else
03561       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
03562     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
03563 
03564     Constructor += "    Desc = desc;\n";
03565   } else {
03566     // Finish writing the constructor.
03567     Constructor += ", int flags=0) {\n";
03568     if (GlobalVarDecl)
03569       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
03570     else
03571       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
03572     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
03573     Constructor += "    Desc = desc;\n";
03574   }
03575   Constructor += "  ";
03576   Constructor += "}\n";
03577   S += Constructor;
03578   S += "};\n";
03579   return S;
03580 }
03581 
03582 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, 
03583                                                    std::string ImplTag, int i,
03584                                                    StringRef FunName,
03585                                                    unsigned hasCopy) {
03586   std::string S = "\nstatic struct " + DescTag;
03587   
03588   S += " {\n  unsigned long reserved;\n";
03589   S += "  unsigned long Block_size;\n";
03590   if (hasCopy) {
03591     S += "  void (*copy)(struct ";
03592     S += ImplTag; S += "*, struct ";
03593     S += ImplTag; S += "*);\n";
03594     
03595     S += "  void (*dispose)(struct ";
03596     S += ImplTag; S += "*);\n";
03597   }
03598   S += "} ";
03599 
03600   S += DescTag + "_DATA = { 0, sizeof(struct ";
03601   S += ImplTag + ")";
03602   if (hasCopy) {
03603     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
03604     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
03605   }
03606   S += "};\n";
03607   return S;
03608 }
03609 
03610 void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
03611                                           StringRef FunName) {
03612   // Insert declaration for the function in which block literal is used.
03613   if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
03614     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
03615   bool RewriteSC = (GlobalVarDecl &&
03616                     !Blocks.empty() &&
03617                     GlobalVarDecl->getStorageClass() == SC_Static &&
03618                     GlobalVarDecl->getType().getCVRQualifiers());
03619   if (RewriteSC) {
03620     std::string SC(" void __");
03621     SC += GlobalVarDecl->getNameAsString();
03622     SC += "() {}";
03623     InsertText(FunLocStart, SC);
03624   }
03625   
03626   // Insert closures that were part of the function.
03627   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
03628     CollectBlockDeclRefInfo(Blocks[i]);
03629     // Need to copy-in the inner copied-in variables not actually used in this
03630     // block.
03631     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
03632       DeclRefExpr *Exp = InnerDeclRefs[count++];
03633       ValueDecl *VD = Exp->getDecl();
03634       BlockDeclRefs.push_back(Exp);
03635       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
03636         BlockByCopyDeclsPtrSet.insert(VD);
03637         BlockByCopyDecls.push_back(VD);
03638       }
03639       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
03640         BlockByRefDeclsPtrSet.insert(VD);
03641         BlockByRefDecls.push_back(VD);
03642       }
03643       // imported objects in the inner blocks not used in the outer
03644       // blocks must be copied/disposed in the outer block as well.
03645       if (VD->hasAttr<BlocksAttr>() ||
03646           VD->getType()->isObjCObjectPointerType() || 
03647           VD->getType()->isBlockPointerType())
03648         ImportedBlockDecls.insert(VD);
03649     }
03650 
03651     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
03652     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
03653 
03654     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
03655 
03656     InsertText(FunLocStart, CI);
03657 
03658     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
03659 
03660     InsertText(FunLocStart, CF);
03661 
03662     if (ImportedBlockDecls.size()) {
03663       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
03664       InsertText(FunLocStart, HF);
03665     }
03666     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
03667                                                ImportedBlockDecls.size() > 0);
03668     InsertText(FunLocStart, BD);
03669 
03670     BlockDeclRefs.clear();
03671     BlockByRefDecls.clear();
03672     BlockByRefDeclsPtrSet.clear();
03673     BlockByCopyDecls.clear();
03674     BlockByCopyDeclsPtrSet.clear();
03675     ImportedBlockDecls.clear();
03676   }
03677   if (RewriteSC) {
03678     // Must insert any 'const/volatile/static here. Since it has been
03679     // removed as result of rewriting of block literals.
03680     std::string SC;
03681     if (GlobalVarDecl->getStorageClass() == SC_Static)
03682       SC = "static ";
03683     if (GlobalVarDecl->getType().isConstQualified())
03684       SC += "const ";
03685     if (GlobalVarDecl->getType().isVolatileQualified())
03686       SC += "volatile ";
03687     if (GlobalVarDecl->getType().isRestrictQualified())
03688       SC += "restrict ";
03689     InsertText(FunLocStart, SC);
03690   }
03691   
03692   Blocks.clear();
03693   InnerDeclRefsCount.clear();
03694   InnerDeclRefs.clear();
03695   RewrittenBlockExprs.clear();
03696 }
03697 
03698 void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
03699   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
03700   StringRef FuncName = FD->getName();
03701 
03702   SynthesizeBlockLiterals(FunLocStart, FuncName);
03703 }
03704 
03705 static void BuildUniqueMethodName(std::string &Name,
03706                                   ObjCMethodDecl *MD) {
03707   ObjCInterfaceDecl *IFace = MD->getClassInterface();
03708   Name = IFace->getName();
03709   Name += "__" + MD->getSelector().getAsString();
03710   // Convert colons to underscores.
03711   std::string::size_type loc = 0;
03712   while ((loc = Name.find(":", loc)) != std::string::npos)
03713     Name.replace(loc, 1, "_");
03714 }
03715 
03716 void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
03717   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
03718   //SourceLocation FunLocStart = MD->getLocStart();
03719   SourceLocation FunLocStart = MD->getLocStart();
03720   std::string FuncName;
03721   BuildUniqueMethodName(FuncName, MD);
03722   SynthesizeBlockLiterals(FunLocStart, FuncName);
03723 }
03724 
03725 void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
03726   for (Stmt::child_range CI = S->children(); CI; ++CI)
03727     if (*CI) {
03728       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
03729         GetBlockDeclRefExprs(CBE->getBody());
03730       else
03731         GetBlockDeclRefExprs(*CI);
03732     }
03733   // Handle specific things.
03734   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
03735     if (DRE->refersToEnclosingLocal()) {
03736       // FIXME: Handle enums.
03737       if (!isa<FunctionDecl>(DRE->getDecl()))
03738         BlockDeclRefs.push_back(DRE);
03739       if (HasLocalVariableExternalStorage(DRE->getDecl()))
03740         BlockDeclRefs.push_back(DRE);
03741     }
03742   }
03743   
03744   return;
03745 }
03746 
03747 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S, 
03748                 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
03749                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
03750   for (Stmt::child_range CI = S->children(); CI; ++CI)
03751     if (*CI) {
03752       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
03753         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
03754         GetInnerBlockDeclRefExprs(CBE->getBody(),
03755                                   InnerBlockDeclRefs,
03756                                   InnerContexts);
03757       }
03758       else
03759         GetInnerBlockDeclRefExprs(*CI,
03760                                   InnerBlockDeclRefs,
03761                                   InnerContexts);
03762 
03763     }
03764   // Handle specific things.
03765   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
03766     if (DRE->refersToEnclosingLocal()) {
03767       if (!isa<FunctionDecl>(DRE->getDecl()) &&
03768           !InnerContexts.count(DRE->getDecl()->getDeclContext()))
03769         InnerBlockDeclRefs.push_back(DRE);
03770       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
03771         if (Var->isFunctionOrMethodVarDecl())
03772           ImportedLocalExternalDecls.insert(Var);
03773     }
03774   }
03775   
03776   return;
03777 }
03778 
03779 /// convertFunctionTypeOfBlocks - This routine converts a function type
03780 /// whose result type may be a block pointer or whose argument type(s)
03781 /// might be block pointers to an equivalent function type replacing
03782 /// all block pointers to function pointers.
03783 QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
03784   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
03785   // FTP will be null for closures that don't take arguments.
03786   // Generate a funky cast.
03787   SmallVector<QualType, 8> ArgTypes;
03788   QualType Res = FT->getResultType();
03789   bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
03790   
03791   if (FTP) {
03792     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
03793          E = FTP->arg_type_end(); I && (I != E); ++I) {
03794       QualType t = *I;
03795       // Make sure we convert "t (^)(...)" to "t (*)(...)".
03796       if (convertBlockPointerToFunctionPointer(t))
03797         HasBlockType = true;
03798       ArgTypes.push_back(t);
03799     }
03800   }
03801   QualType FuncType;
03802   // FIXME. Does this work if block takes no argument but has a return type
03803   // which is of block type?
03804   if (HasBlockType)
03805     FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
03806   else FuncType = QualType(FT, 0);
03807   return FuncType;
03808 }
03809 
03810 Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
03811   // Navigate to relevant type information.
03812   const BlockPointerType *CPT = 0;
03813 
03814   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
03815     CPT = DRE->getType()->getAs<BlockPointerType>();
03816   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
03817     CPT = MExpr->getType()->getAs<BlockPointerType>();
03818   } 
03819   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
03820     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
03821   }
03822   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) 
03823     CPT = IEXPR->getType()->getAs<BlockPointerType>();
03824   else if (const ConditionalOperator *CEXPR = 
03825             dyn_cast<ConditionalOperator>(BlockExp)) {
03826     Expr *LHSExp = CEXPR->getLHS();
03827     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
03828     Expr *RHSExp = CEXPR->getRHS();
03829     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
03830     Expr *CONDExp = CEXPR->getCond();
03831     ConditionalOperator *CondExpr =
03832       new (Context) ConditionalOperator(CONDExp,
03833                                       SourceLocation(), cast<Expr>(LHSStmt),
03834                                       SourceLocation(), cast<Expr>(RHSStmt),
03835                                       Exp->getType(), VK_RValue, OK_Ordinary);
03836     return CondExpr;
03837   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
03838     CPT = IRE->getType()->getAs<BlockPointerType>();
03839   } else if (const PseudoObjectExpr *POE
03840                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
03841     CPT = POE->getType()->castAs<BlockPointerType>();
03842   } else {
03843     assert(1 && "RewriteBlockClass: Bad type");
03844   }
03845   assert(CPT && "RewriteBlockClass: Bad type");
03846   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
03847   assert(FT && "RewriteBlockClass: Bad type");
03848   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
03849   // FTP will be null for closures that don't take arguments.
03850 
03851   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
03852                                       SourceLocation(), SourceLocation(),
03853                                       &Context->Idents.get("__block_impl"));
03854   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
03855 
03856   // Generate a funky cast.
03857   SmallVector<QualType, 8> ArgTypes;
03858 
03859   // Push the block argument type.
03860   ArgTypes.push_back(PtrBlock);
03861   if (FTP) {
03862     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
03863          E = FTP->arg_type_end(); I && (I != E); ++I) {
03864       QualType t = *I;
03865       // Make sure we convert "t (^)(...)" to "t (*)(...)".
03866       if (!convertBlockPointerToFunctionPointer(t))
03867         convertToUnqualifiedObjCType(t);
03868       ArgTypes.push_back(t);
03869     }
03870   }
03871   // Now do the pointer to function cast.
03872   QualType PtrToFuncCastType
03873     = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
03874 
03875   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
03876 
03877   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
03878                                                CK_BitCast,
03879                                                const_cast<Expr*>(BlockExp));
03880   // Don't forget the parens to enforce the proper binding.
03881   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
03882                                           BlkCast);
03883   //PE->dump();
03884 
03885   FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
03886                                     SourceLocation(),
03887                                     &Context->Idents.get("FuncPtr"),
03888                                     Context->VoidPtrTy, 0,
03889                                     /*BitWidth=*/0, /*Mutable=*/true,
03890                                     /*HasInit=*/false);
03891   MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
03892                                             FD->getType(), VK_LValue,
03893                                             OK_Ordinary);
03894 
03895   
03896   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
03897                                                 CK_BitCast, ME);
03898   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
03899 
03900   SmallVector<Expr*, 8> BlkExprs;
03901   // Add the implicit argument.
03902   BlkExprs.push_back(BlkCast);
03903   // Add the user arguments.
03904   for (CallExpr::arg_iterator I = Exp->arg_begin(),
03905        E = Exp->arg_end(); I != E; ++I) {
03906     BlkExprs.push_back(*I);
03907   }
03908   CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
03909                                         BlkExprs.size(),
03910                                         Exp->getType(), VK_RValue,
03911                                         SourceLocation());
03912   return CE;
03913 }
03914 
03915 // We need to return the rewritten expression to handle cases where the
03916 // BlockDeclRefExpr is embedded in another expression being rewritten.
03917 // For example:
03918 //
03919 // int main() {
03920 //    __block Foo *f;
03921 //    __block int i;
03922 //
03923 //    void (^myblock)() = ^() {
03924 //        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
03925 //        i = 77;
03926 //    };
03927 //}
03928 Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
03929   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
03930   // for each DeclRefExp where BYREFVAR is name of the variable.
03931   ValueDecl *VD = DeclRefExp->getDecl();
03932   bool isArrow = DeclRefExp->refersToEnclosingLocal();
03933   
03934   FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
03935                                     SourceLocation(),
03936                                     &Context->Idents.get("__forwarding"), 
03937                                     Context->VoidPtrTy, 0,
03938                                     /*BitWidth=*/0, /*Mutable=*/true,
03939                                     /*HasInit=*/false);
03940   MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
03941                                             FD, SourceLocation(),
03942                                             FD->getType(), VK_LValue,
03943                                             OK_Ordinary);
03944 
03945   StringRef Name = VD->getName();
03946   FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
03947                          &Context->Idents.get(Name), 
03948                          Context->VoidPtrTy, 0,
03949                          /*BitWidth=*/0, /*Mutable=*/true,
03950                          /*HasInit=*/false);
03951   ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
03952                                 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
03953   
03954   
03955   
03956   // Need parens to enforce precedence.
03957   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), 
03958                                           DeclRefExp->getExprLoc(), 
03959                                           ME);
03960   ReplaceStmt(DeclRefExp, PE);
03961   return PE;
03962 }
03963 
03964 // Rewrites the imported local variable V with external storage 
03965 // (static, extern, etc.) as *V
03966 //
03967 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
03968   ValueDecl *VD = DRE->getDecl();
03969   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
03970     if (!ImportedLocalExternalDecls.count(Var))
03971       return DRE;
03972   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
03973                                           VK_LValue, OK_Ordinary,
03974                                           DRE->getLocation());
03975   // Need parens to enforce precedence.
03976   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
03977                                           Exp);
03978   ReplaceStmt(DRE, PE);
03979   return PE;
03980 }
03981 
03982 void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
03983   SourceLocation LocStart = CE->getLParenLoc();
03984   SourceLocation LocEnd = CE->getRParenLoc();
03985 
03986   // Need to avoid trying to rewrite synthesized casts.
03987   if (LocStart.isInvalid())
03988     return;
03989   // Need to avoid trying to rewrite casts contained in macros.
03990   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
03991     return;
03992 
03993   const char *startBuf = SM->getCharacterData(LocStart);
03994   const char *endBuf = SM->getCharacterData(LocEnd);
03995   QualType QT = CE->getType();
03996   const Type* TypePtr = QT->getAs<Type>();
03997   if (isa<TypeOfExprType>(TypePtr)) {
03998     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
03999     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
04000     std::string TypeAsString = "(";
04001     RewriteBlockPointerType(TypeAsString, QT);
04002     TypeAsString += ")";
04003     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
04004     return;
04005   }
04006   // advance the location to startArgList.
04007   const char *argPtr = startBuf;
04008 
04009   while (*argPtr++ && (argPtr < endBuf)) {
04010     switch (*argPtr) {
04011     case '^':
04012       // Replace the '^' with '*'.
04013       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
04014       ReplaceText(LocStart, 1, "*");
04015       break;
04016     }
04017   }
04018   return;
04019 }
04020 
04021 void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
04022   SourceLocation DeclLoc = FD->getLocation();
04023   unsigned parenCount = 0;
04024 
04025   // We have 1 or more arguments that have closure pointers.
04026   const char *startBuf = SM->getCharacterData(DeclLoc);
04027   const char *startArgList = strchr(startBuf, '(');
04028 
04029   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
04030 
04031   parenCount++;
04032   // advance the location to startArgList.
04033   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
04034   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
04035 
04036   const char *argPtr = startArgList;
04037 
04038   while (*argPtr++ && parenCount) {
04039     switch (*argPtr) {
04040     case '^':
04041       // Replace the '^' with '*'.
04042       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
04043       ReplaceText(DeclLoc, 1, "*");
04044       break;
04045     case '(':
04046       parenCount++;
04047       break;
04048     case ')':
04049       parenCount--;
04050       break;
04051     }
04052   }
04053   return;
04054 }
04055 
04056 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
04057   const FunctionProtoType *FTP;
04058   const PointerType *PT = QT->getAs<PointerType>();
04059   if (PT) {
04060     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
04061   } else {
04062     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
04063     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
04064     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
04065   }
04066   if (FTP) {
04067     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
04068          E = FTP->arg_type_end(); I != E; ++I)
04069       if (isTopLevelBlockPointerType(*I))
04070         return true;
04071   }
04072   return false;
04073 }
04074 
04075 bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
04076   const FunctionProtoType *FTP;
04077   const PointerType *PT = QT->getAs<PointerType>();
04078   if (PT) {
04079     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
04080   } else {
04081     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
04082     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
04083     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
04084   }
04085   if (FTP) {
04086     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
04087          E = FTP->arg_type_end(); I != E; ++I) {
04088       if ((*I)->isObjCQualifiedIdType())
04089         return true;
04090       if ((*I)->isObjCObjectPointerType() &&
04091           (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
04092         return true;
04093     }
04094         
04095   }
04096   return false;
04097 }
04098 
04099 void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
04100                                      const char *&RParen) {
04101   const char *argPtr = strchr(Name, '(');
04102   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
04103 
04104   LParen = argPtr; // output the start.
04105   argPtr++; // skip past the left paren.
04106   unsigned parenCount = 1;
04107 
04108   while (*argPtr && parenCount) {
04109     switch (*argPtr) {
04110     case '(': parenCount++; break;
04111     case ')': parenCount--; break;
04112     default: break;
04113     }
04114     if (parenCount) argPtr++;
04115   }
04116   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
04117   RParen = argPtr; // output the end
04118 }
04119 
04120 void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
04121   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
04122     RewriteBlockPointerFunctionArgs(FD);
04123     return;
04124   }
04125   // Handle Variables and Typedefs.
04126   SourceLocation DeclLoc = ND->getLocation();
04127   QualType DeclT;
04128   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
04129     DeclT = VD->getType();
04130   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
04131     DeclT = TDD->getUnderlyingType();
04132   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
04133     DeclT = FD->getType();
04134   else
04135     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
04136 
04137   const char *startBuf = SM->getCharacterData(DeclLoc);
04138   const char *endBuf = startBuf;
04139   // scan backward (from the decl location) for the end of the previous decl.
04140   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
04141     startBuf--;
04142   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
04143   std::string buf;
04144   unsigned OrigLength=0;
04145   // *startBuf != '^' if we are dealing with a pointer to function that
04146   // may take block argument types (which will be handled below).
04147   if (*startBuf == '^') {
04148     // Replace the '^' with '*', computing a negative offset.
04149     buf = '*';
04150     startBuf++;
04151     OrigLength++;
04152   }
04153   while (*startBuf != ')') {
04154     buf += *startBuf;
04155     startBuf++;
04156     OrigLength++;
04157   }
04158   buf += ')';
04159   OrigLength++;
04160   
04161   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
04162       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
04163     // Replace the '^' with '*' for arguments.
04164     // Replace id<P> with id/*<>*/
04165     DeclLoc = ND->getLocation();
04166     startBuf = SM->getCharacterData(DeclLoc);
04167     const char *argListBegin, *argListEnd;
04168     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
04169     while (argListBegin < argListEnd) {
04170       if (*argListBegin == '^')
04171         buf += '*';
04172       else if (*argListBegin ==  '<') {
04173         buf += "/*"; 
04174         buf += *argListBegin++;
04175         OrigLength++;;
04176         while (*argListBegin != '>') {
04177           buf += *argListBegin++;
04178           OrigLength++;
04179         }
04180         buf += *argListBegin;
04181         buf += "*/";
04182       }
04183       else
04184         buf += *argListBegin;
04185       argListBegin++;
04186       OrigLength++;
04187     }
04188     buf += ')';
04189     OrigLength++;
04190   }
04191   ReplaceText(Start, OrigLength, buf);
04192   
04193   return;
04194 }
04195 
04196 
04197 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
04198 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
04199 ///                    struct Block_byref_id_object *src) {
04200 ///  _Block_object_assign (&_dest->object, _src->object, 
04201 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
04202 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
04203 ///  _Block_object_assign(&_dest->object, _src->object, 
04204 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
04205 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
04206 /// }
04207 /// And:
04208 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
04209 ///  _Block_object_dispose(_src->object, 
04210 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
04211 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
04212 ///  _Block_object_dispose(_src->object, 
04213 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
04214 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
04215 /// }
04216 
04217 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
04218                                                           int flag) {
04219   std::string S;
04220   if (CopyDestroyCache.count(flag))
04221     return S;
04222   CopyDestroyCache.insert(flag);
04223   S = "static void __Block_byref_id_object_copy_";
04224   S += utostr(flag);
04225   S += "(void *dst, void *src) {\n";
04226   
04227   // offset into the object pointer is computed as:
04228   // void * + void* + int + int + void* + void *
04229   unsigned IntSize = 
04230   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
04231   unsigned VoidPtrSize = 
04232   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
04233   
04234   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
04235   S += " _Block_object_assign((char*)dst + ";
04236   S += utostr(offset);
04237   S += ", *(void * *) ((char*)src + ";
04238   S += utostr(offset);
04239   S += "), ";
04240   S += utostr(flag);
04241   S += ");\n}\n";
04242   
04243   S += "static void __Block_byref_id_object_dispose_";
04244   S += utostr(flag);
04245   S += "(void *src) {\n";
04246   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
04247   S += utostr(offset);
04248   S += "), ";
04249   S += utostr(flag);
04250   S += ");\n}\n";
04251   return S;
04252 }
04253 
04254 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
04255 /// the declaration into:
04256 /// struct __Block_byref_ND {
04257 /// void *__isa;                  // NULL for everything except __weak pointers
04258 /// struct __Block_byref_ND *__forwarding;
04259 /// int32_t __flags;
04260 /// int32_t __size;
04261 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
04262 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
04263 /// typex ND;
04264 /// };
04265 ///
04266 /// It then replaces declaration of ND variable with:
04267 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, 
04268 ///                               __size=sizeof(struct __Block_byref_ND), 
04269 ///                               ND=initializer-if-any};
04270 ///
04271 ///
04272 void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
04273   // Insert declaration for the function in which block literal is
04274   // used.
04275   if (CurFunctionDeclToDeclareForBlock)
04276     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
04277   int flag = 0;
04278   int isa = 0;
04279   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
04280   if (DeclLoc.isInvalid())
04281     // If type location is missing, it is because of missing type (a warning).
04282     // Use variable's location which is good for this case.
04283     DeclLoc = ND->getLocation();
04284   const char *startBuf = SM->getCharacterData(DeclLoc);
04285   SourceLocation X = ND->getLocEnd();
04286   X = SM->getExpansionLoc(X);
04287   const char *endBuf = SM->getCharacterData(X);
04288   std::string Name(ND->getNameAsString());
04289   std::string ByrefType;
04290   RewriteByRefString(ByrefType, Name, ND, true);
04291   ByrefType += " {\n";
04292   ByrefType += "  void *__isa;\n";
04293   RewriteByRefString(ByrefType, Name, ND);
04294   ByrefType += " *__forwarding;\n";
04295   ByrefType += " int __flags;\n";
04296   ByrefType += " int __size;\n";
04297   // Add void *__Block_byref_id_object_copy; 
04298   // void *__Block_byref_id_object_dispose; if needed.
04299   QualType Ty = ND->getType();
04300   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
04301   if (HasCopyAndDispose) {
04302     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
04303     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
04304   }
04305 
04306   QualType T = Ty;
04307   (void)convertBlockPointerToFunctionPointer(T);
04308   T.getAsStringInternal(Name, Context->getPrintingPolicy());
04309     
04310   ByrefType += " " + Name + ";\n";
04311   ByrefType += "};\n";
04312   // Insert this type in global scope. It is needed by helper function.
04313   SourceLocation FunLocStart;
04314   if (CurFunctionDef)
04315      FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
04316   else {
04317     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
04318     FunLocStart = CurMethodDef->getLocStart();
04319   }
04320   InsertText(FunLocStart, ByrefType);
04321   if (Ty.isObjCGCWeak()) {
04322     flag |= BLOCK_FIELD_IS_WEAK;
04323     isa = 1;
04324   }
04325   
04326   if (HasCopyAndDispose) {
04327     flag = BLOCK_BYREF_CALLER;
04328     QualType Ty = ND->getType();
04329     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
04330     if (Ty->isBlockPointerType())
04331       flag |= BLOCK_FIELD_IS_BLOCK;
04332     else
04333       flag |= BLOCK_FIELD_IS_OBJECT;
04334     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
04335     if (!HF.empty())
04336       InsertText(FunLocStart, HF);
04337   }
04338   
04339   // struct __Block_byref_ND ND = 
04340   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), 
04341   //  initializer-if-any};
04342   bool hasInit = (ND->getInit() != 0);
04343   unsigned flags = 0;
04344   if (HasCopyAndDispose)
04345     flags |= BLOCK_HAS_COPY_DISPOSE;
04346   Name = ND->getNameAsString();
04347   ByrefType.clear();
04348   RewriteByRefString(ByrefType, Name, ND);
04349   std::string ForwardingCastType("(");
04350   ForwardingCastType += ByrefType + " *)";
04351   if (!hasInit) {
04352     ByrefType += " " + Name + " = {(void*)";
04353     ByrefType += utostr(isa);
04354     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
04355     ByrefType += utostr(flags);
04356     ByrefType += ", ";
04357     ByrefType += "sizeof(";
04358     RewriteByRefString(ByrefType, Name, ND);
04359     ByrefType += ")";
04360     if (HasCopyAndDispose) {
04361       ByrefType += ", __Block_byref_id_object_copy_";
04362       ByrefType += utostr(flag);
04363       ByrefType += ", __Block_byref_id_object_dispose_";
04364       ByrefType += utostr(flag);
04365     }
04366     ByrefType += "};\n";
04367     unsigned nameSize = Name.size();
04368     // for block or function pointer declaration. Name is aleady
04369     // part of the declaration.
04370     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
04371       nameSize = 1;
04372     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
04373   }
04374   else {
04375     SourceLocation startLoc;
04376     Expr *E = ND->getInit();
04377     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
04378       startLoc = ECE->getLParenLoc();
04379     else
04380       startLoc = E->getLocStart();
04381     startLoc = SM->getExpansionLoc(startLoc);
04382     endBuf = SM->getCharacterData(startLoc);
04383     ByrefType += " " + Name;
04384     ByrefType += " = {(void*)";
04385     ByrefType += utostr(isa);
04386     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
04387     ByrefType += utostr(flags);
04388     ByrefType += ", ";
04389     ByrefType += "sizeof(";
04390     RewriteByRefString(ByrefType, Name, ND);
04391     ByrefType += "), ";
04392     if (HasCopyAndDispose) {
04393       ByrefType += "__Block_byref_id_object_copy_";
04394       ByrefType += utostr(flag);
04395       ByrefType += ", __Block_byref_id_object_dispose_";
04396       ByrefType += utostr(flag);
04397       ByrefType += ", ";
04398     }
04399     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
04400     
04401     // Complete the newly synthesized compound expression by inserting a right
04402     // curly brace before the end of the declaration.
04403     // FIXME: This approach avoids rewriting the initializer expression. It
04404     // also assumes there is only one declarator. For example, the following
04405     // isn't currently supported by this routine (in general):
04406     // 
04407     // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
04408     //
04409     const char *startInitializerBuf = SM->getCharacterData(startLoc);
04410     const char *semiBuf = strchr(startInitializerBuf, ';');
04411     assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
04412     SourceLocation semiLoc =
04413       startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
04414 
04415     InsertText(semiLoc, "}");
04416   }
04417   return;
04418 }
04419 
04420 void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
04421   // Add initializers for any closure decl refs.
04422   GetBlockDeclRefExprs(Exp->getBody());
04423   if (BlockDeclRefs.size()) {
04424     // Unique all "by copy" declarations.
04425     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
04426       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
04427         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
04428           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
04429           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
04430         }
04431       }
04432     // Unique all "by ref" declarations.
04433     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
04434       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
04435         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
04436           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
04437           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
04438         }
04439       }
04440     // Find any imported blocks...they will need special attention.
04441     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
04442       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
04443           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
04444           BlockDeclRefs[i]->getType()->isBlockPointerType())
04445         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
04446   }
04447 }
04448 
04449 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
04450   IdentifierInfo *ID = &Context->Idents.get(name);
04451   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
04452   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
04453                               SourceLocation(), ID, FType, 0, SC_Extern,
04454                               SC_None, false, false);
04455 }
04456 
04457 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
04458           const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
04459   const BlockDecl *block = Exp->getBlockDecl();
04460   Blocks.push_back(Exp);
04461 
04462   CollectBlockDeclRefInfo(Exp);
04463   
04464   // Add inner imported variables now used in current block.
04465  int countOfInnerDecls = 0;
04466   if (!InnerBlockDeclRefs.empty()) {
04467     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
04468       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
04469       ValueDecl *VD = Exp->getDecl();
04470       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
04471       // We need to save the copied-in variables in nested
04472       // blocks because it is needed at the end for some of the API generations.
04473       // See SynthesizeBlockLiterals routine.
04474         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
04475         BlockDeclRefs.push_back(Exp);
04476         BlockByCopyDeclsPtrSet.insert(VD);
04477         BlockByCopyDecls.push_back(VD);
04478       }
04479       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
04480         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
04481         BlockDeclRefs.push_back(Exp);
04482         BlockByRefDeclsPtrSet.insert(VD);
04483         BlockByRefDecls.push_back(VD);
04484       }
04485     }
04486     // Find any imported blocks...they will need special attention.
04487     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
04488       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
04489           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
04490           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
04491         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
04492   }
04493   InnerDeclRefsCount.push_back(countOfInnerDecls);
04494   
04495   std::string FuncName;
04496 
04497   if (CurFunctionDef)
04498     FuncName = CurFunctionDef->getNameAsString();
04499   else if (CurMethodDef)
04500     BuildUniqueMethodName(FuncName, CurMethodDef);
04501   else if (GlobalVarDecl)
04502     FuncName = std::string(GlobalVarDecl->getNameAsString());
04503 
04504   std::string BlockNumber = utostr(Blocks.size()-1);
04505 
04506   std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
04507   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
04508 
04509   // Get a pointer to the function type so we can cast appropriately.
04510   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
04511   QualType FType = Context->getPointerType(BFT);
04512 
04513   FunctionDecl *FD;
04514   Expr *NewRep;
04515 
04516   // Simulate a contructor call...
04517   FD = SynthBlockInitFunctionDecl(Tag);
04518   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
04519                                                SourceLocation());
04520 
04521   SmallVector<Expr*, 4> InitExprs;
04522 
04523   // Initialize the block function.
04524   FD = SynthBlockInitFunctionDecl(Func);
04525   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
04526                                                VK_LValue, SourceLocation());
04527   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
04528                                                 CK_BitCast, Arg);
04529   InitExprs.push_back(castExpr);
04530 
04531   // Initialize the block descriptor.
04532   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
04533 
04534   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
04535                                    SourceLocation(), SourceLocation(),
04536                                    &Context->Idents.get(DescData.c_str()),
04537                                    Context->VoidPtrTy, 0,
04538                                    SC_Static, SC_None);
04539   UnaryOperator *DescRefExpr =
04540     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
04541                                                           Context->VoidPtrTy,
04542                                                           VK_LValue,
04543                                                           SourceLocation()), 
04544                                 UO_AddrOf,
04545                                 Context->getPointerType(Context->VoidPtrTy), 
04546                                 VK_RValue, OK_Ordinary,
04547                                 SourceLocation());
04548   InitExprs.push_back(DescRefExpr); 
04549   
04550   // Add initializers for any closure decl refs.
04551   if (BlockDeclRefs.size()) {
04552     Expr *Exp;
04553     // Output all "by copy" declarations.
04554     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
04555          E = BlockByCopyDecls.end(); I != E; ++I) {
04556       if (isObjCType((*I)->getType())) {
04557         // FIXME: Conform to ABI ([[obj retain] autorelease]).
04558         FD = SynthBlockInitFunctionDecl((*I)->getName());
04559         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
04560                                         SourceLocation());
04561         if (HasLocalVariableExternalStorage(*I)) {
04562           QualType QT = (*I)->getType();
04563           QT = Context->getPointerType(QT);
04564           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
04565                                             OK_Ordinary, SourceLocation());
04566         }
04567       } else if (isTopLevelBlockPointerType((*I)->getType())) {
04568         FD = SynthBlockInitFunctionDecl((*I)->getName());
04569         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
04570                                         SourceLocation());
04571         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
04572                                        CK_BitCast, Arg);
04573       } else {
04574         FD = SynthBlockInitFunctionDecl((*I)->getName());
04575         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
04576                                         SourceLocation());
04577         if (HasLocalVariableExternalStorage(*I)) {
04578           QualType QT = (*I)->getType();
04579           QT = Context->getPointerType(QT);
04580           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
04581                                             OK_Ordinary, SourceLocation());
04582         }
04583         
04584       }
04585       InitExprs.push_back(Exp);
04586     }
04587     // Output all "by ref" declarations.
04588     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
04589          E = BlockByRefDecls.end(); I != E; ++I) {
04590       ValueDecl *ND = (*I);
04591       std::string Name(ND->getNameAsString());
04592       std::string RecName;
04593       RewriteByRefString(RecName, Name, ND, true);
04594       IdentifierInfo *II = &Context->Idents.get(RecName.c_str() 
04595                                                 + sizeof("struct"));
04596       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
04597                                           SourceLocation(), SourceLocation(),
04598                                           II);
04599       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
04600       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
04601       
04602       FD = SynthBlockInitFunctionDecl((*I)->getName());
04603       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
04604                                       SourceLocation());
04605       bool isNestedCapturedVar = false;
04606       if (block)
04607         for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
04608              ce = block->capture_end(); ci != ce; ++ci) {
04609           const VarDecl *variable = ci->getVariable();
04610           if (variable == ND && ci->isNested()) {
04611             assert (ci->isByRef() && 
04612                     "SynthBlockInitExpr - captured block variable is not byref");
04613             isNestedCapturedVar = true;
04614             break;
04615           }
04616         }
04617       // captured nested byref variable has its address passed. Do not take
04618       // its address again.
04619       if (!isNestedCapturedVar)
04620           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
04621                                      Context->getPointerType(Exp->getType()),
04622                                      VK_RValue, OK_Ordinary, SourceLocation());
04623       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
04624       InitExprs.push_back(Exp);
04625     }
04626   }
04627   if (ImportedBlockDecls.size()) {
04628     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
04629     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
04630     unsigned IntSize = 
04631       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
04632     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), 
04633                                            Context->IntTy, SourceLocation());
04634     InitExprs.push_back(FlagExp);
04635   }
04636   NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
04637                                   FType, VK_LValue, SourceLocation());
04638   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
04639                              Context->getPointerType(NewRep->getType()),
04640                              VK_RValue, OK_Ordinary, SourceLocation());
04641   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
04642                                     NewRep);
04643   BlockDeclRefs.clear();
04644   BlockByRefDecls.clear();
04645   BlockByRefDeclsPtrSet.clear();
04646   BlockByCopyDecls.clear();
04647   BlockByCopyDeclsPtrSet.clear();
04648   ImportedBlockDecls.clear();
04649   return NewRep;
04650 }
04651 
04652 bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
04653   if (const ObjCForCollectionStmt * CS = 
04654       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
04655         return CS->getElement() == DS;
04656   return false;
04657 }
04658 
04659 //===----------------------------------------------------------------------===//
04660 // Function Body / Expression rewriting
04661 //===----------------------------------------------------------------------===//
04662 
04663 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
04664   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
04665       isa<DoStmt>(S) || isa<ForStmt>(S))
04666     Stmts.push_back(S);
04667   else if (isa<ObjCForCollectionStmt>(S)) {
04668     Stmts.push_back(S);
04669     ObjCBcLabelNo.push_back(++BcLabelCount);
04670   }
04671 
04672   // Pseudo-object operations and ivar references need special
04673   // treatment because we're going to recursively rewrite them.
04674   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
04675     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
04676       return RewritePropertyOrImplicitSetter(PseudoOp);
04677     } else {
04678       return RewritePropertyOrImplicitGetter(PseudoOp);
04679     }
04680   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
04681     return RewriteObjCIvarRefExpr(IvarRefExpr);
04682   }
04683 
04684   SourceRange OrigStmtRange = S->getSourceRange();
04685 
04686   // Perform a bottom up rewrite of all children.
04687   for (Stmt::child_range CI = S->children(); CI; ++CI)
04688     if (*CI) {
04689       Stmt *childStmt = (*CI);
04690       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
04691       if (newStmt) {
04692         *CI = newStmt;
04693       }
04694     }
04695 
04696   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
04697     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
04698     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
04699     InnerContexts.insert(BE->getBlockDecl());
04700     ImportedLocalExternalDecls.clear();
04701     GetInnerBlockDeclRefExprs(BE->getBody(),
04702                               InnerBlockDeclRefs, InnerContexts);
04703     // Rewrite the block body in place.
04704     Stmt *SaveCurrentBody = CurrentBody;
04705     CurrentBody = BE->getBody();
04706     PropParentMap = 0;
04707     // block literal on rhs of a property-dot-sytax assignment
04708     // must be replaced by its synthesize ast so getRewrittenText
04709     // works as expected. In this case, what actually ends up on RHS
04710     // is the blockTranscribed which is the helper function for the
04711     // block literal; as in: self.c = ^() {[ace ARR];};
04712     bool saveDisableReplaceStmt = DisableReplaceStmt;
04713     DisableReplaceStmt = false;
04714     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
04715     DisableReplaceStmt = saveDisableReplaceStmt;
04716     CurrentBody = SaveCurrentBody;
04717     PropParentMap = 0;
04718     ImportedLocalExternalDecls.clear();
04719     // Now we snarf the rewritten text and stash it away for later use.
04720     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
04721     RewrittenBlockExprs[BE] = Str;
04722 
04723     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
04724                             
04725     //blockTranscribed->dump();
04726     ReplaceStmt(S, blockTranscribed);
04727     return blockTranscribed;
04728   }
04729   // Handle specific things.
04730   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
04731     return RewriteAtEncode(AtEncode);
04732 
04733   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
04734     return RewriteAtSelector(AtSelector);
04735 
04736   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
04737     return RewriteObjCStringLiteral(AtString);
04738 
04739   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
04740 #if 0
04741     // Before we rewrite it, put the original message expression in a comment.
04742     SourceLocation startLoc = MessExpr->getLocStart();
04743     SourceLocation endLoc = MessExpr->getLocEnd();
04744 
04745     const char *startBuf = SM->getCharacterData(startLoc);
04746     const char *endBuf = SM->getCharacterData(endLoc);
04747 
04748     std::string messString;
04749     messString += "// ";
04750     messString.append(startBuf, endBuf-startBuf+1);
04751     messString += "\n";
04752 
04753     // FIXME: Missing definition of
04754     // InsertText(clang::SourceLocation, char const*, unsigned int).
04755     // InsertText(startLoc, messString.c_str(), messString.size());
04756     // Tried this, but it didn't work either...
04757     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
04758 #endif
04759     return RewriteMessageExpr(MessExpr);
04760   }
04761 
04762   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
04763     return RewriteObjCTryStmt(StmtTry);
04764 
04765   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
04766     return RewriteObjCSynchronizedStmt(StmtTry);
04767 
04768   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
04769     return RewriteObjCThrowStmt(StmtThrow);
04770 
04771   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
04772     return RewriteObjCProtocolExpr(ProtocolExp);
04773 
04774   if (ObjCForCollectionStmt *StmtForCollection =
04775         dyn_cast<ObjCForCollectionStmt>(S))
04776     return RewriteObjCForCollectionStmt(StmtForCollection,
04777                                         OrigStmtRange.getEnd());
04778   if (BreakStmt *StmtBreakStmt =
04779       dyn_cast<BreakStmt>(S))
04780     return RewriteBreakStmt(StmtBreakStmt);
04781   if (ContinueStmt *StmtContinueStmt =
04782       dyn_cast<ContinueStmt>(S))
04783     return RewriteContinueStmt(StmtContinueStmt);
04784 
04785   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
04786   // and cast exprs.
04787   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
04788     // FIXME: What we're doing here is modifying the type-specifier that
04789     // precedes the first Decl.  In the future the DeclGroup should have
04790     // a separate type-specifier that we can rewrite.
04791     // NOTE: We need to avoid rewriting the DeclStmt if it is within
04792     // the context of an ObjCForCollectionStmt. For example:
04793     //   NSArray *someArray;
04794     //   for (id <FooProtocol> index in someArray) ;
04795     // This is because RewriteObjCForCollectionStmt() does textual rewriting 
04796     // and it depends on the original text locations/positions.
04797     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
04798       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
04799 
04800     // Blocks rewrite rules.
04801     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
04802          DI != DE; ++DI) {
04803       Decl *SD = *DI;
04804       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
04805         if (isTopLevelBlockPointerType(ND->getType()))
04806           RewriteBlockPointerDecl(ND);
04807         else if (ND->getType()->isFunctionPointerType())
04808           CheckFunctionPointerDecl(ND->getType(), ND);
04809         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
04810           if (VD->hasAttr<BlocksAttr>()) {
04811             static unsigned uniqueByrefDeclCount = 0;
04812             assert(!BlockByRefDeclNo.count(ND) &&
04813               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
04814             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
04815             RewriteByRefVar(VD);
04816           }
04817           else           
04818             RewriteTypeOfDecl(VD);
04819         }
04820       }
04821       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
04822         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
04823           RewriteBlockPointerDecl(TD);
04824         else if (TD->getUnderlyingType()->isFunctionPointerType())
04825           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
04826       }
04827     }
04828   }
04829 
04830   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
04831     RewriteObjCQualifiedInterfaceTypes(CE);
04832 
04833   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
04834       isa<DoStmt>(S) || isa<ForStmt>(S)) {
04835     assert(!Stmts.empty() && "Statement stack is empty");
04836     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
04837              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
04838             && "Statement stack mismatch");
04839     Stmts.pop_back();
04840   }
04841   // Handle blocks rewriting.
04842   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
04843     ValueDecl *VD = DRE->getDecl(); 
04844     if (VD->hasAttr<BlocksAttr>())
04845       return RewriteBlockDeclRefExpr(DRE);
04846     if (HasLocalVariableExternalStorage(VD))
04847       return RewriteLocalVariableExternalStorage(DRE);
04848   }
04849   
04850   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
04851     if (CE->getCallee()->getType()->isBlockPointerType()) {
04852       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
04853       ReplaceStmt(S, BlockCall);
04854       return BlockCall;
04855     }
04856   }
04857   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
04858     RewriteCastExpr(CE);
04859   }
04860 #if 0
04861   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
04862     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
04863                                                    ICE->getSubExpr(),
04864                                                    SourceLocation());
04865     // Get the new text.
04866     std::string SStr;
04867     llvm::raw_string_ostream Buf(SStr);
04868     Replacement->printPretty(Buf, *Context);
04869     const std::string &Str = Buf.str();
04870 
04871     printf("CAST = %s\n", &Str[0]);
04872     InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
04873     delete S;
04874     return Replacement;
04875   }
04876 #endif
04877   // Return this stmt unmodified.
04878   return S;
04879 }
04880 
04881 void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
04882   for (RecordDecl::field_iterator i = RD->field_begin(), 
04883                                   e = RD->field_end(); i != e; ++i) {
04884     FieldDecl *FD = &*i;
04885     if (isTopLevelBlockPointerType(FD->getType()))
04886       RewriteBlockPointerDecl(FD);
04887     if (FD->getType()->isObjCQualifiedIdType() ||
04888         FD->getType()->isObjCQualifiedInterfaceType())
04889       RewriteObjCQualifiedInterfaceTypes(FD);
04890   }
04891 }
04892 
04893 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
04894 /// main file of the input.
04895 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
04896   switch (D->getKind()) {
04897     case Decl::Function: {
04898       FunctionDecl *FD = cast<FunctionDecl>(D);
04899       if (FD->isOverloadedOperator())
04900         return;
04901 
04902       // Since function prototypes don't have ParmDecl's, we check the function
04903       // prototype. This enables us to rewrite function declarations and
04904       // definitions using the same code.
04905       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
04906 
04907       if (!FD->isThisDeclarationADefinition())
04908         break;
04909 
04910       // FIXME: If this should support Obj-C++, support CXXTryStmt
04911       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
04912         CurFunctionDef = FD;
04913         CurFunctionDeclToDeclareForBlock = FD;
04914         CurrentBody = Body;
04915         Body =
04916         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
04917         FD->setBody(Body);
04918         CurrentBody = 0;
04919         if (PropParentMap) {
04920           delete PropParentMap;
04921           PropParentMap = 0;
04922         }
04923         // This synthesizes and inserts the block "impl" struct, invoke function,
04924         // and any copy/dispose helper functions.
04925         InsertBlockLiteralsWithinFunction(FD);
04926         CurFunctionDef = 0;
04927         CurFunctionDeclToDeclareForBlock = 0;
04928       }
04929       break;
04930     }
04931     case Decl::ObjCMethod: {
04932       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
04933       if (CompoundStmt *Body = MD->getCompoundBody()) {
04934         CurMethodDef = MD;
04935         CurrentBody = Body;
04936         Body =
04937           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
04938         MD->setBody(Body);
04939         CurrentBody = 0;
04940         if (PropParentMap) {
04941           delete PropParentMap;
04942           PropParentMap = 0;
04943         }
04944         InsertBlockLiteralsWithinMethod(MD);
04945         CurMethodDef = 0;
04946       }
04947       break;
04948     }
04949     case Decl::ObjCImplementation: {
04950       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
04951       ClassImplementation.push_back(CI);
04952       break;
04953     }
04954     case Decl::ObjCCategoryImpl: {
04955       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
04956       CategoryImplementation.push_back(CI);
04957       break;
04958     }
04959     case Decl::Var: {
04960       VarDecl *VD = cast<VarDecl>(D);
04961       RewriteObjCQualifiedInterfaceTypes(VD);
04962       if (isTopLevelBlockPointerType(VD->getType()))
04963         RewriteBlockPointerDecl(VD);
04964       else if (VD->getType()->isFunctionPointerType()) {
04965         CheckFunctionPointerDecl(VD->getType(), VD);
04966         if (VD->getInit()) {
04967           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
04968             RewriteCastExpr(CE);
04969           }
04970         }
04971       } else if (VD->getType()->isRecordType()) {
04972         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
04973         if (RD->isCompleteDefinition())
04974           RewriteRecordBody(RD);
04975       }
04976       if (VD->getInit()) {
04977         GlobalVarDecl = VD;
04978         CurrentBody = VD->getInit();
04979         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
04980         CurrentBody = 0;
04981         if (PropParentMap) {
04982           delete PropParentMap;
04983           PropParentMap = 0;
04984         }
04985         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
04986         GlobalVarDecl = 0;
04987           
04988         // This is needed for blocks.
04989         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
04990             RewriteCastExpr(CE);
04991         }
04992       }
04993       break;
04994     }
04995     case Decl::TypeAlias:
04996     case Decl::Typedef: {
04997       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
04998         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
04999           RewriteBlockPointerDecl(TD);
05000         else if (TD->getUnderlyingType()->isFunctionPointerType())
05001           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
05002       }
05003       break;
05004     }
05005     case Decl::CXXRecord:
05006     case Decl::Record: {
05007       RecordDecl *RD = cast<RecordDecl>(D);
05008       if (RD->isCompleteDefinition()) 
05009         RewriteRecordBody(RD);
05010       break;
05011     }
05012     default:
05013       break;
05014   }
05015   // Nothing yet.
05016 }
05017 
05018 void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
05019   if (Diags.hasErrorOccurred())
05020     return;
05021 
05022   RewriteInclude();
05023 
05024   // Here's a great place to add any extra declarations that may be needed.
05025   // Write out meta data for each @protocol(<expr>).
05026   for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
05027        E = ProtocolExprDecls.end(); I != E; ++I)
05028     RewriteObjCProtocolMetaData(*I, "", "", Preamble);
05029 
05030   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
05031   if (ClassImplementation.size() || CategoryImplementation.size())
05032     RewriteImplementations();
05033 
05034   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
05035   // we are done.
05036   if (const RewriteBuffer *RewriteBuf =
05037       Rewrite.getRewriteBufferFor(MainFileID)) {
05038     //printf("Changed:\n");
05039     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
05040   } else {
05041     llvm::errs() << "No changes\n";
05042   }
05043 
05044   if (ClassImplementation.size() || CategoryImplementation.size() ||
05045       ProtocolExprDecls.size()) {
05046     // Rewrite Objective-c meta data*
05047     std::string ResultStr;
05048     RewriteMetaDataIntoBuffer(ResultStr);
05049     // Emit metadata.
05050     *OutFile << ResultStr;
05051   }
05052   OutFile->flush();
05053 }
05054 
05055 void RewriteObjCFragileABI::Initialize(ASTContext &context) {
05056   InitializeCommon(context);
05057   
05058   // declaring objc_selector outside the parameter list removes a silly
05059   // scope related warning...
05060   if (IsHeader)
05061     Preamble = "#pragma once\n";
05062   Preamble += "struct objc_selector; struct objc_class;\n";
05063   Preamble += "struct __rw_objc_super { struct objc_object *object; ";
05064   Preamble += "struct objc_object *superClass; ";
05065   if (LangOpts.MicrosoftExt) {
05066     // Add a constructor for creating temporary objects.
05067     Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
05068     ": ";
05069     Preamble += "object(o), superClass(s) {} ";
05070   }
05071   Preamble += "};\n";
05072   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
05073   Preamble += "typedef struct objc_object Protocol;\n";
05074   Preamble += "#define _REWRITER_typedef_Protocol\n";
05075   Preamble += "#endif\n";
05076   if (LangOpts.MicrosoftExt) {
05077     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
05078     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
05079   } else
05080     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
05081   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
05082   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
05083   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
05084   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
05085   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
05086   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
05087   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
05088   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
05089   Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
05090   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
05091   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
05092   Preamble += "(const char *);\n";
05093   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
05094   Preamble += "(struct objc_class *);\n";
05095   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
05096   Preamble += "(const char *);\n";
05097   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
05098   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
05099   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
05100   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
05101   Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
05102   Preamble += "(struct objc_class *, struct objc_object *);\n";
05103   // @synchronized hooks.
05104   Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
05105   Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
05106   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
05107   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
05108   Preamble += "struct __objcFastEnumerationState {\n\t";
05109   Preamble += "unsigned long state;\n\t";
05110   Preamble += "void **itemsPtr;\n\t";
05111   Preamble += "unsigned long *mutationsPtr;\n\t";
05112   Preamble += "unsigned long extra[5];\n};\n";
05113   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
05114   Preamble += "#define __FASTENUMERATIONSTATE\n";
05115   Preamble += "#endif\n";
05116   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
05117   Preamble += "struct __NSConstantStringImpl {\n";
05118   Preamble += "  int *isa;\n";
05119   Preamble += "  int flags;\n";
05120   Preamble += "  char *str;\n";
05121   Preamble += "  long length;\n";
05122   Preamble += "};\n";
05123   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
05124   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
05125   Preamble += "#else\n";
05126   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
05127   Preamble += "#endif\n";
05128   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
05129   Preamble += "#endif\n";
05130   // Blocks preamble.
05131   Preamble += "#ifndef BLOCK_IMPL\n";
05132   Preamble += "#define BLOCK_IMPL\n";
05133   Preamble += "struct __block_impl {\n";
05134   Preamble += "  void *isa;\n";
05135   Preamble += "  int Flags;\n";
05136   Preamble += "  int Reserved;\n";
05137   Preamble += "  void *FuncPtr;\n";
05138   Preamble += "};\n";
05139   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
05140   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
05141   Preamble += "extern \"C\" __declspec(dllexport) "
05142   "void _Block_object_assign(void *, const void *, const int);\n";
05143   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
05144   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
05145   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
05146   Preamble += "#else\n";
05147   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
05148   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
05149   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
05150   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
05151   Preamble += "#endif\n";
05152   Preamble += "#endif\n";
05153   if (LangOpts.MicrosoftExt) {
05154     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
05155     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
05156     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
05157     Preamble += "#define __attribute__(X)\n";
05158     Preamble += "#endif\n";
05159     Preamble += "#define __weak\n";
05160   }
05161   else {
05162     Preamble += "#define __block\n";
05163     Preamble += "#define __weak\n";
05164   }
05165   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
05166   // as this avoids warning in any 64bit/32bit compilation model.
05167   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
05168 }
05169 
05170 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
05171 /// ivar offset.
05172 void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
05173                                                          std::string &Result) {
05174   if (ivar->isBitField()) {
05175     // FIXME: The hack below doesn't work for bitfields. For now, we simply
05176     // place all bitfields at offset 0.
05177     Result += "0";
05178   } else {
05179     Result += "__OFFSETOFIVAR__(struct ";
05180     Result += ivar->getContainingInterface()->getNameAsString();
05181     if (LangOpts.MicrosoftExt)
05182       Result += "_IMPL";
05183     Result += ", ";
05184     Result += ivar->getNameAsString();
05185     Result += ")";
05186   }
05187 }
05188 
05189 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
05190 void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
05191                             ObjCProtocolDecl *PDecl, StringRef prefix,
05192                             StringRef ClassName, std::string &Result) {
05193   static bool objc_protocol_methods = false;
05194   
05195   // Output struct protocol_methods holder of method selector and type.
05196   if (!objc_protocol_methods && PDecl->hasDefinition()) {
05197     /* struct protocol_methods {
05198      SEL _cmd;
05199      char *method_types;
05200      }
05201      */
05202     Result += "\nstruct _protocol_methods {\n";
05203     Result += "\tstruct objc_selector *_cmd;\n";
05204     Result += "\tchar *method_types;\n";
05205     Result += "};\n";
05206     
05207     objc_protocol_methods = true;
05208   }
05209   // Do not synthesize the protocol more than once.
05210   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
05211     return;
05212   
05213   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
05214     PDecl = Def;
05215   
05216   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
05217     unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
05218                                         PDecl->instmeth_end());
05219     /* struct _objc_protocol_method_list {
05220      int protocol_method_count;
05221      struct protocol_methods protocols[];
05222      }
05223      */
05224     Result += "\nstatic struct {\n";
05225     Result += "\tint protocol_method_count;\n";
05226     Result += "\tstruct _protocol_methods protocol_methods[";
05227     Result += utostr(NumMethods);
05228     Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
05229     Result += PDecl->getNameAsString();
05230     Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
05231     "{\n\t" + utostr(NumMethods) + "\n";
05232     
05233     // Output instance methods declared in this protocol.
05234     for (ObjCProtocolDecl::instmeth_iterator
05235          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
05236          I != E; ++I) {
05237       if (I == PDecl->instmeth_begin())
05238         Result += "\t  ,{{(struct objc_selector *)\"";
05239       else
05240         Result += "\t  ,{(struct objc_selector *)\"";
05241       Result += (*I)->getSelector().getAsString();
05242       std::string MethodTypeString;
05243       Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
05244       Result += "\", \"";
05245       Result += MethodTypeString;
05246       Result += "\"}\n";
05247     }
05248     Result += "\t }\n};\n";
05249   }
05250   
05251   // Output class methods declared in this protocol.
05252   unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
05253                                       PDecl->classmeth_end());
05254   if (NumMethods > 0) {
05255     /* struct _objc_protocol_method_list {
05256      int protocol_method_count;
05257      struct protocol_methods protocols[];
05258      }
05259      */
05260     Result += "\nstatic struct {\n";
05261     Result += "\tint protocol_method_count;\n";
05262     Result += "\tstruct _protocol_methods protocol_methods[";
05263     Result += utostr(NumMethods);
05264     Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
05265     Result += PDecl->getNameAsString();
05266     Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
05267     "{\n\t";
05268     Result += utostr(NumMethods);
05269     Result += "\n";
05270     
05271     // Output instance methods declared in this protocol.
05272     for (ObjCProtocolDecl::classmeth_iterator
05273          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
05274          I != E; ++I) {
05275       if (I == PDecl->classmeth_begin())
05276         Result += "\t  ,{{(struct objc_selector *)\"";
05277       else
05278         Result += "\t  ,{(struct objc_selector *)\"";
05279       Result += (*I)->getSelector().getAsString();
05280       std::string MethodTypeString;
05281       Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
05282       Result += "\", \"";
05283       Result += MethodTypeString;
05284       Result += "\"}\n";
05285     }
05286     Result += "\t }\n};\n";
05287   }
05288   
05289   // Output:
05290   /* struct _objc_protocol {
05291    // Objective-C 1.0 extensions
05292    struct _objc_protocol_extension *isa;
05293    char *protocol_name;
05294    struct _objc_protocol **protocol_list;
05295    struct _objc_protocol_method_list *instance_methods;
05296    struct _objc_protocol_method_list *class_methods;
05297    };
05298    */
05299   static bool objc_protocol = false;
05300   if (!objc_protocol) {
05301     Result += "\nstruct _objc_protocol {\n";
05302     Result += "\tstruct _objc_protocol_extension *isa;\n";
05303     Result += "\tchar *protocol_name;\n";
05304     Result += "\tstruct _objc_protocol **protocol_list;\n";
05305     Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
05306     Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
05307     Result += "};\n";
05308     
05309     objc_protocol = true;
05310   }
05311   
05312   Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
05313   Result += PDecl->getNameAsString();
05314   Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
05315   "{\n\t0, \"";
05316   Result += PDecl->getNameAsString();
05317   Result += "\", 0, ";
05318   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
05319     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
05320     Result += PDecl->getNameAsString();
05321     Result += ", ";
05322   }
05323   else
05324     Result += "0, ";
05325   if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
05326     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
05327     Result += PDecl->getNameAsString();
05328     Result += "\n";
05329   }
05330   else
05331     Result += "0\n";
05332   Result += "};\n";
05333   
05334   // Mark this protocol as having been generated.
05335   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
05336     llvm_unreachable("protocol already synthesized");
05337   
05338 }
05339 
05340 void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
05341                                 const ObjCList<ObjCProtocolDecl> &Protocols,
05342                                 StringRef prefix, StringRef ClassName,
05343                                 std::string &Result) {
05344   if (Protocols.empty()) return;
05345   
05346   for (unsigned i = 0; i != Protocols.size(); i++)
05347     RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
05348   
05349   // Output the top lovel protocol meta-data for the class.
05350   /* struct _objc_protocol_list {
05351    struct _objc_protocol_list *next;
05352    int    protocol_count;
05353    struct _objc_protocol *class_protocols[];
05354    }
05355    */
05356   Result += "\nstatic struct {\n";
05357   Result += "\tstruct _objc_protocol_list *next;\n";
05358   Result += "\tint    protocol_count;\n";
05359   Result += "\tstruct _objc_protocol *class_protocols[";
05360   Result += utostr(Protocols.size());
05361   Result += "];\n} _OBJC_";
05362   Result += prefix;
05363   Result += "_PROTOCOLS_";
05364   Result += ClassName;
05365   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
05366   "{\n\t0, ";
05367   Result += utostr(Protocols.size());
05368   Result += "\n";
05369   
05370   Result += "\t,{&_OBJC_PROTOCOL_";
05371   Result += Protocols[0]->getNameAsString();
05372   Result += " \n";
05373   
05374   for (unsigned i = 1; i != Protocols.size(); i++) {
05375     Result += "\t ,&_OBJC_PROTOCOL_";
05376     Result += Protocols[i]->getNameAsString();
05377     Result += "\n";
05378   }
05379   Result += "\t }\n};\n";
05380 }
05381 
05382 void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
05383                                            std::string &Result) {
05384   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
05385   
05386   // Explicitly declared @interface's are already synthesized.
05387   if (CDecl->isImplicitInterfaceDecl()) {
05388     // FIXME: Implementation of a class with no @interface (legacy) does not
05389     // produce correct synthesis as yet.
05390     RewriteObjCInternalStruct(CDecl, Result);
05391   }
05392   
05393   // Build _objc_ivar_list metadata for classes ivars if needed
05394   unsigned NumIvars = !IDecl->ivar_empty()
05395   ? IDecl->ivar_size()
05396   : (CDecl ? CDecl->ivar_size() : 0);
05397   if (NumIvars > 0) {
05398     static bool objc_ivar = false;
05399     if (!objc_ivar) {
05400       /* struct _objc_ivar {
05401        char *ivar_name;
05402        char *ivar_type;
05403        int ivar_offset;
05404        };
05405        */
05406       Result += "\nstruct _objc_ivar {\n";
05407       Result += "\tchar *ivar_name;\n";
05408       Result += "\tchar *ivar_type;\n";
05409       Result += "\tint ivar_offset;\n";
05410       Result += "};\n";
05411       
05412       objc_ivar = true;
05413     }
05414     
05415     /* struct {
05416      int ivar_count;
05417      struct _objc_ivar ivar_list[nIvars];
05418      };
05419      */
05420     Result += "\nstatic struct {\n";
05421     Result += "\tint ivar_count;\n";
05422     Result += "\tstruct _objc_ivar ivar_list[";
05423     Result += utostr(NumIvars);
05424     Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
05425     Result += IDecl->getNameAsString();
05426     Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
05427     "{\n\t";
05428     Result += utostr(NumIvars);
05429     Result += "\n";
05430     
05431     ObjCInterfaceDecl::ivar_iterator IVI, IVE;
05432     SmallVector<ObjCIvarDecl *, 8> IVars;
05433     if (!IDecl->ivar_empty()) {
05434       for (ObjCInterfaceDecl::ivar_iterator
05435            IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
05436            IV != IVEnd; ++IV)
05437         IVars.push_back(&*IV);
05438       IVI = IDecl->ivar_begin();
05439       IVE = IDecl->ivar_end();
05440     } else {
05441       IVI = CDecl->ivar_begin();
05442       IVE = CDecl->ivar_end();
05443     }
05444     Result += "\t,{{\"";
05445     Result += IVI->getNameAsString();
05446     Result += "\", \"";
05447     std::string TmpString, StrEncoding;
05448     Context->getObjCEncodingForType(IVI->getType(), TmpString, &*IVI);
05449     QuoteDoublequotes(TmpString, StrEncoding);
05450     Result += StrEncoding;
05451     Result += "\", ";
05452     RewriteIvarOffsetComputation(&*IVI, Result);
05453     Result += "}\n";
05454     for (++IVI; IVI != IVE; ++IVI) {
05455       Result += "\t  ,{\"";
05456       Result += IVI->getNameAsString();
05457       Result += "\", \"";
05458       std::string TmpString, StrEncoding;
05459       Context->getObjCEncodingForType(IVI->getType(), TmpString, &*IVI);
05460       QuoteDoublequotes(TmpString, StrEncoding);
05461       Result += StrEncoding;
05462       Result += "\", ";
05463       RewriteIvarOffsetComputation(&*IVI, Result);
05464       Result += "}\n";
05465     }
05466     
05467     Result += "\t }\n};\n";
05468   }
05469   
05470   // Build _objc_method_list for class's instance methods if needed
05471   SmallVector<ObjCMethodDecl *, 32>
05472   InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
05473   
05474   // If any of our property implementations have associated getters or
05475   // setters, produce metadata for them as well.
05476   for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
05477        PropEnd = IDecl->propimpl_end();
05478        Prop != PropEnd; ++Prop) {
05479     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
05480       continue;
05481     if (!Prop->getPropertyIvarDecl())
05482       continue;
05483     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
05484     if (!PD)
05485       continue;
05486     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
05487       if (!Getter->isDefined())
05488         InstanceMethods.push_back(Getter);
05489     if (PD->isReadOnly())
05490       continue;
05491     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
05492       if (!Setter->isDefined())
05493         InstanceMethods.push_back(Setter);
05494   }
05495   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
05496                              true, "", IDecl->getName(), Result);
05497   
05498   // Build _objc_method_list for class's class methods if needed
05499   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
05500                              false, "", IDecl->getName(), Result);
05501   
05502   // Protocols referenced in class declaration?
05503   RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
05504                                   "CLASS", CDecl->getName(), Result);
05505   
05506   // Declaration of class/meta-class metadata
05507   /* struct _objc_class {
05508    struct _objc_class *isa; // or const char *root_class_name when metadata
05509    const char *super_class_name;
05510    char *name;
05511    long version;
05512    long info;
05513    long instance_size;
05514    struct _objc_ivar_list *ivars;
05515    struct _objc_method_list *methods;
05516    struct objc_cache *cache;
05517    struct objc_protocol_list *protocols;
05518    const char *ivar_layout;
05519    struct _objc_class_ext  *ext;
05520    };
05521    */
05522   static bool objc_class = false;
05523   if (!objc_class) {
05524     Result += "\nstruct _objc_class {\n";
05525     Result += "\tstruct _objc_class *isa;\n";
05526     Result += "\tconst char *super_class_name;\n";
05527     Result += "\tchar *name;\n";
05528     Result += "\tlong version;\n";
05529     Result += "\tlong info;\n";
05530     Result += "\tlong instance_size;\n";
05531     Result += "\tstruct _objc_ivar_list *ivars;\n";
05532     Result += "\tstruct _objc_method_list *methods;\n";
05533     Result += "\tstruct objc_cache *cache;\n";
05534     Result += "\tstruct _objc_protocol_list *protocols;\n";
05535     Result += "\tconst char *ivar_layout;\n";
05536     Result += "\tstruct _objc_class_ext  *ext;\n";
05537     Result += "};\n";
05538     objc_class = true;
05539   }
05540   
05541   // Meta-class metadata generation.
05542   ObjCInterfaceDecl *RootClass = 0;
05543   ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
05544   while (SuperClass) {
05545     RootClass = SuperClass;
05546     SuperClass = SuperClass->getSuperClass();
05547   }
05548   SuperClass = CDecl->getSuperClass();
05549   
05550   Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
05551   Result += CDecl->getNameAsString();
05552   Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
05553   "{\n\t(struct _objc_class *)\"";
05554   Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
05555   Result += "\"";
05556   
05557   if (SuperClass) {
05558     Result += ", \"";
05559     Result += SuperClass->getNameAsString();
05560     Result += "\", \"";
05561     Result += CDecl->getNameAsString();
05562     Result += "\"";
05563   }
05564   else {
05565     Result += ", 0, \"";
05566     Result += CDecl->getNameAsString();
05567     Result += "\"";
05568   }
05569   // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
05570   // 'info' field is initialized to CLS_META(2) for metaclass
05571   Result += ", 0,2, sizeof(struct _objc_class), 0";
05572   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
05573     Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
05574     Result += IDecl->getNameAsString();
05575     Result += "\n";
05576   }
05577   else
05578     Result += ", 0\n";
05579   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
05580     Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
05581     Result += CDecl->getNameAsString();
05582     Result += ",0,0\n";
05583   }
05584   else
05585     Result += "\t,0,0,0,0\n";
05586   Result += "};\n";
05587   
05588   // class metadata generation.
05589   Result += "\nstatic struct _objc_class _OBJC_CLASS_";
05590   Result += CDecl->getNameAsString();
05591   Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
05592   "{\n\t&_OBJC_METACLASS_";
05593   Result += CDecl->getNameAsString();
05594   if (SuperClass) {
05595     Result += ", \"";
05596     Result += SuperClass->getNameAsString();
05597     Result += "\", \"";
05598     Result += CDecl->getNameAsString();
05599     Result += "\"";
05600   }
05601   else {
05602     Result += ", 0, \"";
05603     Result += CDecl->getNameAsString();
05604     Result += "\"";
05605   }
05606   // 'info' field is initialized to CLS_CLASS(1) for class
05607   Result += ", 0,1";
05608   if (!ObjCSynthesizedStructs.count(CDecl))
05609     Result += ",0";
05610   else {
05611     // class has size. Must synthesize its size.
05612     Result += ",sizeof(struct ";
05613     Result += CDecl->getNameAsString();
05614     if (LangOpts.MicrosoftExt)
05615       Result += "_IMPL";
05616     Result += ")";
05617   }
05618   if (NumIvars > 0) {
05619     Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
05620     Result += CDecl->getNameAsString();
05621     Result += "\n\t";
05622   }
05623   else
05624     Result += ",0";
05625   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
05626     Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
05627     Result += CDecl->getNameAsString();
05628     Result += ", 0\n\t";
05629   }
05630   else
05631     Result += ",0,0";
05632   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
05633     Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
05634     Result += CDecl->getNameAsString();
05635     Result += ", 0,0\n";
05636   }
05637   else
05638     Result += ",0,0,0\n";
05639   Result += "};\n";
05640 }
05641 
05642 void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
05643   int ClsDefCount = ClassImplementation.size();
05644   int CatDefCount = CategoryImplementation.size();
05645   
05646   // For each implemented class, write out all its meta data.
05647   for (int i = 0; i < ClsDefCount; i++)
05648     RewriteObjCClassMetaData(ClassImplementation[i], Result);
05649   
05650   // For each implemented category, write out all its meta data.
05651   for (int i = 0; i < CatDefCount; i++)
05652     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
05653   
05654   // Write objc_symtab metadata
05655   /*
05656    struct _objc_symtab
05657    {
05658    long sel_ref_cnt;
05659    SEL *refs;
05660    short cls_def_cnt;
05661    short cat_def_cnt;
05662    void *defs[cls_def_cnt + cat_def_cnt];
05663    };
05664    */
05665   
05666   Result += "\nstruct _objc_symtab {\n";
05667   Result += "\tlong sel_ref_cnt;\n";
05668   Result += "\tSEL *refs;\n";
05669   Result += "\tshort cls_def_cnt;\n";
05670   Result += "\tshort cat_def_cnt;\n";
05671   Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
05672   Result += "};\n\n";
05673   
05674   Result += "static struct _objc_symtab "
05675   "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
05676   Result += "\t0, 0, " + utostr(ClsDefCount)
05677   + ", " + utostr(CatDefCount) + "\n";
05678   for (int i = 0; i < ClsDefCount; i++) {
05679     Result += "\t,&_OBJC_CLASS_";
05680     Result += ClassImplementation[i]->getNameAsString();
05681     Result += "\n";
05682   }
05683   
05684   for (int i = 0; i < CatDefCount; i++) {
05685     Result += "\t,&_OBJC_CATEGORY_";
05686     Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
05687     Result += "_";
05688     Result += CategoryImplementation[i]->getNameAsString();
05689     Result += "\n";
05690   }
05691   
05692   Result += "};\n\n";
05693   
05694   // Write objc_module metadata
05695   
05696   /*
05697    struct _objc_module {
05698    long version;
05699    long size;
05700    const char *name;
05701    struct _objc_symtab *symtab;
05702    }
05703    */
05704   
05705   Result += "\nstruct _objc_module {\n";
05706   Result += "\tlong version;\n";
05707   Result += "\tlong size;\n";
05708   Result += "\tconst char *name;\n";
05709   Result += "\tstruct _objc_symtab *symtab;\n";
05710   Result += "};\n\n";
05711   Result += "static struct _objc_module "
05712   "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
05713   Result += "\t" + utostr(OBJC_ABI_VERSION) +
05714   ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
05715   Result += "};\n\n";
05716   
05717   if (LangOpts.MicrosoftExt) {
05718     if (ProtocolExprDecls.size()) {
05719       Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
05720       Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
05721       for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
05722            E = ProtocolExprDecls.end(); I != E; ++I) {
05723         Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
05724         Result += (*I)->getNameAsString();
05725         Result += " = &_OBJC_PROTOCOL_";
05726         Result += (*I)->getNameAsString();
05727         Result += ";\n";
05728       }
05729       Result += "#pragma data_seg(pop)\n\n";
05730     }
05731     Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
05732     Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
05733     Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
05734     Result += "&_OBJC_MODULES;\n";
05735     Result += "#pragma data_seg(pop)\n\n";
05736   }
05737 }
05738 
05739 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
05740 /// implementation.
05741 void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
05742                                               std::string &Result) {
05743   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
05744   // Find category declaration for this implementation.
05745   ObjCCategoryDecl *CDecl;
05746   for (CDecl = ClassDecl->getCategoryList(); CDecl;
05747        CDecl = CDecl->getNextClassCategory())
05748     if (CDecl->getIdentifier() == IDecl->getIdentifier())
05749       break;
05750   
05751   std::string FullCategoryName = ClassDecl->getNameAsString();
05752   FullCategoryName += '_';
05753   FullCategoryName += IDecl->getNameAsString();
05754   
05755   // Build _objc_method_list for class's instance methods if needed
05756   SmallVector<ObjCMethodDecl *, 32>
05757   InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
05758   
05759   // If any of our property implementations have associated getters or
05760   // setters, produce metadata for them as well.
05761   for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
05762        PropEnd = IDecl->propimpl_end();
05763        Prop != PropEnd; ++Prop) {
05764     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
05765       continue;
05766     if (!Prop->getPropertyIvarDecl())
05767       continue;
05768     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
05769     if (!PD)
05770       continue;
05771     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
05772       InstanceMethods.push_back(Getter);
05773     if (PD->isReadOnly())
05774       continue;
05775     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
05776       InstanceMethods.push_back(Setter);
05777   }
05778   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
05779                              true, "CATEGORY_", FullCategoryName.c_str(),
05780                              Result);
05781   
05782   // Build _objc_method_list for class's class methods if needed
05783   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
05784                              false, "CATEGORY_", FullCategoryName.c_str(),
05785                              Result);
05786   
05787   // Protocols referenced in class declaration?
05788   // Null CDecl is case of a category implementation with no category interface
05789   if (CDecl)
05790     RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
05791                                     FullCategoryName, Result);
05792   /* struct _objc_category {
05793    char *category_name;
05794    char *class_name;
05795    struct _objc_method_list *instance_methods;
05796    struct _objc_method_list *class_methods;
05797    struct _objc_protocol_list *protocols;
05798    // Objective-C 1.0 extensions
05799    uint32_t size;     // sizeof (struct _objc_category)
05800    struct _objc_property_list *instance_properties;  // category's own
05801    // @property decl.
05802    };
05803    */
05804   
05805   static bool objc_category = false;
05806   if (!objc_category) {
05807     Result += "\nstruct _objc_category {\n";
05808     Result += "\tchar *category_name;\n";
05809     Result += "\tchar *class_name;\n";
05810     Result += "\tstruct _objc_method_list *instance_methods;\n";
05811     Result += "\tstruct _objc_method_list *class_methods;\n";
05812     Result += "\tstruct _objc_protocol_list *protocols;\n";
05813     Result += "\tunsigned int size;\n";
05814     Result += "\tstruct _objc_property_list *instance_properties;\n";
05815     Result += "};\n";
05816     objc_category = true;
05817   }
05818   Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
05819   Result += FullCategoryName;
05820   Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
05821   Result += IDecl->getNameAsString();
05822   Result += "\"\n\t, \"";
05823   Result += ClassDecl->getNameAsString();
05824   Result += "\"\n";
05825   
05826   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
05827     Result += "\t, (struct _objc_method_list *)"
05828     "&_OBJC_CATEGORY_INSTANCE_METHODS_";
05829     Result += FullCategoryName;
05830     Result += "\n";
05831   }
05832   else
05833     Result += "\t, 0\n";
05834   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
05835     Result += "\t, (struct _objc_method_list *)"
05836     "&_OBJC_CATEGORY_CLASS_METHODS_";
05837     Result += FullCategoryName;
05838     Result += "\n";
05839   }
05840   else
05841     Result += "\t, 0\n";
05842   
05843   if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
05844     Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
05845     Result += FullCategoryName;
05846     Result += "\n";
05847   }
05848   else
05849     Result += "\t, 0\n";
05850   Result += "\t, sizeof(struct _objc_category), 0\n};\n";
05851 }
05852 
05853 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
05854 /// class methods.
05855 template<typename MethodIterator>
05856 void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
05857                                              MethodIterator MethodEnd,
05858                                              bool IsInstanceMethod,
05859                                              StringRef prefix,
05860                                              StringRef ClassName,
05861                                              std::string &Result) {
05862   if (MethodBegin == MethodEnd) return;
05863   
05864   if (!objc_impl_method) {
05865     /* struct _objc_method {
05866      SEL _cmd;
05867      char *method_types;
05868      void *_imp;
05869      }
05870      */
05871     Result += "\nstruct _objc_method {\n";
05872     Result += "\tSEL _cmd;\n";
05873     Result += "\tchar *method_types;\n";
05874     Result += "\tvoid *_imp;\n";
05875     Result += "};\n";
05876     
05877     objc_impl_method = true;
05878   }
05879   
05880   // Build _objc_method_list for class's methods if needed
05881   
05882   /* struct  {
05883    struct _objc_method_list *next_method;
05884    int method_count;
05885    struct _objc_method method_list[];
05886    }
05887    */
05888   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
05889   Result += "\nstatic struct {\n";
05890   Result += "\tstruct _objc_method_list *next_method;\n";
05891   Result += "\tint method_count;\n";
05892   Result += "\tstruct _objc_method method_list[";
05893   Result += utostr(NumMethods);
05894   Result += "];\n} _OBJC_";
05895   Result += prefix;
05896   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
05897   Result += "_METHODS_";
05898   Result += ClassName;
05899   Result += " __attribute__ ((used, section (\"__OBJC, __";
05900   Result += IsInstanceMethod ? "inst" : "cls";
05901   Result += "_meth\")))= ";
05902   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
05903   
05904   Result += "\t,{{(SEL)\"";
05905   Result += (*MethodBegin)->getSelector().getAsString().c_str();
05906   std::string MethodTypeString;
05907   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
05908   Result += "\", \"";
05909   Result += MethodTypeString;
05910   Result += "\", (void *)";
05911   Result += MethodInternalNames[*MethodBegin];
05912   Result += "}\n";
05913   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
05914     Result += "\t  ,{(SEL)\"";
05915     Result += (*MethodBegin)->getSelector().getAsString().c_str();
05916     std::string MethodTypeString;
05917     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
05918     Result += "\", \"";
05919     Result += MethodTypeString;
05920     Result += "\", (void *)";
05921     Result += MethodInternalNames[*MethodBegin];
05922     Result += "}\n";
05923   }
05924   Result += "\t }\n};\n";
05925 }
05926 
05927 Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
05928   SourceRange OldRange = IV->getSourceRange();
05929   Expr *BaseExpr = IV->getBase();
05930   
05931   // Rewrite the base, but without actually doing replaces.
05932   {
05933     DisableReplaceStmtScope S(*this);
05934     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
05935     IV->setBase(BaseExpr);
05936   }
05937   
05938   ObjCIvarDecl *D = IV->getDecl();
05939   
05940   Expr *Replacement = IV;
05941   if (CurMethodDef) {
05942     if (BaseExpr->getType()->isObjCObjectPointerType()) {
05943       const ObjCInterfaceType *iFaceDecl =
05944       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
05945       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
05946       // lookup which class implements the instance variable.
05947       ObjCInterfaceDecl *clsDeclared = 0;
05948       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
05949                                                    clsDeclared);
05950       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
05951       
05952       // Synthesize an explicit cast to gain access to the ivar.
05953       std::string RecName = clsDeclared->getIdentifier()->getName();
05954       RecName += "_IMPL";
05955       IdentifierInfo *II = &Context->Idents.get(RecName);
05956       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
05957                                           SourceLocation(), SourceLocation(),
05958                                           II);
05959       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
05960       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
05961       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
05962                                                     CK_BitCast,
05963                                                     IV->getBase());
05964       // Don't forget the parens to enforce the proper binding.
05965       ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
05966                                               OldRange.getEnd(),
05967                                               castExpr);
05968       if (IV->isFreeIvar() &&
05969           declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
05970         MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
05971                                                   IV->getLocation(),
05972                                                   D->getType(),
05973                                                   VK_LValue, OK_Ordinary);
05974         Replacement = ME;
05975       } else {
05976         IV->setBase(PE);
05977       }
05978     }
05979   } else { // we are outside a method.
05980     assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
05981     
05982     // Explicit ivar refs need to have a cast inserted.
05983     // FIXME: consider sharing some of this code with the code above.
05984     if (BaseExpr->getType()->isObjCObjectPointerType()) {
05985       const ObjCInterfaceType *iFaceDecl =
05986       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
05987       // lookup which class implements the instance variable.
05988       ObjCInterfaceDecl *clsDeclared = 0;
05989       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
05990                                                    clsDeclared);
05991       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
05992       
05993       // Synthesize an explicit cast to gain access to the ivar.
05994       std::string RecName = clsDeclared->getIdentifier()->getName();
05995       RecName += "_IMPL";
05996       IdentifierInfo *II = &Context->Idents.get(RecName);
05997       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
05998                                           SourceLocation(), SourceLocation(),
05999                                           II);
06000       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
06001       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
06002       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
06003                                                     CK_BitCast,
06004                                                     IV->getBase());
06005       // Don't forget the parens to enforce the proper binding.
06006       ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
06007                                               IV->getBase()->getLocEnd(), castExpr);
06008       // Cannot delete IV->getBase(), since PE points to it.
06009       // Replace the old base with the cast. This is important when doing
06010       // embedded rewrites. For example, [newInv->_container addObject:0].
06011       IV->setBase(PE);
06012     }
06013   }
06014   
06015   ReplaceStmtWithRange(IV, Replacement, OldRange);
06016   return Replacement;  
06017 }
06018