]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Rewrite/Frontend/RewriteModernObjC.cpp
Partial MFC of r234508 (by adrian):
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Rewrite / Frontend / RewriteModernObjC.cpp
1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Hacks and fun related to the code rewriter.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Rewrite/Frontend/ASTConsumers.h"
15 #include "clang/Rewrite/Core/Rewriter.h"
16 #include "clang/AST/AST.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Lex/Lexer.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/DenseSet.h"
29
30 using namespace clang;
31 using llvm::utostr;
32
33 namespace {
34   class RewriteModernObjC : public ASTConsumer {
35   protected:
36     
37     enum {
38       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
39                                         block, ... */
40       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
41       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the 
42                                         __block variable */
43       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
44                                         helpers */
45       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
46                                         support routines */
47       BLOCK_BYREF_CURRENT_MAX = 256
48     };
49     
50     enum {
51       BLOCK_NEEDS_FREE =        (1 << 24),
52       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
53       BLOCK_HAS_CXX_OBJ =       (1 << 26),
54       BLOCK_IS_GC =             (1 << 27),
55       BLOCK_IS_GLOBAL =         (1 << 28),
56       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
57     };
58     static const int OBJC_ABI_VERSION = 7;
59     
60     Rewriter Rewrite;
61     DiagnosticsEngine &Diags;
62     const LangOptions &LangOpts;
63     ASTContext *Context;
64     SourceManager *SM;
65     TranslationUnitDecl *TUDecl;
66     FileID MainFileID;
67     const char *MainFileStart, *MainFileEnd;
68     Stmt *CurrentBody;
69     ParentMap *PropParentMap; // created lazily.
70     std::string InFileName;
71     raw_ostream* OutFile;
72     std::string Preamble;
73     
74     TypeDecl *ProtocolTypeDecl;
75     VarDecl *GlobalVarDecl;
76     Expr *GlobalConstructionExp;
77     unsigned RewriteFailedDiag;
78     unsigned GlobalBlockRewriteFailedDiag;
79     // ObjC string constant support.
80     unsigned NumObjCStringLiterals;
81     VarDecl *ConstantStringClassReference;
82     RecordDecl *NSStringRecord;
83
84     // ObjC foreach break/continue generation support.
85     int BcLabelCount;
86     
87     unsigned TryFinallyContainsReturnDiag;
88     // Needed for super.
89     ObjCMethodDecl *CurMethodDef;
90     RecordDecl *SuperStructDecl;
91     RecordDecl *ConstantStringDecl;
92     
93     FunctionDecl *MsgSendFunctionDecl;
94     FunctionDecl *MsgSendSuperFunctionDecl;
95     FunctionDecl *MsgSendStretFunctionDecl;
96     FunctionDecl *MsgSendSuperStretFunctionDecl;
97     FunctionDecl *MsgSendFpretFunctionDecl;
98     FunctionDecl *GetClassFunctionDecl;
99     FunctionDecl *GetMetaClassFunctionDecl;
100     FunctionDecl *GetSuperClassFunctionDecl;
101     FunctionDecl *SelGetUidFunctionDecl;
102     FunctionDecl *CFStringFunctionDecl;
103     FunctionDecl *SuperContructorFunctionDecl;
104     FunctionDecl *CurFunctionDef;
105
106     /* Misc. containers needed for meta-data rewrite. */
107     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
111     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
112     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
113     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
114     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116     
117     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118     llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119     
120     SmallVector<Stmt *, 32> Stmts;
121     SmallVector<int, 8> ObjCBcLabelNo;
122     // Remember all the @protocol(<expr>) expressions.
123     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124     
125     llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127     // Block expressions.
128     SmallVector<BlockExpr *, 32> Blocks;
129     SmallVector<int, 32> InnerDeclRefsCount;
130     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
131     
132     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
133
134     // Block related declarations.
135     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137     SmallVector<ValueDecl *, 8> BlockByRefDecls;
138     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142     
143     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
144     llvm::DenseMap<ObjCInterfaceDecl *, 
145                     llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146     
147     // This maps an original source AST to it's rewritten form. This allows
148     // us to avoid rewriting the same node twice (which is very uncommon).
149     // This is needed to support some of the exotic property rewriting.
150     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152     // Needed for header files being rewritten
153     bool IsHeader;
154     bool SilenceRewriteMacroWarning;
155     bool objc_impl_method;
156     
157     bool DisableReplaceStmt;
158     class DisableReplaceStmtScope {
159       RewriteModernObjC &R;
160       bool SavedValue;
161     
162     public:
163       DisableReplaceStmtScope(RewriteModernObjC &R)
164         : R(R), SavedValue(R.DisableReplaceStmt) {
165         R.DisableReplaceStmt = true;
166       }
167       ~DisableReplaceStmtScope() {
168         R.DisableReplaceStmt = SavedValue;
169       }
170     };
171     void InitializeCommon(ASTContext &context);
172
173   public:
174     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
175     // Top Level Driver code.
176     virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179           if (!Class->isThisDeclarationADefinition()) {
180             RewriteForwardClassDecl(D);
181             break;
182           } else {
183             // Keep track of all interface declarations seen.
184             ObjCInterfacesSeen.push_back(Class);
185             break;
186           }
187         }
188
189         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190           if (!Proto->isThisDeclarationADefinition()) {
191             RewriteForwardProtocolDecl(D);
192             break;
193           }
194         }
195
196         HandleTopLevelSingleDecl(*I);
197       }
198       return true;
199     }
200     void HandleTopLevelSingleDecl(Decl *D);
201     void HandleDeclInMainFile(Decl *D);
202     RewriteModernObjC(std::string inFile, raw_ostream *OS,
203                 DiagnosticsEngine &D, const LangOptions &LOpts,
204                 bool silenceMacroWarn);
205     
206     ~RewriteModernObjC() {}
207     
208     virtual void HandleTranslationUnit(ASTContext &C);
209
210     void ReplaceStmt(Stmt *Old, Stmt *New) {
211       Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213       if (ReplacingStmt)
214         return; // We can't rewrite the same node twice.
215
216       if (DisableReplaceStmt)
217         return;
218
219       // If replacement succeeded or warning disabled return with no warning.
220       if (!Rewrite.ReplaceStmt(Old, New)) {
221         ReplacedNodes[Old] = New;
222         return;
223       }
224       if (SilenceRewriteMacroWarning)
225         return;
226       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227                    << Old->getSourceRange();
228     }
229
230     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231       if (DisableReplaceStmt)
232         return;
233
234       // Measure the old text.
235       int Size = Rewrite.getRangeSize(SrcRange);
236       if (Size == -1) {
237         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238                      << Old->getSourceRange();
239         return;
240       }
241       // Get the new text.
242       std::string SStr;
243       llvm::raw_string_ostream S(SStr);
244       New->printPretty(S, 0, PrintingPolicy(LangOpts));
245       const std::string &Str = S.str();
246
247       // If replacement succeeded or warning disabled return with no warning.
248       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249         ReplacedNodes[Old] = New;
250         return;
251       }
252       if (SilenceRewriteMacroWarning)
253         return;
254       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255                    << Old->getSourceRange();
256     }
257
258     void InsertText(SourceLocation Loc, StringRef Str,
259                     bool InsertAfter = true) {
260       // If insertion succeeded or warning disabled return with no warning.
261       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262           SilenceRewriteMacroWarning)
263         return;
264
265       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266     }
267
268     void ReplaceText(SourceLocation Start, unsigned OrigLength,
269                      StringRef Str) {
270       // If removal succeeded or warning disabled return with no warning.
271       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272           SilenceRewriteMacroWarning)
273         return;
274
275       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276     }
277
278     // Syntactic Rewriting.
279     void RewriteRecordBody(RecordDecl *RD);
280     void RewriteInclude();
281     void RewriteLineDirective(const Decl *D);
282     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
283                                               std::string &LineString);
284     void RewriteForwardClassDecl(DeclGroupRef D);
285     void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
286     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 
287                                      const std::string &typedefString);
288     void RewriteImplementations();
289     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
290                                  ObjCImplementationDecl *IMD,
291                                  ObjCCategoryImplDecl *CID);
292     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
293     void RewriteImplementationDecl(Decl *Dcl);
294     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
295                                ObjCMethodDecl *MDecl, std::string &ResultStr);
296     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
297                                const FunctionType *&FPRetType);
298     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
299                             ValueDecl *VD, bool def=false);
300     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
301     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
302     void RewriteForwardProtocolDecl(DeclGroupRef D);
303     void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
304     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
305     void RewriteProperty(ObjCPropertyDecl *prop);
306     void RewriteFunctionDecl(FunctionDecl *FD);
307     void RewriteBlockPointerType(std::string& Str, QualType Type);
308     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
309     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
310     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
311     void RewriteTypeOfDecl(VarDecl *VD);
312     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
313     
314     std::string getIvarAccessString(ObjCIvarDecl *D);
315   
316     // Expression Rewriting.
317     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
318     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
319     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
320     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
321     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
322     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
323     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
324     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
325     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
326     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
327     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
328     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
329     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
330     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
331     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
332     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
333     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
334                                        SourceLocation OrigEnd);
335     Stmt *RewriteBreakStmt(BreakStmt *S);
336     Stmt *RewriteContinueStmt(ContinueStmt *S);
337     void RewriteCastExpr(CStyleCastExpr *CE);
338     void RewriteImplicitCastObjCExpr(CastExpr *IE);
339     void RewriteLinkageSpec(LinkageSpecDecl *LSD);
340     
341     // Block rewriting.
342     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
343     
344     // Block specific rewrite rules.
345     void RewriteBlockPointerDecl(NamedDecl *VD);
346     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
347     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
348     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
349     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
350     
351     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
352                                       std::string &Result);
353     
354     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
355     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
356                                  bool &IsNamedDefinition);
357     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 
358                                               std::string &Result);
359     
360     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
361     
362     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
363                                   std::string &Result);
364     
365     virtual void Initialize(ASTContext &context);
366     
367     // Misc. AST transformation routines. Sometimes they end up calling
368     // rewriting routines on the new ASTs.
369     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
370                                            Expr **args, unsigned nargs,
371                                            SourceLocation StartLoc=SourceLocation(),
372                                            SourceLocation EndLoc=SourceLocation());
373     
374     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
375                                         QualType msgSendType, 
376                                         QualType returnType, 
377                                         SmallVectorImpl<QualType> &ArgTypes,
378                                         SmallVectorImpl<Expr*> &MsgExprs,
379                                         ObjCMethodDecl *Method);
380
381     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
382                            SourceLocation StartLoc=SourceLocation(),
383                            SourceLocation EndLoc=SourceLocation());
384     
385     void SynthCountByEnumWithState(std::string &buf);
386     void SynthMsgSendFunctionDecl();
387     void SynthMsgSendSuperFunctionDecl();
388     void SynthMsgSendStretFunctionDecl();
389     void SynthMsgSendFpretFunctionDecl();
390     void SynthMsgSendSuperStretFunctionDecl();
391     void SynthGetClassFunctionDecl();
392     void SynthGetMetaClassFunctionDecl();
393     void SynthGetSuperClassFunctionDecl();
394     void SynthSelGetUidFunctionDecl();
395     void SynthSuperContructorFunctionDecl();
396     
397     // Rewriting metadata
398     template<typename MethodIterator>
399     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
400                                     MethodIterator MethodEnd,
401                                     bool IsInstanceMethod,
402                                     StringRef prefix,
403                                     StringRef ClassName,
404                                     std::string &Result);
405     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
406                                      std::string &Result);
407     void RewriteObjCProtocolListMetaData(
408                    const ObjCList<ObjCProtocolDecl> &Prots,
409                    StringRef prefix, StringRef ClassName, std::string &Result);
410     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
411                                           std::string &Result);
412     void RewriteClassSetupInitHook(std::string &Result);
413     
414     void RewriteMetaDataIntoBuffer(std::string &Result);
415     void WriteImageInfo(std::string &Result);
416     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
417                                              std::string &Result);
418     void RewriteCategorySetupInitHook(std::string &Result);
419     
420     // Rewriting ivar
421     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
422                                               std::string &Result);
423     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
424
425     
426     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
427     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
428                                       StringRef funcName, std::string Tag);
429     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
430                                       StringRef funcName, std::string Tag);
431     std::string SynthesizeBlockImpl(BlockExpr *CE, 
432                                     std::string Tag, std::string Desc);
433     std::string SynthesizeBlockDescriptor(std::string DescTag, 
434                                           std::string ImplTag,
435                                           int i, StringRef funcName,
436                                           unsigned hasCopy);
437     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
438     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
439                                  StringRef FunName);
440     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
441     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
442             const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
443
444     // Misc. helper routines.
445     QualType getProtocolType();
446     void WarnAboutReturnGotoStmts(Stmt *S);
447     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
448     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
449     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
450
451     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
452     void CollectBlockDeclRefInfo(BlockExpr *Exp);
453     void GetBlockDeclRefExprs(Stmt *S);
454     void GetInnerBlockDeclRefExprs(Stmt *S, 
455                 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
456                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
457
458     // We avoid calling Type::isBlockPointerType(), since it operates on the
459     // canonical type. We only care if the top-level type is a closure pointer.
460     bool isTopLevelBlockPointerType(QualType T) {
461       return isa<BlockPointerType>(T);
462     }
463
464     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
465     /// to a function pointer type and upon success, returns true; false
466     /// otherwise.
467     bool convertBlockPointerToFunctionPointer(QualType &T) {
468       if (isTopLevelBlockPointerType(T)) {
469         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
470         T = Context->getPointerType(BPT->getPointeeType());
471         return true;
472       }
473       return false;
474     }
475     
476     bool convertObjCTypeToCStyleType(QualType &T);
477     
478     bool needToScanForQualifiers(QualType T);
479     QualType getSuperStructType();
480     QualType getConstantStringStructType();
481     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
482     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
483     
484     void convertToUnqualifiedObjCType(QualType &T) {
485       if (T->isObjCQualifiedIdType()) {
486         bool isConst = T.isConstQualified();
487         T = isConst ? Context->getObjCIdType().withConst() 
488                     : Context->getObjCIdType();
489       }
490       else if (T->isObjCQualifiedClassType())
491         T = Context->getObjCClassType();
492       else if (T->isObjCObjectPointerType() &&
493                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
494         if (const ObjCObjectPointerType * OBJPT =
495               T->getAsObjCInterfacePointerType()) {
496           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
497           T = QualType(IFaceT, 0);
498           T = Context->getPointerType(T);
499         }
500      }
501     }
502     
503     // FIXME: This predicate seems like it would be useful to add to ASTContext.
504     bool isObjCType(QualType T) {
505       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
506         return false;
507
508       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
509
510       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
511           OCT == Context->getCanonicalType(Context->getObjCClassType()))
512         return true;
513
514       if (const PointerType *PT = OCT->getAs<PointerType>()) {
515         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
516             PT->getPointeeType()->isObjCQualifiedIdType())
517           return true;
518       }
519       return false;
520     }
521     bool PointerTypeTakesAnyBlockArguments(QualType QT);
522     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
523     void GetExtentOfArgList(const char *Name, const char *&LParen,
524                             const char *&RParen);
525     
526     void QuoteDoublequotes(std::string &From, std::string &To) {
527       for (unsigned i = 0; i < From.length(); i++) {
528         if (From[i] == '"')
529           To += "\\\"";
530         else
531           To += From[i];
532       }
533     }
534
535     QualType getSimpleFunctionType(QualType result,
536                                    const QualType *args,
537                                    unsigned numArgs,
538                                    bool variadic = false) {
539       if (result == Context->getObjCInstanceType())
540         result =  Context->getObjCIdType();
541       FunctionProtoType::ExtProtoInfo fpi;
542       fpi.Variadic = variadic;
543       return Context->getFunctionType(result, args, numArgs, fpi);
544     }
545
546     // Helper function: create a CStyleCastExpr with trivial type source info.
547     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
548                                              CastKind Kind, Expr *E) {
549       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
550       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
551                                     SourceLocation(), SourceLocation());
552     }
553     
554     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
555       IdentifierInfo* II = &Context->Idents.get("load");
556       Selector LoadSel = Context->Selectors.getSelector(0, &II);
557       return OD->getClassMethod(LoadSel) != 0;
558     }
559   };
560   
561 }
562
563 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
564                                                    NamedDecl *D) {
565   if (const FunctionProtoType *fproto
566       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
567     for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
568          E = fproto->arg_type_end(); I && (I != E); ++I)
569       if (isTopLevelBlockPointerType(*I)) {
570         // All the args are checked/rewritten. Don't call twice!
571         RewriteBlockPointerDecl(D);
572         break;
573       }
574   }
575 }
576
577 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
578   const PointerType *PT = funcType->getAs<PointerType>();
579   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
580     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
581 }
582
583 static bool IsHeaderFile(const std::string &Filename) {
584   std::string::size_type DotPos = Filename.rfind('.');
585
586   if (DotPos == std::string::npos) {
587     // no file extension
588     return false;
589   }
590
591   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
592   // C header: .h
593   // C++ header: .hh or .H;
594   return Ext == "h" || Ext == "hh" || Ext == "H";
595 }
596
597 RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
598                          DiagnosticsEngine &D, const LangOptions &LOpts,
599                          bool silenceMacroWarn)
600       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
601         SilenceRewriteMacroWarning(silenceMacroWarn) {
602   IsHeader = IsHeaderFile(inFile);
603   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
604                "rewriting sub-expression within a macro (may not be correct)");
605   // FIXME. This should be an error. But if block is not called, it is OK. And it
606   // may break including some headers.
607   GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
608     "rewriting block literal declared in global scope is not implemented");
609           
610   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
611                DiagnosticsEngine::Warning,
612                "rewriter doesn't support user-specified control flow semantics "
613                "for @try/@finally (code may not execute properly)");
614 }
615
616 ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
617                                        raw_ostream* OS,
618                                        DiagnosticsEngine &Diags,
619                                        const LangOptions &LOpts,
620                                        bool SilenceRewriteMacroWarning) {
621     return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
622 }
623
624 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
625   Context = &context;
626   SM = &Context->getSourceManager();
627   TUDecl = Context->getTranslationUnitDecl();
628   MsgSendFunctionDecl = 0;
629   MsgSendSuperFunctionDecl = 0;
630   MsgSendStretFunctionDecl = 0;
631   MsgSendSuperStretFunctionDecl = 0;
632   MsgSendFpretFunctionDecl = 0;
633   GetClassFunctionDecl = 0;
634   GetMetaClassFunctionDecl = 0;
635   GetSuperClassFunctionDecl = 0;
636   SelGetUidFunctionDecl = 0;
637   CFStringFunctionDecl = 0;
638   ConstantStringClassReference = 0;
639   NSStringRecord = 0;
640   CurMethodDef = 0;
641   CurFunctionDef = 0;
642   GlobalVarDecl = 0;
643   GlobalConstructionExp = 0;
644   SuperStructDecl = 0;
645   ProtocolTypeDecl = 0;
646   ConstantStringDecl = 0;
647   BcLabelCount = 0;
648   SuperContructorFunctionDecl = 0;
649   NumObjCStringLiterals = 0;
650   PropParentMap = 0;
651   CurrentBody = 0;
652   DisableReplaceStmt = false;
653   objc_impl_method = false;
654
655   // Get the ID and start/end of the main file.
656   MainFileID = SM->getMainFileID();
657   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
658   MainFileStart = MainBuf->getBufferStart();
659   MainFileEnd = MainBuf->getBufferEnd();
660
661   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
662 }
663
664 //===----------------------------------------------------------------------===//
665 // Top Level Driver Code
666 //===----------------------------------------------------------------------===//
667
668 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
669   if (Diags.hasErrorOccurred())
670     return;
671
672   // Two cases: either the decl could be in the main file, or it could be in a
673   // #included file.  If the former, rewrite it now.  If the later, check to see
674   // if we rewrote the #include/#import.
675   SourceLocation Loc = D->getLocation();
676   Loc = SM->getExpansionLoc(Loc);
677
678   // If this is for a builtin, ignore it.
679   if (Loc.isInvalid()) return;
680
681   // Look for built-in declarations that we need to refer during the rewrite.
682   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
683     RewriteFunctionDecl(FD);
684   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
685     // declared in <Foundation/NSString.h>
686     if (FVD->getName() == "_NSConstantStringClassReference") {
687       ConstantStringClassReference = FVD;
688       return;
689     }
690   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
691     RewriteCategoryDecl(CD);
692   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
693     if (PD->isThisDeclarationADefinition())
694       RewriteProtocolDecl(PD);
695   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
696     // FIXME. This will not work in all situations and leaving it out
697     // is harmless.
698     // RewriteLinkageSpec(LSD);
699     
700     // Recurse into linkage specifications
701     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
702                                  DIEnd = LSD->decls_end();
703          DI != DIEnd; ) {
704       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
705         if (!IFace->isThisDeclarationADefinition()) {
706           SmallVector<Decl *, 8> DG;
707           SourceLocation StartLoc = IFace->getLocStart();
708           do {
709             if (isa<ObjCInterfaceDecl>(*DI) &&
710                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
711                 StartLoc == (*DI)->getLocStart())
712               DG.push_back(*DI);
713             else
714               break;
715             
716             ++DI;
717           } while (DI != DIEnd);
718           RewriteForwardClassDecl(DG);
719           continue;
720         }
721         else {
722           // Keep track of all interface declarations seen.
723           ObjCInterfacesSeen.push_back(IFace);
724           ++DI;
725           continue;
726         }
727       }
728
729       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
730         if (!Proto->isThisDeclarationADefinition()) {
731           SmallVector<Decl *, 8> DG;
732           SourceLocation StartLoc = Proto->getLocStart();
733           do {
734             if (isa<ObjCProtocolDecl>(*DI) &&
735                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
736                 StartLoc == (*DI)->getLocStart())
737               DG.push_back(*DI);
738             else
739               break;
740             
741             ++DI;
742           } while (DI != DIEnd);
743           RewriteForwardProtocolDecl(DG);
744           continue;
745         }
746       }
747       
748       HandleTopLevelSingleDecl(*DI);
749       ++DI;
750     }
751   }
752   // If we have a decl in the main file, see if we should rewrite it.
753   if (SM->isFromMainFile(Loc))
754     return HandleDeclInMainFile(D);
755 }
756
757 //===----------------------------------------------------------------------===//
758 // Syntactic (non-AST) Rewriting Code
759 //===----------------------------------------------------------------------===//
760
761 void RewriteModernObjC::RewriteInclude() {
762   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
763   StringRef MainBuf = SM->getBufferData(MainFileID);
764   const char *MainBufStart = MainBuf.begin();
765   const char *MainBufEnd = MainBuf.end();
766   size_t ImportLen = strlen("import");
767
768   // Loop over the whole file, looking for includes.
769   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
770     if (*BufPtr == '#') {
771       if (++BufPtr == MainBufEnd)
772         return;
773       while (*BufPtr == ' ' || *BufPtr == '\t')
774         if (++BufPtr == MainBufEnd)
775           return;
776       if (!strncmp(BufPtr, "import", ImportLen)) {
777         // replace import with include
778         SourceLocation ImportLoc =
779           LocStart.getLocWithOffset(BufPtr-MainBufStart);
780         ReplaceText(ImportLoc, ImportLen, "include");
781         BufPtr += ImportLen;
782       }
783     }
784   }
785 }
786
787 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
788                                   ObjCIvarDecl *IvarDecl, std::string &Result) {
789   Result += "OBJC_IVAR_$_";
790   Result += IDecl->getName();
791   Result += "$";
792   Result += IvarDecl->getName();
793 }
794
795 std::string 
796 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
797   const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
798   
799   // Build name of symbol holding ivar offset.
800   std::string IvarOffsetName;
801   WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
802   
803   
804   std::string S = "(*(";
805   QualType IvarT = D->getType();
806   
807   if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
808     RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
809     RD = RD->getDefinition();
810     if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
811       // decltype(((Foo_IMPL*)0)->bar) *
812       ObjCContainerDecl *CDecl = 
813       dyn_cast<ObjCContainerDecl>(D->getDeclContext());
814       // ivar in class extensions requires special treatment.
815       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
816         CDecl = CatDecl->getClassInterface();
817       std::string RecName = CDecl->getName();
818       RecName += "_IMPL";
819       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
820                                           SourceLocation(), SourceLocation(),
821                                           &Context->Idents.get(RecName.c_str()));
822       QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
823       unsigned UnsignedIntSize = 
824       static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
825       Expr *Zero = IntegerLiteral::Create(*Context,
826                                           llvm::APInt(UnsignedIntSize, 0),
827                                           Context->UnsignedIntTy, SourceLocation());
828       Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
829       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
830                                               Zero);
831       FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
832                                         SourceLocation(),
833                                         &Context->Idents.get(D->getNameAsString()),
834                                         IvarT, 0,
835                                         /*BitWidth=*/0, /*Mutable=*/true,
836                                         ICIS_NoInit);
837       MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
838                                                 FD->getType(), VK_LValue,
839                                                 OK_Ordinary);
840       IvarT = Context->getDecltypeType(ME, ME->getType());
841     }
842   }
843   convertObjCTypeToCStyleType(IvarT);
844   QualType castT = Context->getPointerType(IvarT);
845   std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
846   S += TypeString;
847   S += ")";
848   
849   // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
850   S += "((char *)self + ";
851   S += IvarOffsetName;
852   S += "))";
853   ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
854   return S;
855 }
856
857 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
858 /// been found in the class implementation. In this case, it must be synthesized.
859 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
860                                              ObjCPropertyDecl *PD,
861                                              bool getter) {
862   return getter ? !IMP->getInstanceMethod(PD->getGetterName())
863                 : !IMP->getInstanceMethod(PD->getSetterName());
864   
865 }
866
867 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
868                                           ObjCImplementationDecl *IMD,
869                                           ObjCCategoryImplDecl *CID) {
870   static bool objcGetPropertyDefined = false;
871   static bool objcSetPropertyDefined = false;
872   SourceLocation startGetterSetterLoc;
873   
874   if (PID->getLocStart().isValid()) {
875     SourceLocation startLoc = PID->getLocStart();
876     InsertText(startLoc, "// ");
877     const char *startBuf = SM->getCharacterData(startLoc);
878     assert((*startBuf == '@') && "bogus @synthesize location");
879     const char *semiBuf = strchr(startBuf, ';');
880     assert((*semiBuf == ';') && "@synthesize: can't find ';'");
881     startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
882   }
883   else
884     startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
885
886   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
887     return; // FIXME: is this correct?
888
889   // Generate the 'getter' function.
890   ObjCPropertyDecl *PD = PID->getPropertyDecl();
891   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
892
893   if (!OID)
894     return;
895   unsigned Attributes = PD->getPropertyAttributes();
896   if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
897     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
898                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
899                                          ObjCPropertyDecl::OBJC_PR_copy));
900     std::string Getr;
901     if (GenGetProperty && !objcGetPropertyDefined) {
902       objcGetPropertyDefined = true;
903       // FIXME. Is this attribute correct in all cases?
904       Getr = "\nextern \"C\" __declspec(dllimport) "
905             "id objc_getProperty(id, SEL, long, bool);\n";
906     }
907     RewriteObjCMethodDecl(OID->getContainingInterface(),  
908                           PD->getGetterMethodDecl(), Getr);
909     Getr += "{ ";
910     // Synthesize an explicit cast to gain access to the ivar.
911     // See objc-act.c:objc_synthesize_new_getter() for details.
912     if (GenGetProperty) {
913       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
914       Getr += "typedef ";
915       const FunctionType *FPRetType = 0;
916       RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr, 
917                             FPRetType);
918       Getr += " _TYPE";
919       if (FPRetType) {
920         Getr += ")"; // close the precedence "scope" for "*".
921       
922         // Now, emit the argument types (if any).
923         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
924           Getr += "(";
925           for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
926             if (i) Getr += ", ";
927             std::string ParamStr = FT->getArgType(i).getAsString(
928                                                           Context->getPrintingPolicy());
929             Getr += ParamStr;
930           }
931           if (FT->isVariadic()) {
932             if (FT->getNumArgs()) Getr += ", ";
933             Getr += "...";
934           }
935           Getr += ")";
936         } else
937           Getr += "()";
938       }
939       Getr += ";\n";
940       Getr += "return (_TYPE)";
941       Getr += "objc_getProperty(self, _cmd, ";
942       RewriteIvarOffsetComputation(OID, Getr);
943       Getr += ", 1)";
944     }
945     else
946       Getr += "return " + getIvarAccessString(OID);
947     Getr += "; }";
948     InsertText(startGetterSetterLoc, Getr);
949   }
950   
951   if (PD->isReadOnly() || 
952       !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
953     return;
954
955   // Generate the 'setter' function.
956   std::string Setr;
957   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
958                                       ObjCPropertyDecl::OBJC_PR_copy);
959   if (GenSetProperty && !objcSetPropertyDefined) {
960     objcSetPropertyDefined = true;
961     // FIXME. Is this attribute correct in all cases?
962     Setr = "\nextern \"C\" __declspec(dllimport) "
963     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
964   }
965   
966   RewriteObjCMethodDecl(OID->getContainingInterface(), 
967                         PD->getSetterMethodDecl(), Setr);
968   Setr += "{ ";
969   // Synthesize an explicit cast to initialize the ivar.
970   // See objc-act.c:objc_synthesize_new_setter() for details.
971   if (GenSetProperty) {
972     Setr += "objc_setProperty (self, _cmd, ";
973     RewriteIvarOffsetComputation(OID, Setr);
974     Setr += ", (id)";
975     Setr += PD->getName();
976     Setr += ", ";
977     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
978       Setr += "0, ";
979     else
980       Setr += "1, ";
981     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
982       Setr += "1)";
983     else
984       Setr += "0)";
985   }
986   else {
987     Setr += getIvarAccessString(OID) + " = ";
988     Setr += PD->getName();
989   }
990   Setr += "; }\n";
991   InsertText(startGetterSetterLoc, Setr);
992 }
993
994 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
995                                        std::string &typedefString) {
996   typedefString += "#ifndef _REWRITER_typedef_";
997   typedefString += ForwardDecl->getNameAsString();
998   typedefString += "\n";
999   typedefString += "#define _REWRITER_typedef_";
1000   typedefString += ForwardDecl->getNameAsString();
1001   typedefString += "\n";
1002   typedefString += "typedef struct objc_object ";
1003   typedefString += ForwardDecl->getNameAsString();
1004   // typedef struct { } _objc_exc_Classname;
1005   typedefString += ";\ntypedef struct {} _objc_exc_";
1006   typedefString += ForwardDecl->getNameAsString();
1007   typedefString += ";\n#endif\n";
1008 }
1009
1010 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1011                                               const std::string &typedefString) {
1012     SourceLocation startLoc = ClassDecl->getLocStart();
1013     const char *startBuf = SM->getCharacterData(startLoc);
1014     const char *semiPtr = strchr(startBuf, ';'); 
1015     // Replace the @class with typedefs corresponding to the classes.
1016     ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);  
1017 }
1018
1019 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1020   std::string typedefString;
1021   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1022     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1023     if (I == D.begin()) {
1024       // Translate to typedef's that forward reference structs with the same name
1025       // as the class. As a convenience, we include the original declaration
1026       // as a comment.
1027       typedefString += "// @class ";
1028       typedefString += ForwardDecl->getNameAsString();
1029       typedefString += ";\n";
1030     }
1031     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1032   }
1033   DeclGroupRef::iterator I = D.begin();
1034   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1035 }
1036
1037 void RewriteModernObjC::RewriteForwardClassDecl(
1038                                 const llvm::SmallVector<Decl*, 8> &D) {
1039   std::string typedefString;
1040   for (unsigned i = 0; i < D.size(); i++) {
1041     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1042     if (i == 0) {
1043       typedefString += "// @class ";
1044       typedefString += ForwardDecl->getNameAsString();
1045       typedefString += ";\n";
1046     }
1047     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1048   }
1049   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1050 }
1051
1052 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1053   // When method is a synthesized one, such as a getter/setter there is
1054   // nothing to rewrite.
1055   if (Method->isImplicit())
1056     return;
1057   SourceLocation LocStart = Method->getLocStart();
1058   SourceLocation LocEnd = Method->getLocEnd();
1059
1060   if (SM->getExpansionLineNumber(LocEnd) >
1061       SM->getExpansionLineNumber(LocStart)) {
1062     InsertText(LocStart, "#if 0\n");
1063     ReplaceText(LocEnd, 1, ";\n#endif\n");
1064   } else {
1065     InsertText(LocStart, "// ");
1066   }
1067 }
1068
1069 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1070   SourceLocation Loc = prop->getAtLoc();
1071
1072   ReplaceText(Loc, 0, "// ");
1073   // FIXME: handle properties that are declared across multiple lines.
1074 }
1075
1076 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1077   SourceLocation LocStart = CatDecl->getLocStart();
1078
1079   // FIXME: handle category headers that are declared across multiple lines.
1080   if (CatDecl->getIvarRBraceLoc().isValid()) {
1081     ReplaceText(LocStart, 1, "/** ");
1082     ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1083   }
1084   else {
1085     ReplaceText(LocStart, 0, "// ");
1086   }
1087   
1088   for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1089        E = CatDecl->prop_end(); I != E; ++I)
1090     RewriteProperty(*I);
1091   
1092   for (ObjCCategoryDecl::instmeth_iterator
1093          I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1094        I != E; ++I)
1095     RewriteMethodDeclaration(*I);
1096   for (ObjCCategoryDecl::classmeth_iterator
1097          I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1098        I != E; ++I)
1099     RewriteMethodDeclaration(*I);
1100
1101   // Lastly, comment out the @end.
1102   ReplaceText(CatDecl->getAtEndRange().getBegin(), 
1103               strlen("@end"), "/* @end */");
1104 }
1105
1106 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1107   SourceLocation LocStart = PDecl->getLocStart();
1108   assert(PDecl->isThisDeclarationADefinition());
1109   
1110   // FIXME: handle protocol headers that are declared across multiple lines.
1111   ReplaceText(LocStart, 0, "// ");
1112
1113   for (ObjCProtocolDecl::instmeth_iterator
1114          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1115        I != E; ++I)
1116     RewriteMethodDeclaration(*I);
1117   for (ObjCProtocolDecl::classmeth_iterator
1118          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1119        I != E; ++I)
1120     RewriteMethodDeclaration(*I);
1121
1122   for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1123        E = PDecl->prop_end(); I != E; ++I)
1124     RewriteProperty(*I);
1125   
1126   // Lastly, comment out the @end.
1127   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1128   ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1129
1130   // Must comment out @optional/@required
1131   const char *startBuf = SM->getCharacterData(LocStart);
1132   const char *endBuf = SM->getCharacterData(LocEnd);
1133   for (const char *p = startBuf; p < endBuf; p++) {
1134     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1135       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1136       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1137
1138     }
1139     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1140       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1141       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1142
1143     }
1144   }
1145 }
1146
1147 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1148   SourceLocation LocStart = (*D.begin())->getLocStart();
1149   if (LocStart.isInvalid())
1150     llvm_unreachable("Invalid SourceLocation");
1151   // FIXME: handle forward protocol that are declared across multiple lines.
1152   ReplaceText(LocStart, 0, "// ");
1153 }
1154
1155 void 
1156 RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1157   SourceLocation LocStart = DG[0]->getLocStart();
1158   if (LocStart.isInvalid())
1159     llvm_unreachable("Invalid SourceLocation");
1160   // FIXME: handle forward protocol that are declared across multiple lines.
1161   ReplaceText(LocStart, 0, "// ");
1162 }
1163
1164 void 
1165 RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1166   SourceLocation LocStart = LSD->getExternLoc();
1167   if (LocStart.isInvalid())
1168     llvm_unreachable("Invalid extern SourceLocation");
1169   
1170   ReplaceText(LocStart, 0, "// ");
1171   if (!LSD->hasBraces())
1172     return;
1173   // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1174   SourceLocation LocRBrace = LSD->getRBraceLoc();
1175   if (LocRBrace.isInvalid())
1176     llvm_unreachable("Invalid rbrace SourceLocation");
1177   ReplaceText(LocRBrace, 0, "// ");
1178 }
1179
1180 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1181                                         const FunctionType *&FPRetType) {
1182   if (T->isObjCQualifiedIdType())
1183     ResultStr += "id";
1184   else if (T->isFunctionPointerType() ||
1185            T->isBlockPointerType()) {
1186     // needs special handling, since pointer-to-functions have special
1187     // syntax (where a decaration models use).
1188     QualType retType = T;
1189     QualType PointeeTy;
1190     if (const PointerType* PT = retType->getAs<PointerType>())
1191       PointeeTy = PT->getPointeeType();
1192     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1193       PointeeTy = BPT->getPointeeType();
1194     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1195       ResultStr += FPRetType->getResultType().getAsString(
1196         Context->getPrintingPolicy());
1197       ResultStr += "(*";
1198     }
1199   } else
1200     ResultStr += T.getAsString(Context->getPrintingPolicy());
1201 }
1202
1203 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1204                                         ObjCMethodDecl *OMD,
1205                                         std::string &ResultStr) {
1206   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1207   const FunctionType *FPRetType = 0;
1208   ResultStr += "\nstatic ";
1209   RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1210   ResultStr += " ";
1211
1212   // Unique method name
1213   std::string NameStr;
1214
1215   if (OMD->isInstanceMethod())
1216     NameStr += "_I_";
1217   else
1218     NameStr += "_C_";
1219
1220   NameStr += IDecl->getNameAsString();
1221   NameStr += "_";
1222
1223   if (ObjCCategoryImplDecl *CID =
1224       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1225     NameStr += CID->getNameAsString();
1226     NameStr += "_";
1227   }
1228   // Append selector names, replacing ':' with '_'
1229   {
1230     std::string selString = OMD->getSelector().getAsString();
1231     int len = selString.size();
1232     for (int i = 0; i < len; i++)
1233       if (selString[i] == ':')
1234         selString[i] = '_';
1235     NameStr += selString;
1236   }
1237   // Remember this name for metadata emission
1238   MethodInternalNames[OMD] = NameStr;
1239   ResultStr += NameStr;
1240
1241   // Rewrite arguments
1242   ResultStr += "(";
1243
1244   // invisible arguments
1245   if (OMD->isInstanceMethod()) {
1246     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1247     selfTy = Context->getPointerType(selfTy);
1248     if (!LangOpts.MicrosoftExt) {
1249       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1250         ResultStr += "struct ";
1251     }
1252     // When rewriting for Microsoft, explicitly omit the structure name.
1253     ResultStr += IDecl->getNameAsString();
1254     ResultStr += " *";
1255   }
1256   else
1257     ResultStr += Context->getObjCClassType().getAsString(
1258       Context->getPrintingPolicy());
1259
1260   ResultStr += " self, ";
1261   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1262   ResultStr += " _cmd";
1263
1264   // Method arguments.
1265   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1266        E = OMD->param_end(); PI != E; ++PI) {
1267     ParmVarDecl *PDecl = *PI;
1268     ResultStr += ", ";
1269     if (PDecl->getType()->isObjCQualifiedIdType()) {
1270       ResultStr += "id ";
1271       ResultStr += PDecl->getNameAsString();
1272     } else {
1273       std::string Name = PDecl->getNameAsString();
1274       QualType QT = PDecl->getType();
1275       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1276       (void)convertBlockPointerToFunctionPointer(QT);
1277       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1278       ResultStr += Name;
1279     }
1280   }
1281   if (OMD->isVariadic())
1282     ResultStr += ", ...";
1283   ResultStr += ") ";
1284
1285   if (FPRetType) {
1286     ResultStr += ")"; // close the precedence "scope" for "*".
1287
1288     // Now, emit the argument types (if any).
1289     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1290       ResultStr += "(";
1291       for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1292         if (i) ResultStr += ", ";
1293         std::string ParamStr = FT->getArgType(i).getAsString(
1294           Context->getPrintingPolicy());
1295         ResultStr += ParamStr;
1296       }
1297       if (FT->isVariadic()) {
1298         if (FT->getNumArgs()) ResultStr += ", ";
1299         ResultStr += "...";
1300       }
1301       ResultStr += ")";
1302     } else {
1303       ResultStr += "()";
1304     }
1305   }
1306 }
1307 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1308   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1309   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1310
1311   if (IMD) {
1312     if (IMD->getIvarRBraceLoc().isValid()) {
1313       ReplaceText(IMD->getLocStart(), 1, "/** ");
1314       ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1315     }
1316     else {
1317       InsertText(IMD->getLocStart(), "// ");
1318     }
1319   }
1320   else
1321     InsertText(CID->getLocStart(), "// ");
1322
1323   for (ObjCCategoryImplDecl::instmeth_iterator
1324        I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1325        E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1326        I != E; ++I) {
1327     std::string ResultStr;
1328     ObjCMethodDecl *OMD = *I;
1329     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1330     SourceLocation LocStart = OMD->getLocStart();
1331     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1332
1333     const char *startBuf = SM->getCharacterData(LocStart);
1334     const char *endBuf = SM->getCharacterData(LocEnd);
1335     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1336   }
1337
1338   for (ObjCCategoryImplDecl::classmeth_iterator
1339        I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1340        E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1341        I != E; ++I) {
1342     std::string ResultStr;
1343     ObjCMethodDecl *OMD = *I;
1344     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1345     SourceLocation LocStart = OMD->getLocStart();
1346     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1347
1348     const char *startBuf = SM->getCharacterData(LocStart);
1349     const char *endBuf = SM->getCharacterData(LocEnd);
1350     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1351   }
1352   for (ObjCCategoryImplDecl::propimpl_iterator
1353        I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1354        E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1355        I != E; ++I) {
1356     RewritePropertyImplDecl(*I, IMD, CID);
1357   }
1358
1359   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1360 }
1361
1362 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1363   // Do not synthesize more than once.
1364   if (ObjCSynthesizedStructs.count(ClassDecl))
1365     return;
1366   // Make sure super class's are written before current class is written.
1367   ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1368   while (SuperClass) {
1369     RewriteInterfaceDecl(SuperClass);
1370     SuperClass = SuperClass->getSuperClass();
1371   }
1372   std::string ResultStr;
1373   if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1374     // we haven't seen a forward decl - generate a typedef.
1375     RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1376     RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1377     
1378     RewriteObjCInternalStruct(ClassDecl, ResultStr);
1379     // Mark this typedef as having been written into its c++ equivalent.
1380     ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1381   
1382     for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1383          E = ClassDecl->prop_end(); I != E; ++I)
1384       RewriteProperty(*I);
1385     for (ObjCInterfaceDecl::instmeth_iterator
1386          I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1387          I != E; ++I)
1388       RewriteMethodDeclaration(*I);
1389     for (ObjCInterfaceDecl::classmeth_iterator
1390          I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1391          I != E; ++I)
1392       RewriteMethodDeclaration(*I);
1393
1394     // Lastly, comment out the @end.
1395     ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), 
1396                 "/* @end */");
1397   }
1398 }
1399
1400 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1401   SourceRange OldRange = PseudoOp->getSourceRange();
1402
1403   // We just magically know some things about the structure of this
1404   // expression.
1405   ObjCMessageExpr *OldMsg =
1406     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1407                             PseudoOp->getNumSemanticExprs() - 1));
1408
1409   // Because the rewriter doesn't allow us to rewrite rewritten code,
1410   // we need to suppress rewriting the sub-statements.
1411   Expr *Base;
1412   SmallVector<Expr*, 2> Args;
1413   {
1414     DisableReplaceStmtScope S(*this);
1415
1416     // Rebuild the base expression if we have one.
1417     Base = 0;
1418     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1419       Base = OldMsg->getInstanceReceiver();
1420       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1421       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1422     }
1423   
1424     unsigned numArgs = OldMsg->getNumArgs();
1425     for (unsigned i = 0; i < numArgs; i++) {
1426       Expr *Arg = OldMsg->getArg(i);
1427       if (isa<OpaqueValueExpr>(Arg))
1428         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1429       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1430       Args.push_back(Arg);
1431     }
1432   }
1433
1434   // TODO: avoid this copy.
1435   SmallVector<SourceLocation, 1> SelLocs;
1436   OldMsg->getSelectorLocs(SelLocs);
1437
1438   ObjCMessageExpr *NewMsg = 0;
1439   switch (OldMsg->getReceiverKind()) {
1440   case ObjCMessageExpr::Class:
1441     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1442                                      OldMsg->getValueKind(),
1443                                      OldMsg->getLeftLoc(),
1444                                      OldMsg->getClassReceiverTypeInfo(),
1445                                      OldMsg->getSelector(),
1446                                      SelLocs,
1447                                      OldMsg->getMethodDecl(),
1448                                      Args,
1449                                      OldMsg->getRightLoc(),
1450                                      OldMsg->isImplicit());
1451     break;
1452
1453   case ObjCMessageExpr::Instance:
1454     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455                                      OldMsg->getValueKind(),
1456                                      OldMsg->getLeftLoc(),
1457                                      Base,
1458                                      OldMsg->getSelector(),
1459                                      SelLocs,
1460                                      OldMsg->getMethodDecl(),
1461                                      Args,
1462                                      OldMsg->getRightLoc(),
1463                                      OldMsg->isImplicit());
1464     break;
1465
1466   case ObjCMessageExpr::SuperClass:
1467   case ObjCMessageExpr::SuperInstance:
1468     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1469                                      OldMsg->getValueKind(),
1470                                      OldMsg->getLeftLoc(),
1471                                      OldMsg->getSuperLoc(),
1472                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1473                                      OldMsg->getSuperType(),
1474                                      OldMsg->getSelector(),
1475                                      SelLocs,
1476                                      OldMsg->getMethodDecl(),
1477                                      Args,
1478                                      OldMsg->getRightLoc(),
1479                                      OldMsg->isImplicit());
1480     break;
1481   }
1482
1483   Stmt *Replacement = SynthMessageExpr(NewMsg);
1484   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1485   return Replacement;
1486 }
1487
1488 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1489   SourceRange OldRange = PseudoOp->getSourceRange();
1490
1491   // We just magically know some things about the structure of this
1492   // expression.
1493   ObjCMessageExpr *OldMsg =
1494     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1495
1496   // Because the rewriter doesn't allow us to rewrite rewritten code,
1497   // we need to suppress rewriting the sub-statements.
1498   Expr *Base = 0;
1499   SmallVector<Expr*, 1> Args;
1500   {
1501     DisableReplaceStmtScope S(*this);
1502     // Rebuild the base expression if we have one.
1503     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1504       Base = OldMsg->getInstanceReceiver();
1505       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1506       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1507     }
1508     unsigned numArgs = OldMsg->getNumArgs();
1509     for (unsigned i = 0; i < numArgs; i++) {
1510       Expr *Arg = OldMsg->getArg(i);
1511       if (isa<OpaqueValueExpr>(Arg))
1512         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1513       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1514       Args.push_back(Arg);
1515     }
1516   }
1517
1518   // Intentionally empty.
1519   SmallVector<SourceLocation, 1> SelLocs;
1520
1521   ObjCMessageExpr *NewMsg = 0;
1522   switch (OldMsg->getReceiverKind()) {
1523   case ObjCMessageExpr::Class:
1524     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1525                                      OldMsg->getValueKind(),
1526                                      OldMsg->getLeftLoc(),
1527                                      OldMsg->getClassReceiverTypeInfo(),
1528                                      OldMsg->getSelector(),
1529                                      SelLocs,
1530                                      OldMsg->getMethodDecl(),
1531                                      Args,
1532                                      OldMsg->getRightLoc(),
1533                                      OldMsg->isImplicit());
1534     break;
1535
1536   case ObjCMessageExpr::Instance:
1537     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1538                                      OldMsg->getValueKind(),
1539                                      OldMsg->getLeftLoc(),
1540                                      Base,
1541                                      OldMsg->getSelector(),
1542                                      SelLocs,
1543                                      OldMsg->getMethodDecl(),
1544                                      Args,
1545                                      OldMsg->getRightLoc(),
1546                                      OldMsg->isImplicit());
1547     break;
1548
1549   case ObjCMessageExpr::SuperClass:
1550   case ObjCMessageExpr::SuperInstance:
1551     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1552                                      OldMsg->getValueKind(),
1553                                      OldMsg->getLeftLoc(),
1554                                      OldMsg->getSuperLoc(),
1555                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1556                                      OldMsg->getSuperType(),
1557                                      OldMsg->getSelector(),
1558                                      SelLocs,
1559                                      OldMsg->getMethodDecl(),
1560                                      Args,
1561                                      OldMsg->getRightLoc(),
1562                                      OldMsg->isImplicit());
1563     break;
1564   }
1565
1566   Stmt *Replacement = SynthMessageExpr(NewMsg);
1567   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1568   return Replacement;
1569 }
1570
1571 /// SynthCountByEnumWithState - To print:
1572 /// ((unsigned int (*)
1573 ///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1574 ///  (void *)objc_msgSend)((id)l_collection,
1575 ///                        sel_registerName(
1576 ///                          "countByEnumeratingWithState:objects:count:"),
1577 ///                        &enumState,
1578 ///                        (id *)__rw_items, (unsigned int)16)
1579 ///
1580 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1581   buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1582   "id *, unsigned int))(void *)objc_msgSend)";
1583   buf += "\n\t\t";
1584   buf += "((id)l_collection,\n\t\t";
1585   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1586   buf += "\n\t\t";
1587   buf += "&enumState, "
1588          "(id *)__rw_items, (unsigned int)16)";
1589 }
1590
1591 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1592 /// statement to exit to its outer synthesized loop.
1593 ///
1594 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1595   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1596     return S;
1597   // replace break with goto __break_label
1598   std::string buf;
1599
1600   SourceLocation startLoc = S->getLocStart();
1601   buf = "goto __break_label_";
1602   buf += utostr(ObjCBcLabelNo.back());
1603   ReplaceText(startLoc, strlen("break"), buf);
1604
1605   return 0;
1606 }
1607
1608 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1609                                           SourceLocation Loc,
1610                                           std::string &LineString) {
1611   if (Loc.isFileID()) {
1612     LineString += "\n#line ";
1613     PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1614     LineString += utostr(PLoc.getLine());
1615     LineString += " \"";
1616     LineString += Lexer::Stringify(PLoc.getFilename());
1617     LineString += "\"\n";
1618   }
1619 }
1620
1621 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1622 /// statement to continue with its inner synthesized loop.
1623 ///
1624 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1625   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1626     return S;
1627   // replace continue with goto __continue_label
1628   std::string buf;
1629
1630   SourceLocation startLoc = S->getLocStart();
1631   buf = "goto __continue_label_";
1632   buf += utostr(ObjCBcLabelNo.back());
1633   ReplaceText(startLoc, strlen("continue"), buf);
1634
1635   return 0;
1636 }
1637
1638 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1639 ///  It rewrites:
1640 /// for ( type elem in collection) { stmts; }
1641
1642 /// Into:
1643 /// {
1644 ///   type elem;
1645 ///   struct __objcFastEnumerationState enumState = { 0 };
1646 ///   id __rw_items[16];
1647 ///   id l_collection = (id)collection;
1648 ///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1649 ///                                       objects:__rw_items count:16];
1650 /// if (limit) {
1651 ///   unsigned long startMutations = *enumState.mutationsPtr;
1652 ///   do {
1653 ///        unsigned long counter = 0;
1654 ///        do {
1655 ///             if (startMutations != *enumState.mutationsPtr)
1656 ///               objc_enumerationMutation(l_collection);
1657 ///             elem = (type)enumState.itemsPtr[counter++];
1658 ///             stmts;
1659 ///             __continue_label: ;
1660 ///        } while (counter < limit);
1661 ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1662 ///                                  objects:__rw_items count:16]);
1663 ///   elem = nil;
1664 ///   __break_label: ;
1665 ///  }
1666 ///  else
1667 ///       elem = nil;
1668 ///  }
1669 ///
1670 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1671                                                 SourceLocation OrigEnd) {
1672   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1673   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1674          "ObjCForCollectionStmt Statement stack mismatch");
1675   assert(!ObjCBcLabelNo.empty() &&
1676          "ObjCForCollectionStmt - Label No stack empty");
1677
1678   SourceLocation startLoc = S->getLocStart();
1679   const char *startBuf = SM->getCharacterData(startLoc);
1680   StringRef elementName;
1681   std::string elementTypeAsString;
1682   std::string buf;
1683   // line directive first.
1684   SourceLocation ForEachLoc = S->getForLoc();
1685   ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1686   buf += "{\n\t";
1687   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1688     // type elem;
1689     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1690     QualType ElementType = cast<ValueDecl>(D)->getType();
1691     if (ElementType->isObjCQualifiedIdType() ||
1692         ElementType->isObjCQualifiedInterfaceType())
1693       // Simply use 'id' for all qualified types.
1694       elementTypeAsString = "id";
1695     else
1696       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1697     buf += elementTypeAsString;
1698     buf += " ";
1699     elementName = D->getName();
1700     buf += elementName;
1701     buf += ";\n\t";
1702   }
1703   else {
1704     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1705     elementName = DR->getDecl()->getName();
1706     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1707     if (VD->getType()->isObjCQualifiedIdType() ||
1708         VD->getType()->isObjCQualifiedInterfaceType())
1709       // Simply use 'id' for all qualified types.
1710       elementTypeAsString = "id";
1711     else
1712       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1713   }
1714
1715   // struct __objcFastEnumerationState enumState = { 0 };
1716   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1717   // id __rw_items[16];
1718   buf += "id __rw_items[16];\n\t";
1719   // id l_collection = (id)
1720   buf += "id l_collection = (id)";
1721   // Find start location of 'collection' the hard way!
1722   const char *startCollectionBuf = startBuf;
1723   startCollectionBuf += 3;  // skip 'for'
1724   startCollectionBuf = strchr(startCollectionBuf, '(');
1725   startCollectionBuf++; // skip '('
1726   // find 'in' and skip it.
1727   while (*startCollectionBuf != ' ' ||
1728          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1729          (*(startCollectionBuf+3) != ' ' &&
1730           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1731     startCollectionBuf++;
1732   startCollectionBuf += 3;
1733
1734   // Replace: "for (type element in" with string constructed thus far.
1735   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1736   // Replace ')' in for '(' type elem in collection ')' with ';'
1737   SourceLocation rightParenLoc = S->getRParenLoc();
1738   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1739   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1740   buf = ";\n\t";
1741
1742   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1743   //                                   objects:__rw_items count:16];
1744   // which is synthesized into:
1745   // unsigned int limit =
1746   // ((unsigned int (*)
1747   //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1748   //  (void *)objc_msgSend)((id)l_collection,
1749   //                        sel_registerName(
1750   //                          "countByEnumeratingWithState:objects:count:"),
1751   //                        (struct __objcFastEnumerationState *)&state,
1752   //                        (id *)__rw_items, (unsigned int)16);
1753   buf += "unsigned long limit =\n\t\t";
1754   SynthCountByEnumWithState(buf);
1755   buf += ";\n\t";
1756   /// if (limit) {
1757   ///   unsigned long startMutations = *enumState.mutationsPtr;
1758   ///   do {
1759   ///        unsigned long counter = 0;
1760   ///        do {
1761   ///             if (startMutations != *enumState.mutationsPtr)
1762   ///               objc_enumerationMutation(l_collection);
1763   ///             elem = (type)enumState.itemsPtr[counter++];
1764   buf += "if (limit) {\n\t";
1765   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1766   buf += "do {\n\t\t";
1767   buf += "unsigned long counter = 0;\n\t\t";
1768   buf += "do {\n\t\t\t";
1769   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1770   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1771   buf += elementName;
1772   buf += " = (";
1773   buf += elementTypeAsString;
1774   buf += ")enumState.itemsPtr[counter++];";
1775   // Replace ')' in for '(' type elem in collection ')' with all of these.
1776   ReplaceText(lparenLoc, 1, buf);
1777
1778   ///            __continue_label: ;
1779   ///        } while (counter < limit);
1780   ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1781   ///                                  objects:__rw_items count:16]);
1782   ///   elem = nil;
1783   ///   __break_label: ;
1784   ///  }
1785   ///  else
1786   ///       elem = nil;
1787   ///  }
1788   ///
1789   buf = ";\n\t";
1790   buf += "__continue_label_";
1791   buf += utostr(ObjCBcLabelNo.back());
1792   buf += ": ;";
1793   buf += "\n\t\t";
1794   buf += "} while (counter < limit);\n\t";
1795   buf += "} while (limit = ";
1796   SynthCountByEnumWithState(buf);
1797   buf += ");\n\t";
1798   buf += elementName;
1799   buf += " = ((";
1800   buf += elementTypeAsString;
1801   buf += ")0);\n\t";
1802   buf += "__break_label_";
1803   buf += utostr(ObjCBcLabelNo.back());
1804   buf += ": ;\n\t";
1805   buf += "}\n\t";
1806   buf += "else\n\t\t";
1807   buf += elementName;
1808   buf += " = ((";
1809   buf += elementTypeAsString;
1810   buf += ")0);\n\t";
1811   buf += "}\n";
1812
1813   // Insert all these *after* the statement body.
1814   // FIXME: If this should support Obj-C++, support CXXTryStmt
1815   if (isa<CompoundStmt>(S->getBody())) {
1816     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1817     InsertText(endBodyLoc, buf);
1818   } else {
1819     /* Need to treat single statements specially. For example:
1820      *
1821      *     for (A *a in b) if (stuff()) break;
1822      *     for (A *a in b) xxxyy;
1823      *
1824      * The following code simply scans ahead to the semi to find the actual end.
1825      */
1826     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1827     const char *semiBuf = strchr(stmtBuf, ';');
1828     assert(semiBuf && "Can't find ';'");
1829     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1830     InsertText(endBodyLoc, buf);
1831   }
1832   Stmts.pop_back();
1833   ObjCBcLabelNo.pop_back();
1834   return 0;
1835 }
1836
1837 static void Write_RethrowObject(std::string &buf) {
1838   buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1839   buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1840   buf += "\tid rethrow;\n";
1841   buf += "\t} _fin_force_rethow(_rethrow);";
1842 }
1843
1844 /// RewriteObjCSynchronizedStmt -
1845 /// This routine rewrites @synchronized(expr) stmt;
1846 /// into:
1847 /// objc_sync_enter(expr);
1848 /// @try stmt @finally { objc_sync_exit(expr); }
1849 ///
1850 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1851   // Get the start location and compute the semi location.
1852   SourceLocation startLoc = S->getLocStart();
1853   const char *startBuf = SM->getCharacterData(startLoc);
1854
1855   assert((*startBuf == '@') && "bogus @synchronized location");
1856
1857   std::string buf;
1858   SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1859   ConvertSourceLocationToLineDirective(SynchLoc, buf);
1860   buf += "{ id _rethrow = 0; id _sync_obj = ";
1861   
1862   const char *lparenBuf = startBuf;
1863   while (*lparenBuf != '(') lparenBuf++;
1864   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1865   
1866   buf = "; objc_sync_enter(_sync_obj);\n";
1867   buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1868   buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1869   buf += "\n\tid sync_exit;";
1870   buf += "\n\t} _sync_exit(_sync_obj);\n";
1871
1872   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1873   // the sync expression is typically a message expression that's already
1874   // been rewritten! (which implies the SourceLocation's are invalid).
1875   SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1876   const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1877   while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1878   RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1879   
1880   SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1881   const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1882   assert (*LBraceLocBuf == '{');
1883   ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1884   
1885   SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1886   assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1887          "bogus @synchronized block");
1888   
1889   buf = "} catch (id e) {_rethrow = e;}\n";
1890   Write_RethrowObject(buf);
1891   buf += "}\n";
1892   buf += "}\n";
1893
1894   ReplaceText(startRBraceLoc, 1, buf);
1895
1896   return 0;
1897 }
1898
1899 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1900 {
1901   // Perform a bottom up traversal of all children.
1902   for (Stmt::child_range CI = S->children(); CI; ++CI)
1903     if (*CI)
1904       WarnAboutReturnGotoStmts(*CI);
1905
1906   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1907     Diags.Report(Context->getFullLoc(S->getLocStart()),
1908                  TryFinallyContainsReturnDiag);
1909   }
1910   return;
1911 }
1912
1913 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1914   SourceLocation startLoc = S->getAtLoc();
1915   ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1916   ReplaceText(S->getSubStmt()->getLocStart(), 1, 
1917               "{ __AtAutoreleasePool __autoreleasepool; ");
1918   
1919   return 0;
1920 }
1921
1922 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1923   ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1924   bool noCatch = S->getNumCatchStmts() == 0;
1925   std::string buf;
1926   SourceLocation TryLocation = S->getAtTryLoc();
1927   ConvertSourceLocationToLineDirective(TryLocation, buf);
1928   
1929   if (finalStmt) {
1930     if (noCatch)
1931       buf += "{ id volatile _rethrow = 0;\n";
1932     else {
1933       buf += "{ id volatile _rethrow = 0;\ntry {\n";
1934     }
1935   }
1936   // Get the start location and compute the semi location.
1937   SourceLocation startLoc = S->getLocStart();
1938   const char *startBuf = SM->getCharacterData(startLoc);
1939
1940   assert((*startBuf == '@') && "bogus @try location");
1941   if (finalStmt)
1942     ReplaceText(startLoc, 1, buf);
1943   else
1944     // @try -> try
1945     ReplaceText(startLoc, 1, "");
1946   
1947   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1948     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1949     VarDecl *catchDecl = Catch->getCatchParamDecl();
1950     
1951     startLoc = Catch->getLocStart();
1952     bool AtRemoved = false;
1953     if (catchDecl) {
1954       QualType t = catchDecl->getType();
1955       if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1956         // Should be a pointer to a class.
1957         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1958         if (IDecl) {
1959           std::string Result;
1960           ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1961           
1962           startBuf = SM->getCharacterData(startLoc);
1963           assert((*startBuf == '@') && "bogus @catch location");
1964           SourceLocation rParenLoc = Catch->getRParenLoc();
1965           const char *rParenBuf = SM->getCharacterData(rParenLoc);
1966           
1967           // _objc_exc_Foo *_e as argument to catch.
1968           Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1969           Result += " *_"; Result += catchDecl->getNameAsString();
1970           Result += ")";
1971           ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1972           // Foo *e = (Foo *)_e;
1973           Result.clear();
1974           Result = "{ ";
1975           Result += IDecl->getNameAsString();
1976           Result += " *"; Result += catchDecl->getNameAsString();
1977           Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1978           Result += "_"; Result += catchDecl->getNameAsString();
1979           
1980           Result += "; ";
1981           SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1982           ReplaceText(lBraceLoc, 1, Result);
1983           AtRemoved = true;
1984         }
1985       }
1986     }
1987     if (!AtRemoved)
1988       // @catch -> catch
1989       ReplaceText(startLoc, 1, "");
1990       
1991   }
1992   if (finalStmt) {
1993     buf.clear();
1994     SourceLocation FinallyLoc = finalStmt->getLocStart();
1995     
1996     if (noCatch) {
1997       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
1998       buf += "catch (id e) {_rethrow = e;}\n";
1999     }
2000     else {
2001       buf += "}\n";
2002       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2003       buf += "catch (id e) {_rethrow = e;}\n";
2004     }
2005     
2006     SourceLocation startFinalLoc = finalStmt->getLocStart();
2007     ReplaceText(startFinalLoc, 8, buf);
2008     Stmt *body = finalStmt->getFinallyBody();
2009     SourceLocation startFinalBodyLoc = body->getLocStart();
2010     buf.clear();
2011     Write_RethrowObject(buf);
2012     ReplaceText(startFinalBodyLoc, 1, buf);
2013     
2014     SourceLocation endFinalBodyLoc = body->getLocEnd();
2015     ReplaceText(endFinalBodyLoc, 1, "}\n}");
2016     // Now check for any return/continue/go statements within the @try.
2017     WarnAboutReturnGotoStmts(S->getTryBody());
2018   }
2019
2020   return 0;
2021 }
2022
2023 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2024 // the throw expression is typically a message expression that's already
2025 // been rewritten! (which implies the SourceLocation's are invalid).
2026 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2027   // Get the start location and compute the semi location.
2028   SourceLocation startLoc = S->getLocStart();
2029   const char *startBuf = SM->getCharacterData(startLoc);
2030
2031   assert((*startBuf == '@') && "bogus @throw location");
2032
2033   std::string buf;
2034   /* void objc_exception_throw(id) __attribute__((noreturn)); */
2035   if (S->getThrowExpr())
2036     buf = "objc_exception_throw(";
2037   else
2038     buf = "throw";
2039
2040   // handle "@  throw" correctly.
2041   const char *wBuf = strchr(startBuf, 'w');
2042   assert((*wBuf == 'w') && "@throw: can't find 'w'");
2043   ReplaceText(startLoc, wBuf-startBuf+1, buf);
2044
2045   const char *semiBuf = strchr(startBuf, ';');
2046   assert((*semiBuf == ';') && "@throw: can't find ';'");
2047   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2048   if (S->getThrowExpr())
2049     ReplaceText(semiLoc, 1, ");");
2050   return 0;
2051 }
2052
2053 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2054   // Create a new string expression.
2055   QualType StrType = Context->getPointerType(Context->CharTy);
2056   std::string StrEncoding;
2057   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2058   Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2059                                             StringLiteral::Ascii, false,
2060                                             StrType, SourceLocation());
2061   ReplaceStmt(Exp, Replacement);
2062
2063   // Replace this subexpr in the parent.
2064   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2065   return Replacement;
2066 }
2067
2068 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2069   if (!SelGetUidFunctionDecl)
2070     SynthSelGetUidFunctionDecl();
2071   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2072   // Create a call to sel_registerName("selName").
2073   SmallVector<Expr*, 8> SelExprs;
2074   QualType argType = Context->getPointerType(Context->CharTy);
2075   SelExprs.push_back(StringLiteral::Create(*Context,
2076                                            Exp->getSelector().getAsString(),
2077                                            StringLiteral::Ascii, false,
2078                                            argType, SourceLocation()));
2079   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2080                                                  &SelExprs[0], SelExprs.size());
2081   ReplaceStmt(Exp, SelExp);
2082   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2083   return SelExp;
2084 }
2085
2086 CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2087   FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2088                                                     SourceLocation EndLoc) {
2089   // Get the type, we will need to reference it in a couple spots.
2090   QualType msgSendType = FD->getType();
2091
2092   // Create a reference to the objc_msgSend() declaration.
2093   DeclRefExpr *DRE =
2094     new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2095
2096   // Now, we cast the reference to a pointer to the objc_msgSend type.
2097   QualType pToFunc = Context->getPointerType(msgSendType);
2098   ImplicitCastExpr *ICE = 
2099     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2100                              DRE, 0, VK_RValue);
2101
2102   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2103
2104   CallExpr *Exp =  
2105     new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
2106                            FT->getCallResultType(*Context),
2107                            VK_RValue, EndLoc);
2108   return Exp;
2109 }
2110
2111 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2112                                 const char *&startRef, const char *&endRef) {
2113   while (startBuf < endBuf) {
2114     if (*startBuf == '<')
2115       startRef = startBuf; // mark the start.
2116     if (*startBuf == '>') {
2117       if (startRef && *startRef == '<') {
2118         endRef = startBuf; // mark the end.
2119         return true;
2120       }
2121       return false;
2122     }
2123     startBuf++;
2124   }
2125   return false;
2126 }
2127
2128 static void scanToNextArgument(const char *&argRef) {
2129   int angle = 0;
2130   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2131     if (*argRef == '<')
2132       angle++;
2133     else if (*argRef == '>')
2134       angle--;
2135     argRef++;
2136   }
2137   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2138 }
2139
2140 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2141   if (T->isObjCQualifiedIdType())
2142     return true;
2143   if (const PointerType *PT = T->getAs<PointerType>()) {
2144     if (PT->getPointeeType()->isObjCQualifiedIdType())
2145       return true;
2146   }
2147   if (T->isObjCObjectPointerType()) {
2148     T = T->getPointeeType();
2149     return T->isObjCQualifiedInterfaceType();
2150   }
2151   if (T->isArrayType()) {
2152     QualType ElemTy = Context->getBaseElementType(T);
2153     return needToScanForQualifiers(ElemTy);
2154   }
2155   return false;
2156 }
2157
2158 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2159   QualType Type = E->getType();
2160   if (needToScanForQualifiers(Type)) {
2161     SourceLocation Loc, EndLoc;
2162
2163     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2164       Loc = ECE->getLParenLoc();
2165       EndLoc = ECE->getRParenLoc();
2166     } else {
2167       Loc = E->getLocStart();
2168       EndLoc = E->getLocEnd();
2169     }
2170     // This will defend against trying to rewrite synthesized expressions.
2171     if (Loc.isInvalid() || EndLoc.isInvalid())
2172       return;
2173
2174     const char *startBuf = SM->getCharacterData(Loc);
2175     const char *endBuf = SM->getCharacterData(EndLoc);
2176     const char *startRef = 0, *endRef = 0;
2177     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178       // Get the locations of the startRef, endRef.
2179       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2180       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2181       // Comment out the protocol references.
2182       InsertText(LessLoc, "/*");
2183       InsertText(GreaterLoc, "*/");
2184     }
2185   }
2186 }
2187
2188 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2189   SourceLocation Loc;
2190   QualType Type;
2191   const FunctionProtoType *proto = 0;
2192   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2193     Loc = VD->getLocation();
2194     Type = VD->getType();
2195   }
2196   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2197     Loc = FD->getLocation();
2198     // Check for ObjC 'id' and class types that have been adorned with protocol
2199     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2200     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2201     assert(funcType && "missing function type");
2202     proto = dyn_cast<FunctionProtoType>(funcType);
2203     if (!proto)
2204       return;
2205     Type = proto->getResultType();
2206   }
2207   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2208     Loc = FD->getLocation();
2209     Type = FD->getType();
2210   }
2211   else
2212     return;
2213
2214   if (needToScanForQualifiers(Type)) {
2215     // Since types are unique, we need to scan the buffer.
2216
2217     const char *endBuf = SM->getCharacterData(Loc);
2218     const char *startBuf = endBuf;
2219     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2220       startBuf--; // scan backward (from the decl location) for return type.
2221     const char *startRef = 0, *endRef = 0;
2222     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2223       // Get the locations of the startRef, endRef.
2224       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2225       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2226       // Comment out the protocol references.
2227       InsertText(LessLoc, "/*");
2228       InsertText(GreaterLoc, "*/");
2229     }
2230   }
2231   if (!proto)
2232       return; // most likely, was a variable
2233   // Now check arguments.
2234   const char *startBuf = SM->getCharacterData(Loc);
2235   const char *startFuncBuf = startBuf;
2236   for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2237     if (needToScanForQualifiers(proto->getArgType(i))) {
2238       // Since types are unique, we need to scan the buffer.
2239
2240       const char *endBuf = startBuf;
2241       // scan forward (from the decl location) for argument types.
2242       scanToNextArgument(endBuf);
2243       const char *startRef = 0, *endRef = 0;
2244       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2245         // Get the locations of the startRef, endRef.
2246         SourceLocation LessLoc =
2247           Loc.getLocWithOffset(startRef-startFuncBuf);
2248         SourceLocation GreaterLoc =
2249           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2250         // Comment out the protocol references.
2251         InsertText(LessLoc, "/*");
2252         InsertText(GreaterLoc, "*/");
2253       }
2254       startBuf = ++endBuf;
2255     }
2256     else {
2257       // If the function name is derived from a macro expansion, then the
2258       // argument buffer will not follow the name. Need to speak with Chris.
2259       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2260         startBuf++; // scan forward (from the decl location) for argument types.
2261       startBuf++;
2262     }
2263   }
2264 }
2265
2266 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2267   QualType QT = ND->getType();
2268   const Type* TypePtr = QT->getAs<Type>();
2269   if (!isa<TypeOfExprType>(TypePtr))
2270     return;
2271   while (isa<TypeOfExprType>(TypePtr)) {
2272     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2273     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2274     TypePtr = QT->getAs<Type>();
2275   }
2276   // FIXME. This will not work for multiple declarators; as in:
2277   // __typeof__(a) b,c,d;
2278   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2279   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2280   const char *startBuf = SM->getCharacterData(DeclLoc);
2281   if (ND->getInit()) {
2282     std::string Name(ND->getNameAsString());
2283     TypeAsString += " " + Name + " = ";
2284     Expr *E = ND->getInit();
2285     SourceLocation startLoc;
2286     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2287       startLoc = ECE->getLParenLoc();
2288     else
2289       startLoc = E->getLocStart();
2290     startLoc = SM->getExpansionLoc(startLoc);
2291     const char *endBuf = SM->getCharacterData(startLoc);
2292     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2293   }
2294   else {
2295     SourceLocation X = ND->getLocEnd();
2296     X = SM->getExpansionLoc(X);
2297     const char *endBuf = SM->getCharacterData(X);
2298     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2299   }
2300 }
2301
2302 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2303 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2304   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2305   SmallVector<QualType, 16> ArgTys;
2306   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2307   QualType getFuncType =
2308     getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2309   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2310                                            SourceLocation(),
2311                                            SourceLocation(),
2312                                            SelGetUidIdent, getFuncType, 0,
2313                                            SC_Extern,
2314                                            SC_None, false);
2315 }
2316
2317 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2318   // declared in <objc/objc.h>
2319   if (FD->getIdentifier() &&
2320       FD->getName() == "sel_registerName") {
2321     SelGetUidFunctionDecl = FD;
2322     return;
2323   }
2324   RewriteObjCQualifiedInterfaceTypes(FD);
2325 }
2326
2327 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2328   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2329   const char *argPtr = TypeString.c_str();
2330   if (!strchr(argPtr, '^')) {
2331     Str += TypeString;
2332     return;
2333   }
2334   while (*argPtr) {
2335     Str += (*argPtr == '^' ? '*' : *argPtr);
2336     argPtr++;
2337   }
2338 }
2339
2340 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2341 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2342                                                   ValueDecl *VD) {
2343   QualType Type = VD->getType();
2344   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2345   const char *argPtr = TypeString.c_str();
2346   int paren = 0;
2347   while (*argPtr) {
2348     switch (*argPtr) {
2349       case '(':
2350         Str += *argPtr;
2351         paren++;
2352         break;
2353       case ')':
2354         Str += *argPtr;
2355         paren--;
2356         break;
2357       case '^':
2358         Str += '*';
2359         if (paren == 1)
2360           Str += VD->getNameAsString();
2361         break;
2362       default:
2363         Str += *argPtr;
2364         break;
2365     }
2366     argPtr++;
2367   }
2368 }
2369
2370 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2371   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2372   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2373   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2374   if (!proto)
2375     return;
2376   QualType Type = proto->getResultType();
2377   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2378   FdStr += " ";
2379   FdStr += FD->getName();
2380   FdStr +=  "(";
2381   unsigned numArgs = proto->getNumArgs();
2382   for (unsigned i = 0; i < numArgs; i++) {
2383   QualType ArgType = proto->getArgType(i);
2384   RewriteBlockPointerType(FdStr, ArgType);
2385   if (i+1 < numArgs)
2386     FdStr += ", ";
2387   }
2388   if (FD->isVariadic()) {
2389     FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
2390   }
2391   else
2392     FdStr +=  ");\n";
2393   InsertText(FunLocStart, FdStr);
2394 }
2395
2396 // SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
2397 void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2398   if (SuperContructorFunctionDecl)
2399     return;
2400   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2401   SmallVector<QualType, 16> ArgTys;
2402   QualType argT = Context->getObjCIdType();
2403   assert(!argT.isNull() && "Can't find 'id' type");
2404   ArgTys.push_back(argT);
2405   ArgTys.push_back(argT);
2406   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2407                                                &ArgTys[0], ArgTys.size());
2408   SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2409                                          SourceLocation(),
2410                                          SourceLocation(),
2411                                          msgSendIdent, msgSendType, 0,
2412                                          SC_Extern,
2413                                          SC_None, false);
2414 }
2415
2416 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2417 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2418   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2419   SmallVector<QualType, 16> ArgTys;
2420   QualType argT = Context->getObjCIdType();
2421   assert(!argT.isNull() && "Can't find 'id' type");
2422   ArgTys.push_back(argT);
2423   argT = Context->getObjCSelType();
2424   assert(!argT.isNull() && "Can't find 'SEL' type");
2425   ArgTys.push_back(argT);
2426   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2427                                                &ArgTys[0], ArgTys.size(),
2428                                                true /*isVariadic*/);
2429   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430                                          SourceLocation(),
2431                                          SourceLocation(),
2432                                          msgSendIdent, msgSendType, 0,
2433                                          SC_Extern,
2434                                          SC_None, false);
2435 }
2436
2437 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2438 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2439   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2440   SmallVector<QualType, 2> ArgTys;
2441   ArgTys.push_back(Context->VoidTy);
2442   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2443                                                &ArgTys[0], 1,
2444                                                true /*isVariadic*/);
2445   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446                                               SourceLocation(),
2447                                               SourceLocation(),
2448                                               msgSendIdent, msgSendType, 0,
2449                                               SC_Extern,
2450                                               SC_None, false);
2451 }
2452
2453 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2454 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2455   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2456   SmallVector<QualType, 16> ArgTys;
2457   QualType argT = Context->getObjCIdType();
2458   assert(!argT.isNull() && "Can't find 'id' type");
2459   ArgTys.push_back(argT);
2460   argT = Context->getObjCSelType();
2461   assert(!argT.isNull() && "Can't find 'SEL' type");
2462   ArgTys.push_back(argT);
2463   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2464                                                &ArgTys[0], ArgTys.size(),
2465                                                true /*isVariadic*/);
2466   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2467                                          SourceLocation(),
2468                                          SourceLocation(),
2469                                          msgSendIdent, msgSendType, 0,
2470                                          SC_Extern,
2471                                          SC_None, false);
2472 }
2473
2474 // SynthMsgSendSuperStretFunctionDecl -
2475 // id objc_msgSendSuper_stret(void);
2476 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2477   IdentifierInfo *msgSendIdent =
2478     &Context->Idents.get("objc_msgSendSuper_stret");
2479   SmallVector<QualType, 2> ArgTys;
2480   ArgTys.push_back(Context->VoidTy);
2481   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2482                                                &ArgTys[0], 1,
2483                                                true /*isVariadic*/);
2484   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2485                                                        SourceLocation(),
2486                                                        SourceLocation(),
2487                                               msgSendIdent, msgSendType, 0,
2488                                               SC_Extern,
2489                                               SC_None, false);
2490 }
2491
2492 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495   SmallVector<QualType, 16> ArgTys;
2496   QualType argT = Context->getObjCIdType();
2497   assert(!argT.isNull() && "Can't find 'id' type");
2498   ArgTys.push_back(argT);
2499   argT = Context->getObjCSelType();
2500   assert(!argT.isNull() && "Can't find 'SEL' type");
2501   ArgTys.push_back(argT);
2502   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2503                                                &ArgTys[0], ArgTys.size(),
2504                                                true /*isVariadic*/);
2505   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2506                                               SourceLocation(),
2507                                               SourceLocation(),
2508                                               msgSendIdent, msgSendType, 0,
2509                                               SC_Extern,
2510                                               SC_None, false);
2511 }
2512
2513 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2514 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2515   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2516   SmallVector<QualType, 16> ArgTys;
2517   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2518   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2519                                                 &ArgTys[0], ArgTys.size());
2520   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2521                                           SourceLocation(),
2522                                           SourceLocation(),
2523                                           getClassIdent, getClassType, 0,
2524                                           SC_Extern,
2525                                           SC_None, false);
2526 }
2527
2528 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2529 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2530   IdentifierInfo *getSuperClassIdent = 
2531     &Context->Idents.get("class_getSuperclass");
2532   SmallVector<QualType, 16> ArgTys;
2533   ArgTys.push_back(Context->getObjCClassType());
2534   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2535                                                 &ArgTys[0], ArgTys.size());
2536   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2537                                                    SourceLocation(),
2538                                                    SourceLocation(),
2539                                                    getSuperClassIdent,
2540                                                    getClassType, 0,
2541                                                    SC_Extern,
2542                                                    SC_None,
2543                                                    false);
2544 }
2545
2546 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2547 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2548   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2549   SmallVector<QualType, 16> ArgTys;
2550   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2551   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2552                                                 &ArgTys[0], ArgTys.size());
2553   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2554                                               SourceLocation(),
2555                                               SourceLocation(),
2556                                               getClassIdent, getClassType, 0,
2557                                               SC_Extern,
2558                                               SC_None, false);
2559 }
2560
2561 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2562   QualType strType = getConstantStringStructType();
2563
2564   std::string S = "__NSConstantStringImpl_";
2565
2566   std::string tmpName = InFileName;
2567   unsigned i;
2568   for (i=0; i < tmpName.length(); i++) {
2569     char c = tmpName.at(i);
2570     // replace any non alphanumeric characters with '_'.
2571     if (!isalpha(c) && (c < '0' || c > '9'))
2572       tmpName[i] = '_';
2573   }
2574   S += tmpName;
2575   S += "_";
2576   S += utostr(NumObjCStringLiterals++);
2577
2578   Preamble += "static __NSConstantStringImpl " + S;
2579   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2580   Preamble += "0x000007c8,"; // utf8_str
2581   // The pretty printer for StringLiteral handles escape characters properly.
2582   std::string prettyBufS;
2583   llvm::raw_string_ostream prettyBuf(prettyBufS);
2584   Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
2585   Preamble += prettyBuf.str();
2586   Preamble += ",";
2587   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2588
2589   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2590                                    SourceLocation(), &Context->Idents.get(S),
2591                                    strType, 0, SC_Static, SC_None);
2592   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2593                                                SourceLocation());
2594   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2595                                  Context->getPointerType(DRE->getType()),
2596                                            VK_RValue, OK_Ordinary,
2597                                            SourceLocation());
2598   // cast to NSConstantString *
2599   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2600                                             CK_CPointerToObjCPointerCast, Unop);
2601   ReplaceStmt(Exp, cast);
2602   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2603   return cast;
2604 }
2605
2606 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2607   unsigned IntSize =
2608     static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2609   
2610   Expr *FlagExp = IntegerLiteral::Create(*Context, 
2611                                          llvm::APInt(IntSize, Exp->getValue()), 
2612                                          Context->IntTy, Exp->getLocation());
2613   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2614                                             CK_BitCast, FlagExp);
2615   ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), 
2616                                           cast);
2617   ReplaceStmt(Exp, PE);
2618   return PE;
2619 }
2620
2621 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2622   // synthesize declaration of helper functions needed in this routine.
2623   if (!SelGetUidFunctionDecl)
2624     SynthSelGetUidFunctionDecl();
2625   // use objc_msgSend() for all.
2626   if (!MsgSendFunctionDecl)
2627     SynthMsgSendFunctionDecl();
2628   if (!GetClassFunctionDecl)
2629     SynthGetClassFunctionDecl();
2630   
2631   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2632   SourceLocation StartLoc = Exp->getLocStart();
2633   SourceLocation EndLoc = Exp->getLocEnd();
2634   
2635   // Synthesize a call to objc_msgSend().
2636   SmallVector<Expr*, 4> MsgExprs;
2637   SmallVector<Expr*, 4> ClsExprs;
2638   QualType argType = Context->getPointerType(Context->CharTy);
2639   
2640   // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2641   ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2642   ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2643   
2644   IdentifierInfo *clsName = BoxingClass->getIdentifier();
2645   ClsExprs.push_back(StringLiteral::Create(*Context,
2646                                            clsName->getName(),
2647                                            StringLiteral::Ascii, false,
2648                                            argType, SourceLocation()));
2649   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2650                                                &ClsExprs[0],
2651                                                ClsExprs.size(), 
2652                                                StartLoc, EndLoc);
2653   MsgExprs.push_back(Cls);
2654   
2655   // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2656   // it will be the 2nd argument.
2657   SmallVector<Expr*, 4> SelExprs;
2658   SelExprs.push_back(StringLiteral::Create(*Context,
2659                                            BoxingMethod->getSelector().getAsString(),
2660                                            StringLiteral::Ascii, false,
2661                                            argType, SourceLocation()));
2662   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2663                                                   &SelExprs[0], SelExprs.size(),
2664                                                   StartLoc, EndLoc);
2665   MsgExprs.push_back(SelExp);
2666   
2667   // User provided sub-expression is the 3rd, and last, argument.
2668   Expr *subExpr  = Exp->getSubExpr();
2669   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2670     QualType type = ICE->getType();
2671     const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2672     CastKind CK = CK_BitCast;
2673     if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2674       CK = CK_IntegralToBoolean;
2675     subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2676   }
2677   MsgExprs.push_back(subExpr);
2678   
2679   SmallVector<QualType, 4> ArgTypes;
2680   ArgTypes.push_back(Context->getObjCIdType());
2681   ArgTypes.push_back(Context->getObjCSelType());
2682   for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2683        E = BoxingMethod->param_end(); PI != E; ++PI)
2684     ArgTypes.push_back((*PI)->getType());
2685   
2686   QualType returnType = Exp->getType();
2687   // Get the type, we will need to reference it in a couple spots.
2688   QualType msgSendType = MsgSendFlavor->getType();
2689   
2690   // Create a reference to the objc_msgSend() declaration.
2691   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2692                                                VK_LValue, SourceLocation());
2693   
2694   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2695                                             Context->getPointerType(Context->VoidTy),
2696                                             CK_BitCast, DRE);
2697   
2698   // Now do the "normal" pointer to function cast.
2699   QualType castType =
2700   getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2701                         BoxingMethod->isVariadic());
2702   castType = Context->getPointerType(castType);
2703   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2704                                   cast);
2705   
2706   // Don't forget the parens to enforce the proper binding.
2707   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2708   
2709   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2710   CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
2711                                         FT->getResultType(), VK_RValue,
2712                                         EndLoc);
2713   ReplaceStmt(Exp, CE);
2714   return CE;
2715 }
2716
2717 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2718   // synthesize declaration of helper functions needed in this routine.
2719   if (!SelGetUidFunctionDecl)
2720     SynthSelGetUidFunctionDecl();
2721   // use objc_msgSend() for all.
2722   if (!MsgSendFunctionDecl)
2723     SynthMsgSendFunctionDecl();
2724   if (!GetClassFunctionDecl)
2725     SynthGetClassFunctionDecl();
2726   
2727   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2728   SourceLocation StartLoc = Exp->getLocStart();
2729   SourceLocation EndLoc = Exp->getLocEnd();
2730   
2731   // Build the expression: __NSContainer_literal(int, ...).arr
2732   QualType IntQT = Context->IntTy;
2733   QualType NSArrayFType =
2734     getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2735   std::string NSArrayFName("__NSContainer_literal");
2736   FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2737   DeclRefExpr *NSArrayDRE = 
2738     new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2739                               SourceLocation());
2740
2741   SmallVector<Expr*, 16> InitExprs;
2742   unsigned NumElements = Exp->getNumElements();
2743   unsigned UnsignedIntSize = 
2744     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2745   Expr *count = IntegerLiteral::Create(*Context,
2746                                        llvm::APInt(UnsignedIntSize, NumElements),
2747                                        Context->UnsignedIntTy, SourceLocation());
2748   InitExprs.push_back(count);
2749   for (unsigned i = 0; i < NumElements; i++)
2750     InitExprs.push_back(Exp->getElement(i));
2751   Expr *NSArrayCallExpr = 
2752     new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2753                            NSArrayFType, VK_LValue, SourceLocation());
2754   
2755   FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2756                                     SourceLocation(),
2757                                     &Context->Idents.get("arr"),
2758                                     Context->getPointerType(Context->VoidPtrTy), 0,
2759                                     /*BitWidth=*/0, /*Mutable=*/true,
2760                                     ICIS_NoInit);
2761   MemberExpr *ArrayLiteralME = 
2762     new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD, 
2763                              SourceLocation(),
2764                              ARRFD->getType(), VK_LValue,
2765                              OK_Ordinary);
2766   QualType ConstIdT = Context->getObjCIdType().withConst();
2767   CStyleCastExpr * ArrayLiteralObjects = 
2768     NoTypeInfoCStyleCastExpr(Context, 
2769                              Context->getPointerType(ConstIdT),
2770                              CK_BitCast,
2771                              ArrayLiteralME);
2772   
2773   // Synthesize a call to objc_msgSend().
2774   SmallVector<Expr*, 32> MsgExprs;
2775   SmallVector<Expr*, 4> ClsExprs;
2776   QualType argType = Context->getPointerType(Context->CharTy);
2777   QualType expType = Exp->getType();
2778   
2779   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2780   ObjCInterfaceDecl *Class = 
2781     expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2782   
2783   IdentifierInfo *clsName = Class->getIdentifier();
2784   ClsExprs.push_back(StringLiteral::Create(*Context,
2785                                            clsName->getName(),
2786                                            StringLiteral::Ascii, false,
2787                                            argType, SourceLocation()));
2788   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2789                                                &ClsExprs[0],
2790                                                ClsExprs.size(), 
2791                                                StartLoc, EndLoc);
2792   MsgExprs.push_back(Cls);
2793   
2794   // Create a call to sel_registerName("arrayWithObjects:count:").
2795   // it will be the 2nd argument.
2796   SmallVector<Expr*, 4> SelExprs;
2797   ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2798   SelExprs.push_back(StringLiteral::Create(*Context,
2799                                            ArrayMethod->getSelector().getAsString(),
2800                                            StringLiteral::Ascii, false,
2801                                            argType, SourceLocation()));
2802   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2803                                                   &SelExprs[0], SelExprs.size(),
2804                                                   StartLoc, EndLoc);
2805   MsgExprs.push_back(SelExp);
2806   
2807   // (const id [])objects
2808   MsgExprs.push_back(ArrayLiteralObjects);
2809   
2810   // (NSUInteger)cnt
2811   Expr *cnt = IntegerLiteral::Create(*Context,
2812                                      llvm::APInt(UnsignedIntSize, NumElements),
2813                                      Context->UnsignedIntTy, SourceLocation());
2814   MsgExprs.push_back(cnt);
2815   
2816   
2817   SmallVector<QualType, 4> ArgTypes;
2818   ArgTypes.push_back(Context->getObjCIdType());
2819   ArgTypes.push_back(Context->getObjCSelType());
2820   for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2821        E = ArrayMethod->param_end(); PI != E; ++PI)
2822     ArgTypes.push_back((*PI)->getType());
2823   
2824   QualType returnType = Exp->getType();
2825   // Get the type, we will need to reference it in a couple spots.
2826   QualType msgSendType = MsgSendFlavor->getType();
2827   
2828   // Create a reference to the objc_msgSend() declaration.
2829   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2830                                                VK_LValue, SourceLocation());
2831   
2832   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2833                                             Context->getPointerType(Context->VoidTy),
2834                                             CK_BitCast, DRE);
2835   
2836   // Now do the "normal" pointer to function cast.
2837   QualType castType =
2838   getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2839                         ArrayMethod->isVariadic());
2840   castType = Context->getPointerType(castType);
2841   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2842                                   cast);
2843   
2844   // Don't forget the parens to enforce the proper binding.
2845   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2846   
2847   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2848   CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
2849                                         FT->getResultType(), VK_RValue,
2850                                         EndLoc);
2851   ReplaceStmt(Exp, CE);
2852   return CE;
2853 }
2854
2855 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2856   // synthesize declaration of helper functions needed in this routine.
2857   if (!SelGetUidFunctionDecl)
2858     SynthSelGetUidFunctionDecl();
2859   // use objc_msgSend() for all.
2860   if (!MsgSendFunctionDecl)
2861     SynthMsgSendFunctionDecl();
2862   if (!GetClassFunctionDecl)
2863     SynthGetClassFunctionDecl();
2864   
2865   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2866   SourceLocation StartLoc = Exp->getLocStart();
2867   SourceLocation EndLoc = Exp->getLocEnd();
2868   
2869   // Build the expression: __NSContainer_literal(int, ...).arr
2870   QualType IntQT = Context->IntTy;
2871   QualType NSDictFType =
2872     getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2873   std::string NSDictFName("__NSContainer_literal");
2874   FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2875   DeclRefExpr *NSDictDRE = 
2876     new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2877                               SourceLocation());
2878   
2879   SmallVector<Expr*, 16> KeyExprs;
2880   SmallVector<Expr*, 16> ValueExprs;
2881   
2882   unsigned NumElements = Exp->getNumElements();
2883   unsigned UnsignedIntSize = 
2884     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2885   Expr *count = IntegerLiteral::Create(*Context,
2886                                        llvm::APInt(UnsignedIntSize, NumElements),
2887                                        Context->UnsignedIntTy, SourceLocation());
2888   KeyExprs.push_back(count);
2889   ValueExprs.push_back(count);
2890   for (unsigned i = 0; i < NumElements; i++) {
2891     ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2892     KeyExprs.push_back(Element.Key);
2893     ValueExprs.push_back(Element.Value);
2894   }
2895   
2896   // (const id [])objects
2897   Expr *NSValueCallExpr = 
2898     new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2899                            NSDictFType, VK_LValue, SourceLocation());
2900   
2901   FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2902                                        SourceLocation(),
2903                                        &Context->Idents.get("arr"),
2904                                        Context->getPointerType(Context->VoidPtrTy), 0,
2905                                        /*BitWidth=*/0, /*Mutable=*/true,
2906                                        ICIS_NoInit);
2907   MemberExpr *DictLiteralValueME = 
2908     new (Context) MemberExpr(NSValueCallExpr, false, ARRFD, 
2909                              SourceLocation(),
2910                              ARRFD->getType(), VK_LValue,
2911                              OK_Ordinary);
2912   QualType ConstIdT = Context->getObjCIdType().withConst();
2913   CStyleCastExpr * DictValueObjects = 
2914     NoTypeInfoCStyleCastExpr(Context, 
2915                              Context->getPointerType(ConstIdT),
2916                              CK_BitCast,
2917                              DictLiteralValueME);
2918   // (const id <NSCopying> [])keys
2919   Expr *NSKeyCallExpr = 
2920     new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2921                            NSDictFType, VK_LValue, SourceLocation());
2922   
2923   MemberExpr *DictLiteralKeyME = 
2924     new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD, 
2925                              SourceLocation(),
2926                              ARRFD->getType(), VK_LValue,
2927                              OK_Ordinary);
2928   
2929   CStyleCastExpr * DictKeyObjects = 
2930     NoTypeInfoCStyleCastExpr(Context, 
2931                              Context->getPointerType(ConstIdT),
2932                              CK_BitCast,
2933                              DictLiteralKeyME);
2934   
2935   
2936   
2937   // Synthesize a call to objc_msgSend().
2938   SmallVector<Expr*, 32> MsgExprs;
2939   SmallVector<Expr*, 4> ClsExprs;
2940   QualType argType = Context->getPointerType(Context->CharTy);
2941   QualType expType = Exp->getType();
2942   
2943   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2944   ObjCInterfaceDecl *Class = 
2945   expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2946   
2947   IdentifierInfo *clsName = Class->getIdentifier();
2948   ClsExprs.push_back(StringLiteral::Create(*Context,
2949                                            clsName->getName(),
2950                                            StringLiteral::Ascii, false,
2951                                            argType, SourceLocation()));
2952   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2953                                                &ClsExprs[0],
2954                                                ClsExprs.size(), 
2955                                                StartLoc, EndLoc);
2956   MsgExprs.push_back(Cls);
2957   
2958   // Create a call to sel_registerName("arrayWithObjects:count:").
2959   // it will be the 2nd argument.
2960   SmallVector<Expr*, 4> SelExprs;
2961   ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2962   SelExprs.push_back(StringLiteral::Create(*Context,
2963                                            DictMethod->getSelector().getAsString(),
2964                                            StringLiteral::Ascii, false,
2965                                            argType, SourceLocation()));
2966   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2967                                                   &SelExprs[0], SelExprs.size(),
2968                                                   StartLoc, EndLoc);
2969   MsgExprs.push_back(SelExp);
2970   
2971   // (const id [])objects
2972   MsgExprs.push_back(DictValueObjects);
2973   
2974   // (const id <NSCopying> [])keys
2975   MsgExprs.push_back(DictKeyObjects);
2976   
2977   // (NSUInteger)cnt
2978   Expr *cnt = IntegerLiteral::Create(*Context,
2979                                      llvm::APInt(UnsignedIntSize, NumElements),
2980                                      Context->UnsignedIntTy, SourceLocation());
2981   MsgExprs.push_back(cnt);
2982   
2983   
2984   SmallVector<QualType, 8> ArgTypes;
2985   ArgTypes.push_back(Context->getObjCIdType());
2986   ArgTypes.push_back(Context->getObjCSelType());
2987   for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2988        E = DictMethod->param_end(); PI != E; ++PI) {
2989     QualType T = (*PI)->getType();
2990     if (const PointerType* PT = T->getAs<PointerType>()) {
2991       QualType PointeeTy = PT->getPointeeType();
2992       convertToUnqualifiedObjCType(PointeeTy);
2993       T = Context->getPointerType(PointeeTy);
2994     }
2995     ArgTypes.push_back(T);
2996   }
2997   
2998   QualType returnType = Exp->getType();
2999   // Get the type, we will need to reference it in a couple spots.
3000   QualType msgSendType = MsgSendFlavor->getType();
3001   
3002   // Create a reference to the objc_msgSend() declaration.
3003   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3004                                                VK_LValue, SourceLocation());
3005   
3006   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3007                                             Context->getPointerType(Context->VoidTy),
3008                                             CK_BitCast, DRE);
3009   
3010   // Now do the "normal" pointer to function cast.
3011   QualType castType =
3012   getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3013                         DictMethod->isVariadic());
3014   castType = Context->getPointerType(castType);
3015   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3016                                   cast);
3017   
3018   // Don't forget the parens to enforce the proper binding.
3019   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3020   
3021   const FunctionType *FT = msgSendType->getAs<FunctionType>();
3022   CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3023                                         FT->getResultType(), VK_RValue,
3024                                         EndLoc);
3025   ReplaceStmt(Exp, CE);
3026   return CE;
3027 }
3028
3029 // struct __rw_objc_super { 
3030 //   struct objc_object *object; struct objc_object *superClass; 
3031 // };
3032 QualType RewriteModernObjC::getSuperStructType() {
3033   if (!SuperStructDecl) {
3034     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3035                                          SourceLocation(), SourceLocation(),
3036                                          &Context->Idents.get("__rw_objc_super"));
3037     QualType FieldTypes[2];
3038
3039     // struct objc_object *object;
3040     FieldTypes[0] = Context->getObjCIdType();
3041     // struct objc_object *superClass;
3042     FieldTypes[1] = Context->getObjCIdType();
3043
3044     // Create fields
3045     for (unsigned i = 0; i < 2; ++i) {
3046       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3047                                                  SourceLocation(),
3048                                                  SourceLocation(), 0,
3049                                                  FieldTypes[i], 0,
3050                                                  /*BitWidth=*/0,
3051                                                  /*Mutable=*/false,
3052                                                  ICIS_NoInit));
3053     }
3054
3055     SuperStructDecl->completeDefinition();
3056   }
3057   return Context->getTagDeclType(SuperStructDecl);
3058 }
3059
3060 QualType RewriteModernObjC::getConstantStringStructType() {
3061   if (!ConstantStringDecl) {
3062     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3063                                             SourceLocation(), SourceLocation(),
3064                          &Context->Idents.get("__NSConstantStringImpl"));
3065     QualType FieldTypes[4];
3066
3067     // struct objc_object *receiver;
3068     FieldTypes[0] = Context->getObjCIdType();
3069     // int flags;
3070     FieldTypes[1] = Context->IntTy;
3071     // char *str;
3072     FieldTypes[2] = Context->getPointerType(Context->CharTy);
3073     // long length;
3074     FieldTypes[3] = Context->LongTy;
3075
3076     // Create fields
3077     for (unsigned i = 0; i < 4; ++i) {
3078       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3079                                                     ConstantStringDecl,
3080                                                     SourceLocation(),
3081                                                     SourceLocation(), 0,
3082                                                     FieldTypes[i], 0,
3083                                                     /*BitWidth=*/0,
3084                                                     /*Mutable=*/true,
3085                                                     ICIS_NoInit));
3086     }
3087
3088     ConstantStringDecl->completeDefinition();
3089   }
3090   return Context->getTagDeclType(ConstantStringDecl);
3091 }
3092
3093 /// getFunctionSourceLocation - returns start location of a function
3094 /// definition. Complication arises when function has declared as
3095 /// extern "C" or extern "C" {...}
3096 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3097                                                  FunctionDecl *FD) {
3098   if (FD->isExternC()  && !FD->isMain()) {
3099     const DeclContext *DC = FD->getDeclContext();
3100     if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3101       // if it is extern "C" {...}, return function decl's own location.
3102       if (!LSD->getRBraceLoc().isValid())
3103         return LSD->getExternLoc();
3104   }
3105   if (FD->getStorageClassAsWritten() != SC_None)
3106     R.RewriteBlockLiteralFunctionDecl(FD);
3107   return FD->getTypeSpecStartLoc();
3108 }
3109
3110 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3111   
3112   SourceLocation Location = D->getLocation();
3113   
3114   if (Location.isFileID()) {
3115     std::string LineString("\n#line ");
3116     PresumedLoc PLoc = SM->getPresumedLoc(Location);
3117     LineString += utostr(PLoc.getLine());
3118     LineString += " \"";
3119     LineString += Lexer::Stringify(PLoc.getFilename());
3120     if (isa<ObjCMethodDecl>(D))
3121       LineString += "\"";
3122     else LineString += "\"\n";
3123     
3124     Location = D->getLocStart();
3125     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3126       if (FD->isExternC()  && !FD->isMain()) {
3127         const DeclContext *DC = FD->getDeclContext();
3128         if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3129           // if it is extern "C" {...}, return function decl's own location.
3130           if (!LSD->getRBraceLoc().isValid())
3131             Location = LSD->getExternLoc();
3132       }
3133     }
3134     InsertText(Location, LineString);
3135   }
3136 }
3137
3138 /// SynthMsgSendStretCallExpr - This routine translates message expression
3139 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3140 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3141 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3142 /// msgSendType - function type of objc_msgSend_stret(...)
3143 /// returnType - Result type of the method being synthesized.
3144 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3145 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, 
3146 /// starting with receiver.
3147 /// Method - Method being rewritten.
3148 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3149                                                  QualType msgSendType, 
3150                                                  QualType returnType, 
3151                                                  SmallVectorImpl<QualType> &ArgTypes,
3152                                                  SmallVectorImpl<Expr*> &MsgExprs,
3153                                                  ObjCMethodDecl *Method) {
3154   // Now do the "normal" pointer to function cast.
3155   QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3156                                             Method ? Method->isVariadic() : false);
3157   castType = Context->getPointerType(castType);
3158   
3159   // build type for containing the objc_msgSend_stret object.
3160   static unsigned stretCount=0;
3161   std::string name = "__Stret"; name += utostr(stretCount);
3162   std::string str = 
3163     "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3164   str += "struct "; str += name;
3165   str += " {\n\t";
3166   str += name;
3167   str += "(id receiver, SEL sel";
3168   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3169     std::string ArgName = "arg"; ArgName += utostr(i);
3170     ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3171     str += ", "; str += ArgName;
3172   }
3173   // could be vararg.
3174   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3175     std::string ArgName = "arg"; ArgName += utostr(i);
3176     MsgExprs[i]->getType().getAsStringInternal(ArgName,
3177                                                Context->getPrintingPolicy());
3178     str += ", "; str += ArgName;
3179   }
3180   
3181   str += ") {\n";
3182   str += "\t  if (receiver == 0)\n";
3183   str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3184   str += "\t  else\n";
3185   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3186   str += ")(void *)objc_msgSend_stret)(receiver, sel";
3187   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3188     str += ", arg"; str += utostr(i);
3189   }
3190   // could be vararg.
3191   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3192     str += ", arg"; str += utostr(i);
3193   }
3194   
3195   str += ");\n";
3196   str += "\t}\n";
3197   str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3198   str += " s;\n";
3199   str += "};\n\n";
3200   SourceLocation FunLocStart;
3201   if (CurFunctionDef)
3202     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3203   else {
3204     assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3205     FunLocStart = CurMethodDef->getLocStart();
3206   }
3207
3208   InsertText(FunLocStart, str);
3209   ++stretCount;
3210   
3211   // AST for __Stretn(receiver, args).s;
3212   IdentifierInfo *ID = &Context->Idents.get(name);
3213   FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3214                                           SourceLocation(), ID, castType, 0, SC_Extern,
3215                                           SC_None, false, false);
3216   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3217                                                SourceLocation());
3218   CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3219                                           castType, VK_LValue, SourceLocation());
3220   
3221   FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3222                                     SourceLocation(),
3223                                     &Context->Idents.get("s"),
3224                                     returnType, 0,
3225                                     /*BitWidth=*/0, /*Mutable=*/true,
3226                                     ICIS_NoInit);
3227   MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3228                                             FieldD->getType(), VK_LValue,
3229                                             OK_Ordinary);
3230
3231   return ME;
3232 }
3233
3234 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3235                                     SourceLocation StartLoc,
3236                                     SourceLocation EndLoc) {
3237   if (!SelGetUidFunctionDecl)
3238     SynthSelGetUidFunctionDecl();
3239   if (!MsgSendFunctionDecl)
3240     SynthMsgSendFunctionDecl();
3241   if (!MsgSendSuperFunctionDecl)
3242     SynthMsgSendSuperFunctionDecl();
3243   if (!MsgSendStretFunctionDecl)
3244     SynthMsgSendStretFunctionDecl();
3245   if (!MsgSendSuperStretFunctionDecl)
3246     SynthMsgSendSuperStretFunctionDecl();
3247   if (!MsgSendFpretFunctionDecl)
3248     SynthMsgSendFpretFunctionDecl();
3249   if (!GetClassFunctionDecl)
3250     SynthGetClassFunctionDecl();
3251   if (!GetSuperClassFunctionDecl)
3252     SynthGetSuperClassFunctionDecl();
3253   if (!GetMetaClassFunctionDecl)
3254     SynthGetMetaClassFunctionDecl();
3255
3256   // default to objc_msgSend().
3257   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3258   // May need to use objc_msgSend_stret() as well.
3259   FunctionDecl *MsgSendStretFlavor = 0;
3260   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3261     QualType resultType = mDecl->getResultType();
3262     if (resultType->isRecordType())
3263       MsgSendStretFlavor = MsgSendStretFunctionDecl;
3264     else if (resultType->isRealFloatingType())
3265       MsgSendFlavor = MsgSendFpretFunctionDecl;
3266   }
3267
3268   // Synthesize a call to objc_msgSend().
3269   SmallVector<Expr*, 8> MsgExprs;
3270   switch (Exp->getReceiverKind()) {
3271   case ObjCMessageExpr::SuperClass: {
3272     MsgSendFlavor = MsgSendSuperFunctionDecl;
3273     if (MsgSendStretFlavor)
3274       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3275     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3276
3277     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3278
3279     SmallVector<Expr*, 4> InitExprs;
3280
3281     // set the receiver to self, the first argument to all methods.
3282     InitExprs.push_back(
3283       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3284                                CK_BitCast,
3285                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3286                                              false,
3287                                              Context->getObjCIdType(),
3288                                              VK_RValue,
3289                                              SourceLocation()))
3290                         ); // set the 'receiver'.
3291
3292     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3293     SmallVector<Expr*, 8> ClsExprs;
3294     QualType argType = Context->getPointerType(Context->CharTy);
3295     ClsExprs.push_back(StringLiteral::Create(*Context,
3296                                    ClassDecl->getIdentifier()->getName(),
3297                                    StringLiteral::Ascii, false,
3298                                    argType, SourceLocation()));
3299     // (Class)objc_getClass("CurrentClass")
3300     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3301                                                  &ClsExprs[0],
3302                                                  ClsExprs.size(),
3303                                                  StartLoc,
3304                                                  EndLoc);
3305     ClsExprs.clear();
3306     ClsExprs.push_back(Cls);
3307     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3308                                        &ClsExprs[0], ClsExprs.size(),
3309                                        StartLoc, EndLoc);
3310     
3311     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3312     // To turn off a warning, type-cast to 'id'
3313     InitExprs.push_back( // set 'super class', using class_getSuperclass().
3314                         NoTypeInfoCStyleCastExpr(Context,
3315                                                  Context->getObjCIdType(),
3316                                                  CK_BitCast, Cls));
3317     // struct __rw_objc_super
3318     QualType superType = getSuperStructType();
3319     Expr *SuperRep;
3320
3321     if (LangOpts.MicrosoftExt) {
3322       SynthSuperContructorFunctionDecl();
3323       // Simulate a contructor call...
3324       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
3325                                                    false, superType, VK_LValue,
3326                                                    SourceLocation());
3327       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3328                                         superType, VK_LValue,
3329                                         SourceLocation());
3330       // The code for super is a little tricky to prevent collision with
3331       // the structure definition in the header. The rewriter has it's own
3332       // internal definition (__rw_objc_super) that is uses. This is why
3333       // we need the cast below. For example:
3334       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3335       //
3336       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3337                                Context->getPointerType(SuperRep->getType()),
3338                                              VK_RValue, OK_Ordinary,
3339                                              SourceLocation());
3340       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3341                                           Context->getPointerType(superType),
3342                                           CK_BitCast, SuperRep);
3343     } else {
3344       // (struct __rw_objc_super) { <exprs from above> }
3345       InitListExpr *ILE =
3346         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3347                                    SourceLocation());
3348       TypeSourceInfo *superTInfo
3349         = Context->getTrivialTypeSourceInfo(superType);
3350       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3351                                                    superType, VK_LValue,
3352                                                    ILE, false);
3353       // struct __rw_objc_super *
3354       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3355                                Context->getPointerType(SuperRep->getType()),
3356                                              VK_RValue, OK_Ordinary,
3357                                              SourceLocation());
3358     }
3359     MsgExprs.push_back(SuperRep);
3360     break;
3361   }
3362
3363   case ObjCMessageExpr::Class: {
3364     SmallVector<Expr*, 8> ClsExprs;
3365     QualType argType = Context->getPointerType(Context->CharTy);
3366     ObjCInterfaceDecl *Class
3367       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3368     IdentifierInfo *clsName = Class->getIdentifier();
3369     ClsExprs.push_back(StringLiteral::Create(*Context,
3370                                              clsName->getName(),
3371                                              StringLiteral::Ascii, false,
3372                                              argType, SourceLocation()));
3373     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3374                                                  &ClsExprs[0],
3375                                                  ClsExprs.size(), 
3376                                                  StartLoc, EndLoc);
3377     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3378                                                  Context->getObjCIdType(),
3379                                                  CK_BitCast, Cls);
3380     MsgExprs.push_back(ArgExpr);
3381     break;
3382   }
3383
3384   case ObjCMessageExpr::SuperInstance:{
3385     MsgSendFlavor = MsgSendSuperFunctionDecl;
3386     if (MsgSendStretFlavor)
3387       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3388     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3389     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3390     SmallVector<Expr*, 4> InitExprs;
3391
3392     InitExprs.push_back(
3393       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3394                                CK_BitCast,
3395                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3396                                              false,
3397                                              Context->getObjCIdType(),
3398                                              VK_RValue, SourceLocation()))
3399                         ); // set the 'receiver'.
3400     
3401     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3402     SmallVector<Expr*, 8> ClsExprs;
3403     QualType argType = Context->getPointerType(Context->CharTy);
3404     ClsExprs.push_back(StringLiteral::Create(*Context,
3405                                    ClassDecl->getIdentifier()->getName(),
3406                                    StringLiteral::Ascii, false, argType,
3407                                    SourceLocation()));
3408     // (Class)objc_getClass("CurrentClass")
3409     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3410                                                  &ClsExprs[0],
3411                                                  ClsExprs.size(), 
3412                                                  StartLoc, EndLoc);
3413     ClsExprs.clear();
3414     ClsExprs.push_back(Cls);
3415     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3416                                        &ClsExprs[0], ClsExprs.size(),
3417                                        StartLoc, EndLoc);
3418     
3419     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3420     // To turn off a warning, type-cast to 'id'
3421     InitExprs.push_back(
3422       // set 'super class', using class_getSuperclass().
3423       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3424                                CK_BitCast, Cls));
3425     // struct __rw_objc_super
3426     QualType superType = getSuperStructType();
3427     Expr *SuperRep;
3428
3429     if (LangOpts.MicrosoftExt) {
3430       SynthSuperContructorFunctionDecl();
3431       // Simulate a contructor call...
3432       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
3433                                                    false, superType, VK_LValue,
3434                                                    SourceLocation());
3435       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3436                                         superType, VK_LValue, SourceLocation());
3437       // The code for super is a little tricky to prevent collision with
3438       // the structure definition in the header. The rewriter has it's own
3439       // internal definition (__rw_objc_super) that is uses. This is why
3440       // we need the cast below. For example:
3441       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3442       //
3443       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3444                                Context->getPointerType(SuperRep->getType()),
3445                                VK_RValue, OK_Ordinary,
3446                                SourceLocation());
3447       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3448                                Context->getPointerType(superType),
3449                                CK_BitCast, SuperRep);
3450     } else {
3451       // (struct __rw_objc_super) { <exprs from above> }
3452       InitListExpr *ILE =
3453         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3454                                    SourceLocation());
3455       TypeSourceInfo *superTInfo
3456         = Context->getTrivialTypeSourceInfo(superType);
3457       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3458                                                    superType, VK_RValue, ILE,
3459                                                    false);
3460     }
3461     MsgExprs.push_back(SuperRep);
3462     break;
3463   }
3464
3465   case ObjCMessageExpr::Instance: {
3466     // Remove all type-casts because it may contain objc-style types; e.g.
3467     // Foo<Proto> *.
3468     Expr *recExpr = Exp->getInstanceReceiver();
3469     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3470       recExpr = CE->getSubExpr();
3471     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3472                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3473                                      ? CK_BlockPointerToObjCPointerCast
3474                                      : CK_CPointerToObjCPointerCast;
3475
3476     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3477                                        CK, recExpr);
3478     MsgExprs.push_back(recExpr);
3479     break;
3480   }
3481   }
3482
3483   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3484   SmallVector<Expr*, 8> SelExprs;
3485   QualType argType = Context->getPointerType(Context->CharTy);
3486   SelExprs.push_back(StringLiteral::Create(*Context,
3487                                        Exp->getSelector().getAsString(),
3488                                        StringLiteral::Ascii, false,
3489                                        argType, SourceLocation()));
3490   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3491                                                  &SelExprs[0], SelExprs.size(),
3492                                                   StartLoc,
3493                                                   EndLoc);
3494   MsgExprs.push_back(SelExp);
3495
3496   // Now push any user supplied arguments.
3497   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3498     Expr *userExpr = Exp->getArg(i);
3499     // Make all implicit casts explicit...ICE comes in handy:-)
3500     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3501       // Reuse the ICE type, it is exactly what the doctor ordered.
3502       QualType type = ICE->getType();
3503       if (needToScanForQualifiers(type))
3504         type = Context->getObjCIdType();
3505       // Make sure we convert "type (^)(...)" to "type (*)(...)".
3506       (void)convertBlockPointerToFunctionPointer(type);
3507       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3508       CastKind CK;
3509       if (SubExpr->getType()->isIntegralType(*Context) && 
3510           type->isBooleanType()) {
3511         CK = CK_IntegralToBoolean;
3512       } else if (type->isObjCObjectPointerType()) {
3513         if (SubExpr->getType()->isBlockPointerType()) {
3514           CK = CK_BlockPointerToObjCPointerCast;
3515         } else if (SubExpr->getType()->isPointerType()) {
3516           CK = CK_CPointerToObjCPointerCast;
3517         } else {
3518           CK = CK_BitCast;
3519         }
3520       } else {
3521         CK = CK_BitCast;
3522       }
3523
3524       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3525     }
3526     // Make id<P...> cast into an 'id' cast.
3527     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3528       if (CE->getType()->isObjCQualifiedIdType()) {
3529         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3530           userExpr = CE->getSubExpr();
3531         CastKind CK;
3532         if (userExpr->getType()->isIntegralType(*Context)) {
3533           CK = CK_IntegralToPointer;
3534         } else if (userExpr->getType()->isBlockPointerType()) {
3535           CK = CK_BlockPointerToObjCPointerCast;
3536         } else if (userExpr->getType()->isPointerType()) {
3537           CK = CK_CPointerToObjCPointerCast;
3538         } else {
3539           CK = CK_BitCast;
3540         }
3541         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3542                                             CK, userExpr);
3543       }
3544     }
3545     MsgExprs.push_back(userExpr);
3546     // We've transferred the ownership to MsgExprs. For now, we *don't* null
3547     // out the argument in the original expression (since we aren't deleting
3548     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3549     //Exp->setArg(i, 0);
3550   }
3551   // Generate the funky cast.
3552   CastExpr *cast;
3553   SmallVector<QualType, 8> ArgTypes;
3554   QualType returnType;
3555
3556   // Push 'id' and 'SEL', the 2 implicit arguments.
3557   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3558     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3559   else
3560     ArgTypes.push_back(Context->getObjCIdType());
3561   ArgTypes.push_back(Context->getObjCSelType());
3562   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3563     // Push any user argument types.
3564     for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3565          E = OMD->param_end(); PI != E; ++PI) {
3566       QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3567                      ? Context->getObjCIdType()
3568                      : (*PI)->getType();
3569       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3570       (void)convertBlockPointerToFunctionPointer(t);
3571       ArgTypes.push_back(t);
3572     }
3573     returnType = Exp->getType();
3574     convertToUnqualifiedObjCType(returnType);
3575     (void)convertBlockPointerToFunctionPointer(returnType);
3576   } else {
3577     returnType = Context->getObjCIdType();
3578   }
3579   // Get the type, we will need to reference it in a couple spots.
3580   QualType msgSendType = MsgSendFlavor->getType();
3581
3582   // Create a reference to the objc_msgSend() declaration.
3583   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3584                                                VK_LValue, SourceLocation());
3585
3586   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3587   // If we don't do this cast, we get the following bizarre warning/note:
3588   // xx.m:13: warning: function called through a non-compatible type
3589   // xx.m:13: note: if this code is reached, the program will abort
3590   cast = NoTypeInfoCStyleCastExpr(Context,
3591                                   Context->getPointerType(Context->VoidTy),
3592                                   CK_BitCast, DRE);
3593
3594   // Now do the "normal" pointer to function cast.
3595   QualType castType =
3596     getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3597       // If we don't have a method decl, force a variadic cast.
3598       Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3599   castType = Context->getPointerType(castType);
3600   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3601                                   cast);
3602
3603   // Don't forget the parens to enforce the proper binding.
3604   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3605
3606   const FunctionType *FT = msgSendType->getAs<FunctionType>();
3607   CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3608                                         FT->getResultType(), VK_RValue, EndLoc);
3609   Stmt *ReplacingStmt = CE;
3610   if (MsgSendStretFlavor) {
3611     // We have the method which returns a struct/union. Must also generate
3612     // call to objc_msgSend_stret and hang both varieties on a conditional
3613     // expression which dictate which one to envoke depending on size of
3614     // method's return type.
3615
3616     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, 
3617                                            msgSendType, returnType, 
3618                                            ArgTypes, MsgExprs,
3619                                            Exp->getMethodDecl());
3620
3621     // Build sizeof(returnType)
3622     UnaryExprOrTypeTraitExpr *sizeofExpr =
3623        new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3624                                  Context->getTrivialTypeSourceInfo(returnType),
3625                                  Context->getSizeType(), SourceLocation(),
3626                                  SourceLocation());
3627     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3628     // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3629     // For X86 it is more complicated and some kind of target specific routine
3630     // is needed to decide what to do.
3631     unsigned IntSize =
3632       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3633     IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3634                                                    llvm::APInt(IntSize, 8),
3635                                                    Context->IntTy,
3636                                                    SourceLocation());
3637     BinaryOperator *lessThanExpr = 
3638       new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3639                                    VK_RValue, OK_Ordinary, SourceLocation(),
3640                                    false);
3641     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3642     ConditionalOperator *CondExpr =
3643       new (Context) ConditionalOperator(lessThanExpr,
3644                                         SourceLocation(), CE,
3645                                         SourceLocation(), STCE,
3646                                         returnType, VK_RValue, OK_Ordinary);
3647     ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
3648                                             CondExpr);
3649   }
3650   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3651   return ReplacingStmt;
3652 }
3653
3654 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3655   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3656                                          Exp->getLocEnd());
3657
3658   // Now do the actual rewrite.
3659   ReplaceStmt(Exp, ReplacingStmt);
3660
3661   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3662   return ReplacingStmt;
3663 }
3664
3665 // typedef struct objc_object Protocol;
3666 QualType RewriteModernObjC::getProtocolType() {
3667   if (!ProtocolTypeDecl) {
3668     TypeSourceInfo *TInfo
3669       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3670     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3671                                            SourceLocation(), SourceLocation(),
3672                                            &Context->Idents.get("Protocol"),
3673                                            TInfo);
3674   }
3675   return Context->getTypeDeclType(ProtocolTypeDecl);
3676 }
3677
3678 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3679 /// a synthesized/forward data reference (to the protocol's metadata).
3680 /// The forward references (and metadata) are generated in
3681 /// RewriteModernObjC::HandleTranslationUnit().
3682 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3683   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + 
3684                       Exp->getProtocol()->getNameAsString();
3685   IdentifierInfo *ID = &Context->Idents.get(Name);
3686   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3687                                 SourceLocation(), ID, getProtocolType(), 0,
3688                                 SC_Extern, SC_None);
3689   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3690                                                VK_LValue, SourceLocation());
3691   Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3692                              Context->getPointerType(DRE->getType()),
3693                              VK_RValue, OK_Ordinary, SourceLocation());
3694   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3695                                                 CK_BitCast,
3696                                                 DerefExpr);
3697   ReplaceStmt(Exp, castExpr);
3698   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3699   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3700   return castExpr;
3701
3702 }
3703
3704 bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3705                                              const char *endBuf) {
3706   while (startBuf < endBuf) {
3707     if (*startBuf == '#') {
3708       // Skip whitespace.
3709       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3710         ;
3711       if (!strncmp(startBuf, "if", strlen("if")) ||
3712           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3713           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3714           !strncmp(startBuf, "define", strlen("define")) ||
3715           !strncmp(startBuf, "undef", strlen("undef")) ||
3716           !strncmp(startBuf, "else", strlen("else")) ||
3717           !strncmp(startBuf, "elif", strlen("elif")) ||
3718           !strncmp(startBuf, "endif", strlen("endif")) ||
3719           !strncmp(startBuf, "pragma", strlen("pragma")) ||
3720           !strncmp(startBuf, "include", strlen("include")) ||
3721           !strncmp(startBuf, "import", strlen("import")) ||
3722           !strncmp(startBuf, "include_next", strlen("include_next")))
3723         return true;
3724     }
3725     startBuf++;
3726   }
3727   return false;
3728 }
3729
3730 /// IsTagDefinedInsideClass - This routine checks that a named tagged type 
3731 /// is defined inside an objective-c class. If so, it returns true. 
3732 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, 
3733                                                 TagDecl *Tag,
3734                                                 bool &IsNamedDefinition) {
3735   if (!IDecl)
3736     return false;
3737   SourceLocation TagLocation;
3738   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3739     RD = RD->getDefinition();
3740     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3741       return false;
3742     IsNamedDefinition = true;
3743     TagLocation = RD->getLocation();
3744     return Context->getSourceManager().isBeforeInTranslationUnit(
3745                                           IDecl->getLocation(), TagLocation);
3746   }
3747   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3748     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3749       return false;
3750     IsNamedDefinition = true;
3751     TagLocation = ED->getLocation();
3752     return Context->getSourceManager().isBeforeInTranslationUnit(
3753                                           IDecl->getLocation(), TagLocation);
3754
3755   }
3756   return false;
3757 }
3758
3759 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3760 /// It handles elaborated types, as well as enum types in the process.
3761 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, 
3762                                                  std::string &Result) {
3763   if (isa<TypedefType>(Type)) {
3764     Result += "\t";
3765     return false;
3766   }
3767     
3768   if (Type->isArrayType()) {
3769     QualType ElemTy = Context->getBaseElementType(Type);
3770     return RewriteObjCFieldDeclType(ElemTy, Result);
3771   }
3772   else if (Type->isRecordType()) {
3773     RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3774     if (RD->isCompleteDefinition()) {
3775       if (RD->isStruct())
3776         Result += "\n\tstruct ";
3777       else if (RD->isUnion())
3778         Result += "\n\tunion ";
3779       else
3780         assert(false && "class not allowed as an ivar type");
3781       
3782       Result += RD->getName();
3783       if (GlobalDefinedTags.count(RD)) {
3784         // struct/union is defined globally, use it.
3785         Result += " ";
3786         return true;
3787       }
3788       Result += " {\n";
3789       for (RecordDecl::field_iterator i = RD->field_begin(), 
3790            e = RD->field_end(); i != e; ++i) {
3791         FieldDecl *FD = *i;
3792         RewriteObjCFieldDecl(FD, Result);
3793       }
3794       Result += "\t} "; 
3795       return true;
3796     }
3797   }
3798   else if (Type->isEnumeralType()) {
3799     EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3800     if (ED->isCompleteDefinition()) {
3801       Result += "\n\tenum ";
3802       Result += ED->getName();
3803       if (GlobalDefinedTags.count(ED)) {
3804         // Enum is globall defined, use it.
3805         Result += " ";
3806         return true;
3807       }
3808       
3809       Result += " {\n";
3810       for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3811            ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3812         Result += "\t"; Result += EC->getName(); Result += " = ";
3813         llvm::APSInt Val = EC->getInitVal();
3814         Result += Val.toString(10);
3815         Result += ",\n";
3816       }
3817       Result += "\t} "; 
3818       return true;
3819     }
3820   }
3821   
3822   Result += "\t";
3823   convertObjCTypeToCStyleType(Type);
3824   return false;
3825 }
3826
3827
3828 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3829 /// It handles elaborated types, as well as enum types in the process.
3830 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, 
3831                                              std::string &Result) {
3832   QualType Type = fieldDecl->getType();
3833   std::string Name = fieldDecl->getNameAsString();
3834   
3835   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); 
3836   if (!EleboratedType)
3837     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3838   Result += Name;
3839   if (fieldDecl->isBitField()) {
3840     Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3841   }
3842   else if (EleboratedType && Type->isArrayType()) {
3843     CanQualType CType = Context->getCanonicalType(Type);
3844     while (isa<ArrayType>(CType)) {
3845       if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3846         Result += "[";
3847         llvm::APInt Dim = CAT->getSize();
3848         Result += utostr(Dim.getZExtValue());
3849         Result += "]";
3850       }
3851       CType = CType->getAs<ArrayType>()->getElementType();
3852     }
3853   }
3854   
3855   Result += ";\n";
3856 }
3857
3858 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3859 /// named aggregate types into the input buffer.
3860 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 
3861                                              std::string &Result) {
3862   QualType Type = fieldDecl->getType();
3863   if (isa<TypedefType>(Type))
3864     return;
3865   if (Type->isArrayType())
3866     Type = Context->getBaseElementType(Type);
3867   ObjCContainerDecl *IDecl = 
3868     dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3869   
3870   TagDecl *TD = 0;
3871   if (Type->isRecordType()) {
3872     TD = Type->getAs<RecordType>()->getDecl();
3873   }
3874   else if (Type->isEnumeralType()) {
3875     TD = Type->getAs<EnumType>()->getDecl();
3876   }
3877   
3878   if (TD) {
3879     if (GlobalDefinedTags.count(TD))
3880       return;
3881     
3882     bool IsNamedDefinition = false;
3883     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3884       RewriteObjCFieldDeclType(Type, Result);
3885       Result += ";";
3886     }
3887     if (IsNamedDefinition)
3888       GlobalDefinedTags.insert(TD);
3889   }
3890     
3891 }
3892
3893 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3894 /// an objective-c class with ivars.
3895 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3896                                                std::string &Result) {
3897   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3898   assert(CDecl->getName() != "" &&
3899          "Name missing in SynthesizeObjCInternalStruct");
3900   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3901   SmallVector<ObjCIvarDecl *, 8> IVars;
3902   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3903        IVD; IVD = IVD->getNextIvar())
3904     IVars.push_back(IVD);
3905   
3906   SourceLocation LocStart = CDecl->getLocStart();
3907   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3908   
3909   const char *startBuf = SM->getCharacterData(LocStart);
3910   const char *endBuf = SM->getCharacterData(LocEnd);
3911   
3912   // If no ivars and no root or if its root, directly or indirectly,
3913   // have no ivars (thus not synthesized) then no need to synthesize this class.
3914   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3915       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3916     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3917     ReplaceText(LocStart, endBuf-startBuf, Result);
3918     return;
3919   }
3920   
3921   // Insert named struct/union definitions inside class to
3922   // outer scope. This follows semantics of locally defined
3923   // struct/unions in objective-c classes.
3924   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3925     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3926
3927   Result += "\nstruct ";
3928   Result += CDecl->getNameAsString();
3929   Result += "_IMPL {\n";
3930   
3931   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3932     Result += "\tstruct "; Result += RCDecl->getNameAsString();
3933     Result += "_IMPL "; Result += RCDecl->getNameAsString();
3934     Result += "_IVARS;\n";
3935   }
3936   
3937   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3938     RewriteObjCFieldDecl(IVars[i], Result);
3939
3940   Result += "};\n";
3941   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3942   ReplaceText(LocStart, endBuf-startBuf, Result);
3943   // Mark this struct as having been generated.
3944   if (!ObjCSynthesizedStructs.insert(CDecl))
3945     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3946 }
3947
3948 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3949 /// have been referenced in an ivar access expression.
3950 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3951                                                   std::string &Result) {
3952   // write out ivar offset symbols which have been referenced in an ivar
3953   // access expression.
3954   llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3955   if (Ivars.empty())
3956     return;
3957   for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3958        e = Ivars.end(); i != e; i++) {
3959     ObjCIvarDecl *IvarDecl = (*i);
3960     Result += "\n";
3961     if (LangOpts.MicrosoftExt)
3962       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3963     Result += "extern \"C\" ";
3964     if (LangOpts.MicrosoftExt && 
3965         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3966         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3967         Result += "__declspec(dllimport) ";
3968
3969     Result += "unsigned long ";
3970     WriteInternalIvarName(CDecl, IvarDecl, Result);
3971     Result += ";";
3972   }
3973 }
3974
3975 //===----------------------------------------------------------------------===//
3976 // Meta Data Emission
3977 //===----------------------------------------------------------------------===//
3978
3979
3980 /// RewriteImplementations - This routine rewrites all method implementations
3981 /// and emits meta-data.
3982
3983 void RewriteModernObjC::RewriteImplementations() {
3984   int ClsDefCount = ClassImplementation.size();
3985   int CatDefCount = CategoryImplementation.size();
3986
3987   // Rewrite implemented methods
3988   for (int i = 0; i < ClsDefCount; i++) {
3989     ObjCImplementationDecl *OIMP = ClassImplementation[i];
3990     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3991     if (CDecl->isImplicitInterfaceDecl())
3992       assert(false &&
3993              "Legacy implicit interface rewriting not supported in moder abi");
3994     RewriteImplementationDecl(OIMP);
3995   }
3996
3997   for (int i = 0; i < CatDefCount; i++) {
3998     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3999     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4000     if (CDecl->isImplicitInterfaceDecl())
4001       assert(false &&
4002              "Legacy implicit interface rewriting not supported in moder abi");
4003     RewriteImplementationDecl(CIMP);
4004   }
4005 }
4006
4007 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, 
4008                                      const std::string &Name,
4009                                      ValueDecl *VD, bool def) {
4010   assert(BlockByRefDeclNo.count(VD) && 
4011          "RewriteByRefString: ByRef decl missing");
4012   if (def)
4013     ResultStr += "struct ";
4014   ResultStr += "__Block_byref_" + Name + 
4015     "_" + utostr(BlockByRefDeclNo[VD]) ;
4016 }
4017
4018 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4019   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4020     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4021   return false;
4022 }
4023
4024 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4025                                                    StringRef funcName,
4026                                                    std::string Tag) {
4027   const FunctionType *AFT = CE->getFunctionType();
4028   QualType RT = AFT->getResultType();
4029   std::string StructRef = "struct " + Tag;
4030   SourceLocation BlockLoc = CE->getExprLoc();
4031   std::string S;
4032   ConvertSourceLocationToLineDirective(BlockLoc, S);
4033   
4034   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4035          funcName.str() + "_block_func_" + utostr(i);
4036
4037   BlockDecl *BD = CE->getBlockDecl();
4038
4039   if (isa<FunctionNoProtoType>(AFT)) {
4040     // No user-supplied arguments. Still need to pass in a pointer to the
4041     // block (to reference imported block decl refs).
4042     S += "(" + StructRef + " *__cself)";
4043   } else if (BD->param_empty()) {
4044     S += "(" + StructRef + " *__cself)";
4045   } else {
4046     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4047     assert(FT && "SynthesizeBlockFunc: No function proto");
4048     S += '(';
4049     // first add the implicit argument.
4050     S += StructRef + " *__cself, ";
4051     std::string ParamStr;
4052     for (BlockDecl::param_iterator AI = BD->param_begin(),
4053          E = BD->param_end(); AI != E; ++AI) {
4054       if (AI != BD->param_begin()) S += ", ";
4055       ParamStr = (*AI)->getNameAsString();
4056       QualType QT = (*AI)->getType();
4057       (void)convertBlockPointerToFunctionPointer(QT);
4058       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4059       S += ParamStr;
4060     }
4061     if (FT->isVariadic()) {
4062       if (!BD->param_empty()) S += ", ";
4063       S += "...";
4064     }
4065     S += ')';
4066   }
4067   S += " {\n";
4068
4069   // Create local declarations to avoid rewriting all closure decl ref exprs.
4070   // First, emit a declaration for all "by ref" decls.
4071   for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4072        E = BlockByRefDecls.end(); I != E; ++I) {
4073     S += "  ";
4074     std::string Name = (*I)->getNameAsString();
4075     std::string TypeString;
4076     RewriteByRefString(TypeString, Name, (*I));
4077     TypeString += " *";
4078     Name = TypeString + Name;
4079     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4080   }
4081   // Next, emit a declaration for all "by copy" declarations.
4082   for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4083        E = BlockByCopyDecls.end(); I != E; ++I) {
4084     S += "  ";
4085     // Handle nested closure invocation. For example:
4086     //
4087     //   void (^myImportedClosure)(void);
4088     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4089     //
4090     //   void (^anotherClosure)(void);
4091     //   anotherClosure = ^(void) {
4092     //     myImportedClosure(); // import and invoke the closure
4093     //   };
4094     //
4095     if (isTopLevelBlockPointerType((*I)->getType())) {
4096       RewriteBlockPointerTypeVariable(S, (*I));
4097       S += " = (";
4098       RewriteBlockPointerType(S, (*I)->getType());
4099       S += ")";
4100       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4101     }
4102     else {
4103       std::string Name = (*I)->getNameAsString();
4104       QualType QT = (*I)->getType();
4105       if (HasLocalVariableExternalStorage(*I))
4106         QT = Context->getPointerType(QT);
4107       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4108       S += Name + " = __cself->" + 
4109                               (*I)->getNameAsString() + "; // bound by copy\n";
4110     }
4111   }
4112   std::string RewrittenStr = RewrittenBlockExprs[CE];
4113   const char *cstr = RewrittenStr.c_str();
4114   while (*cstr++ != '{') ;
4115   S += cstr;
4116   S += "\n";
4117   return S;
4118 }
4119
4120 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4121                                                    StringRef funcName,
4122                                                    std::string Tag) {
4123   std::string StructRef = "struct " + Tag;
4124   std::string S = "static void __";
4125
4126   S += funcName;
4127   S += "_block_copy_" + utostr(i);
4128   S += "(" + StructRef;
4129   S += "*dst, " + StructRef;
4130   S += "*src) {";
4131   for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4132       E = ImportedBlockDecls.end(); I != E; ++I) {
4133     ValueDecl *VD = (*I);
4134     S += "_Block_object_assign((void*)&dst->";
4135     S += (*I)->getNameAsString();
4136     S += ", (void*)src->";
4137     S += (*I)->getNameAsString();
4138     if (BlockByRefDeclsPtrSet.count((*I)))
4139       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4140     else if (VD->getType()->isBlockPointerType())
4141       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4142     else
4143       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4144   }
4145   S += "}\n";
4146   
4147   S += "\nstatic void __";
4148   S += funcName;
4149   S += "_block_dispose_" + utostr(i);
4150   S += "(" + StructRef;
4151   S += "*src) {";
4152   for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4153       E = ImportedBlockDecls.end(); I != E; ++I) {
4154     ValueDecl *VD = (*I);
4155     S += "_Block_object_dispose((void*)src->";
4156     S += (*I)->getNameAsString();
4157     if (BlockByRefDeclsPtrSet.count((*I)))
4158       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4159     else if (VD->getType()->isBlockPointerType())
4160       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4161     else
4162       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4163   }
4164   S += "}\n";
4165   return S;
4166 }
4167
4168 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, 
4169                                              std::string Desc) {
4170   std::string S = "\nstruct " + Tag;
4171   std::string Constructor = "  " + Tag;
4172
4173   S += " {\n  struct __block_impl impl;\n";
4174   S += "  struct " + Desc;
4175   S += "* Desc;\n";
4176
4177   Constructor += "(void *fp, "; // Invoke function pointer.
4178   Constructor += "struct " + Desc; // Descriptor pointer.
4179   Constructor += " *desc";
4180
4181   if (BlockDeclRefs.size()) {
4182     // Output all "by copy" declarations.
4183     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4184          E = BlockByCopyDecls.end(); I != E; ++I) {
4185       S += "  ";
4186       std::string FieldName = (*I)->getNameAsString();
4187       std::string ArgName = "_" + FieldName;
4188       // Handle nested closure invocation. For example:
4189       //
4190       //   void (^myImportedBlock)(void);
4191       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4192       //
4193       //   void (^anotherBlock)(void);
4194       //   anotherBlock = ^(void) {
4195       //     myImportedBlock(); // import and invoke the closure
4196       //   };
4197       //
4198       if (isTopLevelBlockPointerType((*I)->getType())) {
4199         S += "struct __block_impl *";
4200         Constructor += ", void *" + ArgName;
4201       } else {
4202         QualType QT = (*I)->getType();
4203         if (HasLocalVariableExternalStorage(*I))
4204           QT = Context->getPointerType(QT);
4205         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4206         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4207         Constructor += ", " + ArgName;
4208       }
4209       S += FieldName + ";\n";
4210     }
4211     // Output all "by ref" declarations.
4212     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4213          E = BlockByRefDecls.end(); I != E; ++I) {
4214       S += "  ";
4215       std::string FieldName = (*I)->getNameAsString();
4216       std::string ArgName = "_" + FieldName;
4217       {
4218         std::string TypeString;
4219         RewriteByRefString(TypeString, FieldName, (*I));
4220         TypeString += " *";
4221         FieldName = TypeString + FieldName;
4222         ArgName = TypeString + ArgName;
4223         Constructor += ", " + ArgName;
4224       }
4225       S += FieldName + "; // by ref\n";
4226     }
4227     // Finish writing the constructor.
4228     Constructor += ", int flags=0)";
4229     // Initialize all "by copy" arguments.
4230     bool firsTime = true;
4231     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4232          E = BlockByCopyDecls.end(); I != E; ++I) {
4233       std::string Name = (*I)->getNameAsString();
4234         if (firsTime) {
4235           Constructor += " : ";
4236           firsTime = false;
4237         }
4238         else
4239           Constructor += ", ";
4240         if (isTopLevelBlockPointerType((*I)->getType()))
4241           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4242         else
4243           Constructor += Name + "(_" + Name + ")";
4244     }
4245     // Initialize all "by ref" arguments.
4246     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4247          E = BlockByRefDecls.end(); I != E; ++I) {
4248       std::string Name = (*I)->getNameAsString();
4249       if (firsTime) {
4250         Constructor += " : ";
4251         firsTime = false;
4252       }
4253       else
4254         Constructor += ", ";
4255       Constructor += Name + "(_" + Name + "->__forwarding)";
4256     }
4257     
4258     Constructor += " {\n";
4259     if (GlobalVarDecl)
4260       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4261     else
4262       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4263     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4264
4265     Constructor += "    Desc = desc;\n";
4266   } else {
4267     // Finish writing the constructor.
4268     Constructor += ", int flags=0) {\n";
4269     if (GlobalVarDecl)
4270       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4271     else
4272       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4273     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4274     Constructor += "    Desc = desc;\n";
4275   }
4276   Constructor += "  ";
4277   Constructor += "}\n";
4278   S += Constructor;
4279   S += "};\n";
4280   return S;
4281 }
4282
4283 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, 
4284                                                    std::string ImplTag, int i,
4285                                                    StringRef FunName,
4286                                                    unsigned hasCopy) {
4287   std::string S = "\nstatic struct " + DescTag;
4288   
4289   S += " {\n  size_t reserved;\n";
4290   S += "  size_t Block_size;\n";
4291   if (hasCopy) {
4292     S += "  void (*copy)(struct ";
4293     S += ImplTag; S += "*, struct ";
4294     S += ImplTag; S += "*);\n";
4295     
4296     S += "  void (*dispose)(struct ";
4297     S += ImplTag; S += "*);\n";
4298   }
4299   S += "} ";
4300
4301   S += DescTag + "_DATA = { 0, sizeof(struct ";
4302   S += ImplTag + ")";
4303   if (hasCopy) {
4304     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4305     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4306   }
4307   S += "};\n";
4308   return S;
4309 }
4310
4311 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4312                                           StringRef FunName) {
4313   bool RewriteSC = (GlobalVarDecl &&
4314                     !Blocks.empty() &&
4315                     GlobalVarDecl->getStorageClass() == SC_Static &&
4316                     GlobalVarDecl->getType().getCVRQualifiers());
4317   if (RewriteSC) {
4318     std::string SC(" void __");
4319     SC += GlobalVarDecl->getNameAsString();
4320     SC += "() {}";
4321     InsertText(FunLocStart, SC);
4322   }
4323   
4324   // Insert closures that were part of the function.
4325   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4326     CollectBlockDeclRefInfo(Blocks[i]);
4327     // Need to copy-in the inner copied-in variables not actually used in this
4328     // block.
4329     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4330       DeclRefExpr *Exp = InnerDeclRefs[count++];
4331       ValueDecl *VD = Exp->getDecl();
4332       BlockDeclRefs.push_back(Exp);
4333       if (!VD->hasAttr<BlocksAttr>()) {
4334         if (!BlockByCopyDeclsPtrSet.count(VD)) {
4335           BlockByCopyDeclsPtrSet.insert(VD);
4336           BlockByCopyDecls.push_back(VD);
4337         }
4338         continue;
4339       }
4340
4341       if (!BlockByRefDeclsPtrSet.count(VD)) {
4342         BlockByRefDeclsPtrSet.insert(VD);
4343         BlockByRefDecls.push_back(VD);
4344       }
4345
4346       // imported objects in the inner blocks not used in the outer
4347       // blocks must be copied/disposed in the outer block as well.
4348       if (VD->getType()->isObjCObjectPointerType() || 
4349           VD->getType()->isBlockPointerType())
4350         ImportedBlockDecls.insert(VD);
4351     }
4352
4353     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4354     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4355
4356     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4357
4358     InsertText(FunLocStart, CI);
4359
4360     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4361
4362     InsertText(FunLocStart, CF);
4363
4364     if (ImportedBlockDecls.size()) {
4365       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4366       InsertText(FunLocStart, HF);
4367     }
4368     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4369                                                ImportedBlockDecls.size() > 0);
4370     InsertText(FunLocStart, BD);
4371
4372     BlockDeclRefs.clear();
4373     BlockByRefDecls.clear();
4374     BlockByRefDeclsPtrSet.clear();
4375     BlockByCopyDecls.clear();
4376     BlockByCopyDeclsPtrSet.clear();
4377     ImportedBlockDecls.clear();
4378   }
4379   if (RewriteSC) {
4380     // Must insert any 'const/volatile/static here. Since it has been
4381     // removed as result of rewriting of block literals.
4382     std::string SC;
4383     if (GlobalVarDecl->getStorageClass() == SC_Static)
4384       SC = "static ";
4385     if (GlobalVarDecl->getType().isConstQualified())
4386       SC += "const ";
4387     if (GlobalVarDecl->getType().isVolatileQualified())
4388       SC += "volatile ";
4389     if (GlobalVarDecl->getType().isRestrictQualified())
4390       SC += "restrict ";
4391     InsertText(FunLocStart, SC);
4392   }
4393   if (GlobalConstructionExp) {
4394     // extra fancy dance for global literal expression.
4395     
4396     // Always the latest block expression on the block stack.
4397     std::string Tag = "__";
4398     Tag += FunName;
4399     Tag += "_block_impl_";
4400     Tag += utostr(Blocks.size()-1);
4401     std::string globalBuf = "static ";
4402     globalBuf += Tag; globalBuf += " ";
4403     std::string SStr;
4404   
4405     llvm::raw_string_ostream constructorExprBuf(SStr);
4406     GlobalConstructionExp->printPretty(constructorExprBuf, 0,
4407                                          PrintingPolicy(LangOpts));
4408     globalBuf += constructorExprBuf.str();
4409     globalBuf += ";\n";
4410     InsertText(FunLocStart, globalBuf);
4411     GlobalConstructionExp = 0;
4412   }
4413
4414   Blocks.clear();
4415   InnerDeclRefsCount.clear();
4416   InnerDeclRefs.clear();
4417   RewrittenBlockExprs.clear();
4418 }
4419
4420 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4421   SourceLocation FunLocStart = 
4422     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4423                       : FD->getTypeSpecStartLoc();
4424   StringRef FuncName = FD->getName();
4425
4426   SynthesizeBlockLiterals(FunLocStart, FuncName);
4427 }
4428
4429 static void BuildUniqueMethodName(std::string &Name,
4430                                   ObjCMethodDecl *MD) {
4431   ObjCInterfaceDecl *IFace = MD->getClassInterface();
4432   Name = IFace->getName();
4433   Name += "__" + MD->getSelector().getAsString();
4434   // Convert colons to underscores.
4435   std::string::size_type loc = 0;
4436   while ((loc = Name.find(":", loc)) != std::string::npos)
4437     Name.replace(loc, 1, "_");
4438 }
4439
4440 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4441   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4442   //SourceLocation FunLocStart = MD->getLocStart();
4443   SourceLocation FunLocStart = MD->getLocStart();
4444   std::string FuncName;
4445   BuildUniqueMethodName(FuncName, MD);
4446   SynthesizeBlockLiterals(FunLocStart, FuncName);
4447 }
4448
4449 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4450   for (Stmt::child_range CI = S->children(); CI; ++CI)
4451     if (*CI) {
4452       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4453         GetBlockDeclRefExprs(CBE->getBody());
4454       else
4455         GetBlockDeclRefExprs(*CI);
4456     }
4457   // Handle specific things.
4458   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4459     if (DRE->refersToEnclosingLocal()) {
4460       // FIXME: Handle enums.
4461       if (!isa<FunctionDecl>(DRE->getDecl()))
4462         BlockDeclRefs.push_back(DRE);
4463       if (HasLocalVariableExternalStorage(DRE->getDecl()))
4464         BlockDeclRefs.push_back(DRE);
4465     }
4466   }
4467   
4468   return;
4469 }
4470
4471 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S, 
4472                 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
4473                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4474   for (Stmt::child_range CI = S->children(); CI; ++CI)
4475     if (*CI) {
4476       if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4477         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4478         GetInnerBlockDeclRefExprs(CBE->getBody(),
4479                                   InnerBlockDeclRefs,
4480                                   InnerContexts);
4481       }
4482       else
4483         GetInnerBlockDeclRefExprs(*CI,
4484                                   InnerBlockDeclRefs,
4485                                   InnerContexts);
4486
4487     }
4488   // Handle specific things.
4489   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4490     if (DRE->refersToEnclosingLocal()) {
4491       if (!isa<FunctionDecl>(DRE->getDecl()) &&
4492           !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4493         InnerBlockDeclRefs.push_back(DRE);
4494       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4495         if (Var->isFunctionOrMethodVarDecl())
4496           ImportedLocalExternalDecls.insert(Var);
4497     }
4498   }
4499   
4500   return;
4501 }
4502
4503 /// convertObjCTypeToCStyleType - This routine converts such objc types
4504 /// as qualified objects, and blocks to their closest c/c++ types that
4505 /// it can. It returns true if input type was modified.
4506 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4507   QualType oldT = T;
4508   convertBlockPointerToFunctionPointer(T);
4509   if (T->isFunctionPointerType()) {
4510     QualType PointeeTy;
4511     if (const PointerType* PT = T->getAs<PointerType>()) {
4512       PointeeTy = PT->getPointeeType();
4513       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4514         T = convertFunctionTypeOfBlocks(FT);
4515         T = Context->getPointerType(T);
4516       }
4517     }
4518   }
4519   
4520   convertToUnqualifiedObjCType(T);
4521   return T != oldT;
4522 }
4523
4524 /// convertFunctionTypeOfBlocks - This routine converts a function type
4525 /// whose result type may be a block pointer or whose argument type(s)
4526 /// might be block pointers to an equivalent function type replacing
4527 /// all block pointers to function pointers.
4528 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4529   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4530   // FTP will be null for closures that don't take arguments.
4531   // Generate a funky cast.
4532   SmallVector<QualType, 8> ArgTypes;
4533   QualType Res = FT->getResultType();
4534   bool modified = convertObjCTypeToCStyleType(Res);
4535   
4536   if (FTP) {
4537     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4538          E = FTP->arg_type_end(); I && (I != E); ++I) {
4539       QualType t = *I;
4540       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4541       if (convertObjCTypeToCStyleType(t))
4542         modified = true;
4543       ArgTypes.push_back(t);
4544     }
4545   }
4546   QualType FuncType;
4547   if (modified)
4548     FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4549   else FuncType = QualType(FT, 0);
4550   return FuncType;
4551 }
4552
4553 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4554   // Navigate to relevant type information.
4555   const BlockPointerType *CPT = 0;
4556
4557   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4558     CPT = DRE->getType()->getAs<BlockPointerType>();
4559   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4560     CPT = MExpr->getType()->getAs<BlockPointerType>();
4561   } 
4562   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4563     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4564   }
4565   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) 
4566     CPT = IEXPR->getType()->getAs<BlockPointerType>();
4567   else if (const ConditionalOperator *CEXPR = 
4568             dyn_cast<ConditionalOperator>(BlockExp)) {
4569     Expr *LHSExp = CEXPR->getLHS();
4570     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4571     Expr *RHSExp = CEXPR->getRHS();
4572     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4573     Expr *CONDExp = CEXPR->getCond();
4574     ConditionalOperator *CondExpr =
4575       new (Context) ConditionalOperator(CONDExp,
4576                                       SourceLocation(), cast<Expr>(LHSStmt),
4577                                       SourceLocation(), cast<Expr>(RHSStmt),
4578                                       Exp->getType(), VK_RValue, OK_Ordinary);
4579     return CondExpr;
4580   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4581     CPT = IRE->getType()->getAs<BlockPointerType>();
4582   } else if (const PseudoObjectExpr *POE
4583                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4584     CPT = POE->getType()->castAs<BlockPointerType>();
4585   } else {
4586     assert(1 && "RewriteBlockClass: Bad type");
4587   }
4588   assert(CPT && "RewriteBlockClass: Bad type");
4589   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4590   assert(FT && "RewriteBlockClass: Bad type");
4591   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4592   // FTP will be null for closures that don't take arguments.
4593
4594   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4595                                       SourceLocation(), SourceLocation(),
4596                                       &Context->Idents.get("__block_impl"));
4597   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4598
4599   // Generate a funky cast.
4600   SmallVector<QualType, 8> ArgTypes;
4601
4602   // Push the block argument type.
4603   ArgTypes.push_back(PtrBlock);
4604   if (FTP) {
4605     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4606          E = FTP->arg_type_end(); I && (I != E); ++I) {
4607       QualType t = *I;
4608       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609       if (!convertBlockPointerToFunctionPointer(t))
4610         convertToUnqualifiedObjCType(t);
4611       ArgTypes.push_back(t);
4612     }
4613   }
4614   // Now do the pointer to function cast.
4615   QualType PtrToFuncCastType
4616     = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4617
4618   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4619
4620   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4621                                                CK_BitCast,
4622                                                const_cast<Expr*>(BlockExp));
4623   // Don't forget the parens to enforce the proper binding.
4624   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4625                                           BlkCast);
4626   //PE->dump();
4627
4628   FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4629                                     SourceLocation(),
4630                                     &Context->Idents.get("FuncPtr"),
4631                                     Context->VoidPtrTy, 0,
4632                                     /*BitWidth=*/0, /*Mutable=*/true,
4633                                     ICIS_NoInit);
4634   MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4635                                             FD->getType(), VK_LValue,
4636                                             OK_Ordinary);
4637
4638   
4639   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4640                                                 CK_BitCast, ME);
4641   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4642
4643   SmallVector<Expr*, 8> BlkExprs;
4644   // Add the implicit argument.
4645   BlkExprs.push_back(BlkCast);
4646   // Add the user arguments.
4647   for (CallExpr::arg_iterator I = Exp->arg_begin(),
4648        E = Exp->arg_end(); I != E; ++I) {
4649     BlkExprs.push_back(*I);
4650   }
4651   CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4652                                         Exp->getType(), VK_RValue,
4653                                         SourceLocation());
4654   return CE;
4655 }
4656
4657 // We need to return the rewritten expression to handle cases where the
4658 // DeclRefExpr is embedded in another expression being rewritten.
4659 // For example:
4660 //
4661 // int main() {
4662 //    __block Foo *f;
4663 //    __block int i;
4664 //
4665 //    void (^myblock)() = ^() {
4666 //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4667 //        i = 77;
4668 //    };
4669 //}
4670 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4671   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
4672   // for each DeclRefExp where BYREFVAR is name of the variable.
4673   ValueDecl *VD = DeclRefExp->getDecl();
4674   bool isArrow = DeclRefExp->refersToEnclosingLocal();
4675   
4676   FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4677                                     SourceLocation(),
4678                                     &Context->Idents.get("__forwarding"), 
4679                                     Context->VoidPtrTy, 0,
4680                                     /*BitWidth=*/0, /*Mutable=*/true,
4681                                     ICIS_NoInit);
4682   MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4683                                             FD, SourceLocation(),
4684                                             FD->getType(), VK_LValue,
4685                                             OK_Ordinary);
4686
4687   StringRef Name = VD->getName();
4688   FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4689                          &Context->Idents.get(Name), 
4690                          Context->VoidPtrTy, 0,
4691                          /*BitWidth=*/0, /*Mutable=*/true,
4692                          ICIS_NoInit);
4693   ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4694                                 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4695   
4696   
4697   
4698   // Need parens to enforce precedence.
4699   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), 
4700                                           DeclRefExp->getExprLoc(), 
4701                                           ME);
4702   ReplaceStmt(DeclRefExp, PE);
4703   return PE;
4704 }
4705
4706 // Rewrites the imported local variable V with external storage 
4707 // (static, extern, etc.) as *V
4708 //
4709 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4710   ValueDecl *VD = DRE->getDecl();
4711   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4712     if (!ImportedLocalExternalDecls.count(Var))
4713       return DRE;
4714   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4715                                           VK_LValue, OK_Ordinary,
4716                                           DRE->getLocation());
4717   // Need parens to enforce precedence.
4718   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
4719                                           Exp);
4720   ReplaceStmt(DRE, PE);
4721   return PE;
4722 }
4723
4724 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4725   SourceLocation LocStart = CE->getLParenLoc();
4726   SourceLocation LocEnd = CE->getRParenLoc();
4727
4728   // Need to avoid trying to rewrite synthesized casts.
4729   if (LocStart.isInvalid())
4730     return;
4731   // Need to avoid trying to rewrite casts contained in macros.
4732   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4733     return;
4734
4735   const char *startBuf = SM->getCharacterData(LocStart);
4736   const char *endBuf = SM->getCharacterData(LocEnd);
4737   QualType QT = CE->getType();
4738   const Type* TypePtr = QT->getAs<Type>();
4739   if (isa<TypeOfExprType>(TypePtr)) {
4740     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4741     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4742     std::string TypeAsString = "(";
4743     RewriteBlockPointerType(TypeAsString, QT);
4744     TypeAsString += ")";
4745     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4746     return;
4747   }
4748   // advance the location to startArgList.
4749   const char *argPtr = startBuf;
4750
4751   while (*argPtr++ && (argPtr < endBuf)) {
4752     switch (*argPtr) {
4753     case '^':
4754       // Replace the '^' with '*'.
4755       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4756       ReplaceText(LocStart, 1, "*");
4757       break;
4758     }
4759   }
4760   return;
4761 }
4762
4763 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4764   CastKind CastKind = IC->getCastKind();
4765   if (CastKind != CK_BlockPointerToObjCPointerCast &&
4766       CastKind != CK_AnyPointerToBlockPointerCast)
4767     return;
4768   
4769   QualType QT = IC->getType();
4770   (void)convertBlockPointerToFunctionPointer(QT);
4771   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4772   std::string Str = "(";
4773   Str += TypeString;
4774   Str += ")";
4775   InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4776
4777   return;
4778 }
4779
4780 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4781   SourceLocation DeclLoc = FD->getLocation();
4782   unsigned parenCount = 0;
4783
4784   // We have 1 or more arguments that have closure pointers.
4785   const char *startBuf = SM->getCharacterData(DeclLoc);
4786   const char *startArgList = strchr(startBuf, '(');
4787
4788   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4789
4790   parenCount++;
4791   // advance the location to startArgList.
4792   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4793   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4794
4795   const char *argPtr = startArgList;
4796
4797   while (*argPtr++ && parenCount) {
4798     switch (*argPtr) {
4799     case '^':
4800       // Replace the '^' with '*'.
4801       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4802       ReplaceText(DeclLoc, 1, "*");
4803       break;
4804     case '(':
4805       parenCount++;
4806       break;
4807     case ')':
4808       parenCount--;
4809       break;
4810     }
4811   }
4812   return;
4813 }
4814
4815 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4816   const FunctionProtoType *FTP;
4817   const PointerType *PT = QT->getAs<PointerType>();
4818   if (PT) {
4819     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4820   } else {
4821     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4822     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4823     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4824   }
4825   if (FTP) {
4826     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4827          E = FTP->arg_type_end(); I != E; ++I)
4828       if (isTopLevelBlockPointerType(*I))
4829         return true;
4830   }
4831   return false;
4832 }
4833
4834 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4835   const FunctionProtoType *FTP;
4836   const PointerType *PT = QT->getAs<PointerType>();
4837   if (PT) {
4838     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4839   } else {
4840     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4841     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4842     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4843   }
4844   if (FTP) {
4845     for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4846          E = FTP->arg_type_end(); I != E; ++I) {
4847       if ((*I)->isObjCQualifiedIdType())
4848         return true;
4849       if ((*I)->isObjCObjectPointerType() &&
4850           (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4851         return true;
4852     }
4853         
4854   }
4855   return false;
4856 }
4857
4858 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4859                                      const char *&RParen) {
4860   const char *argPtr = strchr(Name, '(');
4861   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4862
4863   LParen = argPtr; // output the start.
4864   argPtr++; // skip past the left paren.
4865   unsigned parenCount = 1;
4866
4867   while (*argPtr && parenCount) {
4868     switch (*argPtr) {
4869     case '(': parenCount++; break;
4870     case ')': parenCount--; break;
4871     default: break;
4872     }
4873     if (parenCount) argPtr++;
4874   }
4875   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4876   RParen = argPtr; // output the end
4877 }
4878
4879 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4880   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4881     RewriteBlockPointerFunctionArgs(FD);
4882     return;
4883   }
4884   // Handle Variables and Typedefs.
4885   SourceLocation DeclLoc = ND->getLocation();
4886   QualType DeclT;
4887   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4888     DeclT = VD->getType();
4889   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4890     DeclT = TDD->getUnderlyingType();
4891   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4892     DeclT = FD->getType();
4893   else
4894     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4895
4896   const char *startBuf = SM->getCharacterData(DeclLoc);
4897   const char *endBuf = startBuf;
4898   // scan backward (from the decl location) for the end of the previous decl.
4899   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4900     startBuf--;
4901   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4902   std::string buf;
4903   unsigned OrigLength=0;
4904   // *startBuf != '^' if we are dealing with a pointer to function that
4905   // may take block argument types (which will be handled below).
4906   if (*startBuf == '^') {
4907     // Replace the '^' with '*', computing a negative offset.
4908     buf = '*';
4909     startBuf++;
4910     OrigLength++;
4911   }
4912   while (*startBuf != ')') {
4913     buf += *startBuf;
4914     startBuf++;
4915     OrigLength++;
4916   }
4917   buf += ')';
4918   OrigLength++;
4919   
4920   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4921       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4922     // Replace the '^' with '*' for arguments.
4923     // Replace id<P> with id/*<>*/
4924     DeclLoc = ND->getLocation();
4925     startBuf = SM->getCharacterData(DeclLoc);
4926     const char *argListBegin, *argListEnd;
4927     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4928     while (argListBegin < argListEnd) {
4929       if (*argListBegin == '^')
4930         buf += '*';
4931       else if (*argListBegin ==  '<') {
4932         buf += "/*"; 
4933         buf += *argListBegin++;
4934         OrigLength++;
4935         while (*argListBegin != '>') {
4936           buf += *argListBegin++;
4937           OrigLength++;
4938         }
4939         buf += *argListBegin;
4940         buf += "*/";
4941       }
4942       else
4943         buf += *argListBegin;
4944       argListBegin++;
4945       OrigLength++;
4946     }
4947     buf += ')';
4948     OrigLength++;
4949   }
4950   ReplaceText(Start, OrigLength, buf);
4951   
4952   return;
4953 }
4954
4955
4956 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4957 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4958 ///                    struct Block_byref_id_object *src) {
4959 ///  _Block_object_assign (&_dest->object, _src->object, 
4960 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4961 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4962 ///  _Block_object_assign(&_dest->object, _src->object, 
4963 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4964 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4965 /// }
4966 /// And:
4967 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4968 ///  _Block_object_dispose(_src->object, 
4969 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4970 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4971 ///  _Block_object_dispose(_src->object, 
4972 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4973 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4974 /// }
4975
4976 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4977                                                           int flag) {
4978   std::string S;
4979   if (CopyDestroyCache.count(flag))
4980     return S;
4981   CopyDestroyCache.insert(flag);
4982   S = "static void __Block_byref_id_object_copy_";
4983   S += utostr(flag);
4984   S += "(void *dst, void *src) {\n";
4985   
4986   // offset into the object pointer is computed as:
4987   // void * + void* + int + int + void* + void *
4988   unsigned IntSize = 
4989   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4990   unsigned VoidPtrSize = 
4991   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4992   
4993   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4994   S += " _Block_object_assign((char*)dst + ";
4995   S += utostr(offset);
4996   S += ", *(void * *) ((char*)src + ";
4997   S += utostr(offset);
4998   S += "), ";
4999   S += utostr(flag);
5000   S += ");\n}\n";
5001   
5002   S += "static void __Block_byref_id_object_dispose_";
5003   S += utostr(flag);
5004   S += "(void *src) {\n";
5005   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5006   S += utostr(offset);
5007   S += "), ";
5008   S += utostr(flag);
5009   S += ");\n}\n";
5010   return S;
5011 }
5012
5013 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5014 /// the declaration into:
5015 /// struct __Block_byref_ND {
5016 /// void *__isa;                  // NULL for everything except __weak pointers
5017 /// struct __Block_byref_ND *__forwarding;
5018 /// int32_t __flags;
5019 /// int32_t __size;
5020 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5021 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5022 /// typex ND;
5023 /// };
5024 ///
5025 /// It then replaces declaration of ND variable with:
5026 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, 
5027 ///                               __size=sizeof(struct __Block_byref_ND), 
5028 ///                               ND=initializer-if-any};
5029 ///
5030 ///
5031 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5032                                         bool lastDecl) {
5033   int flag = 0;
5034   int isa = 0;
5035   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5036   if (DeclLoc.isInvalid())
5037     // If type location is missing, it is because of missing type (a warning).
5038     // Use variable's location which is good for this case.
5039     DeclLoc = ND->getLocation();
5040   const char *startBuf = SM->getCharacterData(DeclLoc);
5041   SourceLocation X = ND->getLocEnd();
5042   X = SM->getExpansionLoc(X);
5043   const char *endBuf = SM->getCharacterData(X);
5044   std::string Name(ND->getNameAsString());
5045   std::string ByrefType;
5046   RewriteByRefString(ByrefType, Name, ND, true);
5047   ByrefType += " {\n";
5048   ByrefType += "  void *__isa;\n";
5049   RewriteByRefString(ByrefType, Name, ND);
5050   ByrefType += " *__forwarding;\n";
5051   ByrefType += " int __flags;\n";
5052   ByrefType += " int __size;\n";
5053   // Add void *__Block_byref_id_object_copy; 
5054   // void *__Block_byref_id_object_dispose; if needed.
5055   QualType Ty = ND->getType();
5056   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5057   if (HasCopyAndDispose) {
5058     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5059     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5060   }
5061
5062   QualType T = Ty;
5063   (void)convertBlockPointerToFunctionPointer(T);
5064   T.getAsStringInternal(Name, Context->getPrintingPolicy());
5065     
5066   ByrefType += " " + Name + ";\n";
5067   ByrefType += "};\n";
5068   // Insert this type in global scope. It is needed by helper function.
5069   SourceLocation FunLocStart;
5070   if (CurFunctionDef)
5071      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5072   else {
5073     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5074     FunLocStart = CurMethodDef->getLocStart();
5075   }
5076   InsertText(FunLocStart, ByrefType);
5077   
5078   if (Ty.isObjCGCWeak()) {
5079     flag |= BLOCK_FIELD_IS_WEAK;
5080     isa = 1;
5081   }
5082   if (HasCopyAndDispose) {
5083     flag = BLOCK_BYREF_CALLER;
5084     QualType Ty = ND->getType();
5085     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5086     if (Ty->isBlockPointerType())
5087       flag |= BLOCK_FIELD_IS_BLOCK;
5088     else
5089       flag |= BLOCK_FIELD_IS_OBJECT;
5090     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5091     if (!HF.empty())
5092       InsertText(FunLocStart, HF);
5093   }
5094   
5095   // struct __Block_byref_ND ND = 
5096   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), 
5097   //  initializer-if-any};
5098   bool hasInit = (ND->getInit() != 0);
5099   // FIXME. rewriter does not support __block c++ objects which
5100   // require construction.
5101   if (hasInit)
5102     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5103       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5104       if (CXXDecl && CXXDecl->isDefaultConstructor())
5105         hasInit = false;
5106     }
5107   
5108   unsigned flags = 0;
5109   if (HasCopyAndDispose)
5110     flags |= BLOCK_HAS_COPY_DISPOSE;
5111   Name = ND->getNameAsString();
5112   ByrefType.clear();
5113   RewriteByRefString(ByrefType, Name, ND);
5114   std::string ForwardingCastType("(");
5115   ForwardingCastType += ByrefType + " *)";
5116   ByrefType += " " + Name + " = {(void*)";
5117   ByrefType += utostr(isa);
5118   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5119   ByrefType += utostr(flags);
5120   ByrefType += ", ";
5121   ByrefType += "sizeof(";
5122   RewriteByRefString(ByrefType, Name, ND);
5123   ByrefType += ")";
5124   if (HasCopyAndDispose) {
5125     ByrefType += ", __Block_byref_id_object_copy_";
5126     ByrefType += utostr(flag);
5127     ByrefType += ", __Block_byref_id_object_dispose_";
5128     ByrefType += utostr(flag);
5129   }
5130   
5131   if (!firstDecl) {
5132     // In multiple __block declarations, and for all but 1st declaration,
5133     // find location of the separating comma. This would be start location
5134     // where new text is to be inserted.
5135     DeclLoc = ND->getLocation();
5136     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5137     const char *commaBuf = startDeclBuf;
5138     while (*commaBuf != ',')
5139       commaBuf--;
5140     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5141     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5142     startBuf = commaBuf;
5143   }
5144   
5145   if (!hasInit) {
5146     ByrefType += "};\n";
5147     unsigned nameSize = Name.size();
5148     // for block or function pointer declaration. Name is aleady
5149     // part of the declaration.
5150     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5151       nameSize = 1;
5152     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5153   }
5154   else {
5155     ByrefType += ", ";
5156     SourceLocation startLoc;
5157     Expr *E = ND->getInit();
5158     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5159       startLoc = ECE->getLParenLoc();
5160     else
5161       startLoc = E->getLocStart();
5162     startLoc = SM->getExpansionLoc(startLoc);
5163     endBuf = SM->getCharacterData(startLoc);
5164     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5165
5166     const char separator = lastDecl ? ';' : ',';
5167     const char *startInitializerBuf = SM->getCharacterData(startLoc);
5168     const char *separatorBuf = strchr(startInitializerBuf, separator);
5169     assert((*separatorBuf == separator) && 
5170            "RewriteByRefVar: can't find ';' or ','");
5171     SourceLocation separatorLoc =
5172       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5173     
5174     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5175   }
5176   return;
5177 }
5178
5179 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5180   // Add initializers for any closure decl refs.
5181   GetBlockDeclRefExprs(Exp->getBody());
5182   if (BlockDeclRefs.size()) {
5183     // Unique all "by copy" declarations.
5184     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5185       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5186         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5187           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5188           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5189         }
5190       }
5191     // Unique all "by ref" declarations.
5192     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5193       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5194         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5195           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5196           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5197         }
5198       }
5199     // Find any imported blocks...they will need special attention.
5200     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5201       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5202           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
5203           BlockDeclRefs[i]->getType()->isBlockPointerType())
5204         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5205   }
5206 }
5207
5208 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5209   IdentifierInfo *ID = &Context->Idents.get(name);
5210   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5211   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5212                               SourceLocation(), ID, FType, 0, SC_Extern,
5213                               SC_None, false, false);
5214 }
5215
5216 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5217           const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
5218   
5219   const BlockDecl *block = Exp->getBlockDecl();
5220   
5221   Blocks.push_back(Exp);
5222
5223   CollectBlockDeclRefInfo(Exp);
5224   
5225   // Add inner imported variables now used in current block.
5226  int countOfInnerDecls = 0;
5227   if (!InnerBlockDeclRefs.empty()) {
5228     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5229       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5230       ValueDecl *VD = Exp->getDecl();
5231       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5232       // We need to save the copied-in variables in nested
5233       // blocks because it is needed at the end for some of the API generations.
5234       // See SynthesizeBlockLiterals routine.
5235         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5236         BlockDeclRefs.push_back(Exp);
5237         BlockByCopyDeclsPtrSet.insert(VD);
5238         BlockByCopyDecls.push_back(VD);
5239       }
5240       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5241         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5242         BlockDeclRefs.push_back(Exp);
5243         BlockByRefDeclsPtrSet.insert(VD);
5244         BlockByRefDecls.push_back(VD);
5245       }
5246     }
5247     // Find any imported blocks...they will need special attention.
5248     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5249       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5250           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
5251           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5252         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5253   }
5254   InnerDeclRefsCount.push_back(countOfInnerDecls);
5255   
5256   std::string FuncName;
5257
5258   if (CurFunctionDef)
5259     FuncName = CurFunctionDef->getNameAsString();
5260   else if (CurMethodDef)
5261     BuildUniqueMethodName(FuncName, CurMethodDef);
5262   else if (GlobalVarDecl)
5263     FuncName = std::string(GlobalVarDecl->getNameAsString());
5264
5265   bool GlobalBlockExpr = 
5266     block->getDeclContext()->getRedeclContext()->isFileContext();
5267   
5268   if (GlobalBlockExpr && !GlobalVarDecl) {
5269     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5270     GlobalBlockExpr = false;
5271   }
5272   
5273   std::string BlockNumber = utostr(Blocks.size()-1);
5274
5275   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5276
5277   // Get a pointer to the function type so we can cast appropriately.
5278   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5279   QualType FType = Context->getPointerType(BFT);
5280
5281   FunctionDecl *FD;
5282   Expr *NewRep;
5283
5284   // Simulate a contructor call...
5285   std::string Tag;
5286   
5287   if (GlobalBlockExpr)
5288     Tag = "__global_";
5289   else
5290     Tag = "__";
5291   Tag += FuncName + "_block_impl_" + BlockNumber;
5292   
5293   FD = SynthBlockInitFunctionDecl(Tag);
5294   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5295                                                SourceLocation());
5296
5297   SmallVector<Expr*, 4> InitExprs;
5298
5299   // Initialize the block function.
5300   FD = SynthBlockInitFunctionDecl(Func);
5301   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5302                                                VK_LValue, SourceLocation());
5303   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5304                                                 CK_BitCast, Arg);
5305   InitExprs.push_back(castExpr);
5306
5307   // Initialize the block descriptor.
5308   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5309
5310   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5311                                    SourceLocation(), SourceLocation(),
5312                                    &Context->Idents.get(DescData.c_str()),
5313                                    Context->VoidPtrTy, 0,
5314                                    SC_Static, SC_None);
5315   UnaryOperator *DescRefExpr =
5316     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5317                                                           Context->VoidPtrTy,
5318                                                           VK_LValue,
5319                                                           SourceLocation()), 
5320                                 UO_AddrOf,
5321                                 Context->getPointerType(Context->VoidPtrTy), 
5322                                 VK_RValue, OK_Ordinary,
5323                                 SourceLocation());
5324   InitExprs.push_back(DescRefExpr); 
5325   
5326   // Add initializers for any closure decl refs.
5327   if (BlockDeclRefs.size()) {
5328     Expr *Exp;
5329     // Output all "by copy" declarations.
5330     for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5331          E = BlockByCopyDecls.end(); I != E; ++I) {
5332       if (isObjCType((*I)->getType())) {
5333         // FIXME: Conform to ABI ([[obj retain] autorelease]).
5334         FD = SynthBlockInitFunctionDecl((*I)->getName());
5335         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5336                                         VK_LValue, SourceLocation());
5337         if (HasLocalVariableExternalStorage(*I)) {
5338           QualType QT = (*I)->getType();
5339           QT = Context->getPointerType(QT);
5340           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5341                                             OK_Ordinary, SourceLocation());
5342         }
5343       } else if (isTopLevelBlockPointerType((*I)->getType())) {
5344         FD = SynthBlockInitFunctionDecl((*I)->getName());
5345         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5346                                         VK_LValue, SourceLocation());
5347         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5348                                        CK_BitCast, Arg);
5349       } else {
5350         FD = SynthBlockInitFunctionDecl((*I)->getName());
5351         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5352                                         VK_LValue, SourceLocation());
5353         if (HasLocalVariableExternalStorage(*I)) {
5354           QualType QT = (*I)->getType();
5355           QT = Context->getPointerType(QT);
5356           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5357                                             OK_Ordinary, SourceLocation());
5358         }
5359         
5360       }
5361       InitExprs.push_back(Exp);
5362     }
5363     // Output all "by ref" declarations.
5364     for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5365          E = BlockByRefDecls.end(); I != E; ++I) {
5366       ValueDecl *ND = (*I);
5367       std::string Name(ND->getNameAsString());
5368       std::string RecName;
5369       RewriteByRefString(RecName, Name, ND, true);
5370       IdentifierInfo *II = &Context->Idents.get(RecName.c_str() 
5371                                                 + sizeof("struct"));
5372       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5373                                           SourceLocation(), SourceLocation(),
5374                                           II);
5375       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5376       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5377       
5378       FD = SynthBlockInitFunctionDecl((*I)->getName());
5379       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5380                                       SourceLocation());
5381       bool isNestedCapturedVar = false;
5382       if (block)
5383         for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5384              ce = block->capture_end(); ci != ce; ++ci) {
5385           const VarDecl *variable = ci->getVariable();
5386           if (variable == ND && ci->isNested()) {
5387             assert (ci->isByRef() && 
5388                     "SynthBlockInitExpr - captured block variable is not byref");
5389             isNestedCapturedVar = true;
5390             break;
5391           }
5392         }
5393       // captured nested byref variable has its address passed. Do not take
5394       // its address again.
5395       if (!isNestedCapturedVar)
5396           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5397                                      Context->getPointerType(Exp->getType()),
5398                                      VK_RValue, OK_Ordinary, SourceLocation());
5399       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5400       InitExprs.push_back(Exp);
5401     }
5402   }
5403   if (ImportedBlockDecls.size()) {
5404     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5405     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5406     unsigned IntSize = 
5407       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5408     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), 
5409                                            Context->IntTy, SourceLocation());
5410     InitExprs.push_back(FlagExp);
5411   }
5412   NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5413                                   FType, VK_LValue, SourceLocation());
5414   
5415   if (GlobalBlockExpr) {
5416     assert (GlobalConstructionExp == 0 && 
5417             "SynthBlockInitExpr - GlobalConstructionExp must be null");
5418     GlobalConstructionExp = NewRep;
5419     NewRep = DRE;
5420   }
5421   
5422   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5423                              Context->getPointerType(NewRep->getType()),
5424                              VK_RValue, OK_Ordinary, SourceLocation());
5425   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5426                                     NewRep);
5427   BlockDeclRefs.clear();
5428   BlockByRefDecls.clear();
5429   BlockByRefDeclsPtrSet.clear();
5430   BlockByCopyDecls.clear();
5431   BlockByCopyDeclsPtrSet.clear();
5432   ImportedBlockDecls.clear();
5433   return NewRep;
5434 }
5435
5436 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5437   if (const ObjCForCollectionStmt * CS = 
5438       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5439         return CS->getElement() == DS;
5440   return false;
5441 }
5442
5443 //===----------------------------------------------------------------------===//
5444 // Function Body / Expression rewriting
5445 //===----------------------------------------------------------------------===//
5446
5447 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5448   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5449       isa<DoStmt>(S) || isa<ForStmt>(S))
5450     Stmts.push_back(S);
5451   else if (isa<ObjCForCollectionStmt>(S)) {
5452     Stmts.push_back(S);
5453     ObjCBcLabelNo.push_back(++BcLabelCount);
5454   }
5455
5456   // Pseudo-object operations and ivar references need special
5457   // treatment because we're going to recursively rewrite them.
5458   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5459     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5460       return RewritePropertyOrImplicitSetter(PseudoOp);
5461     } else {
5462       return RewritePropertyOrImplicitGetter(PseudoOp);
5463     }
5464   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5465     return RewriteObjCIvarRefExpr(IvarRefExpr);
5466   }
5467
5468   SourceRange OrigStmtRange = S->getSourceRange();
5469
5470   // Perform a bottom up rewrite of all children.
5471   for (Stmt::child_range CI = S->children(); CI; ++CI)
5472     if (*CI) {
5473       Stmt *childStmt = (*CI);
5474       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5475       if (newStmt) {
5476         *CI = newStmt;
5477       }
5478     }
5479
5480   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5481     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5482     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5483     InnerContexts.insert(BE->getBlockDecl());
5484     ImportedLocalExternalDecls.clear();
5485     GetInnerBlockDeclRefExprs(BE->getBody(),
5486                               InnerBlockDeclRefs, InnerContexts);
5487     // Rewrite the block body in place.
5488     Stmt *SaveCurrentBody = CurrentBody;
5489     CurrentBody = BE->getBody();
5490     PropParentMap = 0;
5491     // block literal on rhs of a property-dot-sytax assignment
5492     // must be replaced by its synthesize ast so getRewrittenText
5493     // works as expected. In this case, what actually ends up on RHS
5494     // is the blockTranscribed which is the helper function for the
5495     // block literal; as in: self.c = ^() {[ace ARR];};
5496     bool saveDisableReplaceStmt = DisableReplaceStmt;
5497     DisableReplaceStmt = false;
5498     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5499     DisableReplaceStmt = saveDisableReplaceStmt;
5500     CurrentBody = SaveCurrentBody;
5501     PropParentMap = 0;
5502     ImportedLocalExternalDecls.clear();
5503     // Now we snarf the rewritten text and stash it away for later use.
5504     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5505     RewrittenBlockExprs[BE] = Str;
5506
5507     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5508                             
5509     //blockTranscribed->dump();
5510     ReplaceStmt(S, blockTranscribed);
5511     return blockTranscribed;
5512   }
5513   // Handle specific things.
5514   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5515     return RewriteAtEncode(AtEncode);
5516
5517   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5518     return RewriteAtSelector(AtSelector);
5519
5520   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5521     return RewriteObjCStringLiteral(AtString);
5522   
5523   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5524     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5525   
5526   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5527     return RewriteObjCBoxedExpr(BoxedExpr);
5528   
5529   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5530     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5531   
5532   if (ObjCDictionaryLiteral *DictionaryLitExpr = 
5533         dyn_cast<ObjCDictionaryLiteral>(S))
5534     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5535
5536   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5537 #if 0
5538     // Before we rewrite it, put the original message expression in a comment.
5539     SourceLocation startLoc = MessExpr->getLocStart();
5540     SourceLocation endLoc = MessExpr->getLocEnd();
5541
5542     const char *startBuf = SM->getCharacterData(startLoc);
5543     const char *endBuf = SM->getCharacterData(endLoc);
5544
5545     std::string messString;
5546     messString += "// ";
5547     messString.append(startBuf, endBuf-startBuf+1);
5548     messString += "\n";
5549
5550     // FIXME: Missing definition of
5551     // InsertText(clang::SourceLocation, char const*, unsigned int).
5552     // InsertText(startLoc, messString.c_str(), messString.size());
5553     // Tried this, but it didn't work either...
5554     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5555 #endif
5556     return RewriteMessageExpr(MessExpr);
5557   }
5558
5559   if (ObjCAutoreleasePoolStmt *StmtAutoRelease = 
5560         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5561     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5562   }
5563   
5564   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5565     return RewriteObjCTryStmt(StmtTry);
5566
5567   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5568     return RewriteObjCSynchronizedStmt(StmtTry);
5569
5570   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5571     return RewriteObjCThrowStmt(StmtThrow);
5572
5573   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5574     return RewriteObjCProtocolExpr(ProtocolExp);
5575
5576   if (ObjCForCollectionStmt *StmtForCollection =
5577         dyn_cast<ObjCForCollectionStmt>(S))
5578     return RewriteObjCForCollectionStmt(StmtForCollection,
5579                                         OrigStmtRange.getEnd());
5580   if (BreakStmt *StmtBreakStmt =
5581       dyn_cast<BreakStmt>(S))
5582     return RewriteBreakStmt(StmtBreakStmt);
5583   if (ContinueStmt *StmtContinueStmt =
5584       dyn_cast<ContinueStmt>(S))
5585     return RewriteContinueStmt(StmtContinueStmt);
5586
5587   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5588   // and cast exprs.
5589   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5590     // FIXME: What we're doing here is modifying the type-specifier that
5591     // precedes the first Decl.  In the future the DeclGroup should have
5592     // a separate type-specifier that we can rewrite.
5593     // NOTE: We need to avoid rewriting the DeclStmt if it is within
5594     // the context of an ObjCForCollectionStmt. For example:
5595     //   NSArray *someArray;
5596     //   for (id <FooProtocol> index in someArray) ;
5597     // This is because RewriteObjCForCollectionStmt() does textual rewriting 
5598     // and it depends on the original text locations/positions.
5599     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5600       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5601
5602     // Blocks rewrite rules.
5603     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5604          DI != DE; ++DI) {
5605       Decl *SD = *DI;
5606       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5607         if (isTopLevelBlockPointerType(ND->getType()))
5608           RewriteBlockPointerDecl(ND);
5609         else if (ND->getType()->isFunctionPointerType())
5610           CheckFunctionPointerDecl(ND->getType(), ND);
5611         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5612           if (VD->hasAttr<BlocksAttr>()) {
5613             static unsigned uniqueByrefDeclCount = 0;
5614             assert(!BlockByRefDeclNo.count(ND) &&
5615               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5616             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5617             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5618           }
5619           else           
5620             RewriteTypeOfDecl(VD);
5621         }
5622       }
5623       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5624         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5625           RewriteBlockPointerDecl(TD);
5626         else if (TD->getUnderlyingType()->isFunctionPointerType())
5627           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5628       }
5629     }
5630   }
5631
5632   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5633     RewriteObjCQualifiedInterfaceTypes(CE);
5634
5635   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5636       isa<DoStmt>(S) || isa<ForStmt>(S)) {
5637     assert(!Stmts.empty() && "Statement stack is empty");
5638     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5639              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5640             && "Statement stack mismatch");
5641     Stmts.pop_back();
5642   }
5643   // Handle blocks rewriting.
5644   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5645     ValueDecl *VD = DRE->getDecl(); 
5646     if (VD->hasAttr<BlocksAttr>())
5647       return RewriteBlockDeclRefExpr(DRE);
5648     if (HasLocalVariableExternalStorage(VD))
5649       return RewriteLocalVariableExternalStorage(DRE);
5650   }
5651   
5652   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5653     if (CE->getCallee()->getType()->isBlockPointerType()) {
5654       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5655       ReplaceStmt(S, BlockCall);
5656       return BlockCall;
5657     }
5658   }
5659   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5660     RewriteCastExpr(CE);
5661   }
5662   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5663     RewriteImplicitCastObjCExpr(ICE);
5664   }
5665 #if 0
5666
5667   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5668     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5669                                                    ICE->getSubExpr(),
5670                                                    SourceLocation());
5671     // Get the new text.
5672     std::string SStr;
5673     llvm::raw_string_ostream Buf(SStr);
5674     Replacement->printPretty(Buf);
5675     const std::string &Str = Buf.str();
5676
5677     printf("CAST = %s\n", &Str[0]);
5678     InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5679     delete S;
5680     return Replacement;
5681   }
5682 #endif
5683   // Return this stmt unmodified.
5684   return S;
5685 }
5686
5687 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5688   for (RecordDecl::field_iterator i = RD->field_begin(), 
5689                                   e = RD->field_end(); i != e; ++i) {
5690     FieldDecl *FD = *i;
5691     if (isTopLevelBlockPointerType(FD->getType()))
5692       RewriteBlockPointerDecl(FD);
5693     if (FD->getType()->isObjCQualifiedIdType() ||
5694         FD->getType()->isObjCQualifiedInterfaceType())
5695       RewriteObjCQualifiedInterfaceTypes(FD);
5696   }
5697 }
5698
5699 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5700 /// main file of the input.
5701 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5702   switch (D->getKind()) {
5703     case Decl::Function: {
5704       FunctionDecl *FD = cast<FunctionDecl>(D);
5705       if (FD->isOverloadedOperator())
5706         return;
5707
5708       // Since function prototypes don't have ParmDecl's, we check the function
5709       // prototype. This enables us to rewrite function declarations and
5710       // definitions using the same code.
5711       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5712
5713       if (!FD->isThisDeclarationADefinition())
5714         break;
5715
5716       // FIXME: If this should support Obj-C++, support CXXTryStmt
5717       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5718         CurFunctionDef = FD;
5719         CurrentBody = Body;
5720         Body =
5721         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5722         FD->setBody(Body);
5723         CurrentBody = 0;
5724         if (PropParentMap) {
5725           delete PropParentMap;
5726           PropParentMap = 0;
5727         }
5728         // This synthesizes and inserts the block "impl" struct, invoke function,
5729         // and any copy/dispose helper functions.
5730         InsertBlockLiteralsWithinFunction(FD);
5731         RewriteLineDirective(D);
5732         CurFunctionDef = 0;
5733       }
5734       break;
5735     }
5736     case Decl::ObjCMethod: {
5737       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5738       if (CompoundStmt *Body = MD->getCompoundBody()) {
5739         CurMethodDef = MD;
5740         CurrentBody = Body;
5741         Body =
5742           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5743         MD->setBody(Body);
5744         CurrentBody = 0;
5745         if (PropParentMap) {
5746           delete PropParentMap;
5747           PropParentMap = 0;
5748         }
5749         InsertBlockLiteralsWithinMethod(MD);
5750         RewriteLineDirective(D);
5751         CurMethodDef = 0;
5752       }
5753       break;
5754     }
5755     case Decl::ObjCImplementation: {
5756       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5757       ClassImplementation.push_back(CI);
5758       break;
5759     }
5760     case Decl::ObjCCategoryImpl: {
5761       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5762       CategoryImplementation.push_back(CI);
5763       break;
5764     }
5765     case Decl::Var: {
5766       VarDecl *VD = cast<VarDecl>(D);
5767       RewriteObjCQualifiedInterfaceTypes(VD);
5768       if (isTopLevelBlockPointerType(VD->getType()))
5769         RewriteBlockPointerDecl(VD);
5770       else if (VD->getType()->isFunctionPointerType()) {
5771         CheckFunctionPointerDecl(VD->getType(), VD);
5772         if (VD->getInit()) {
5773           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5774             RewriteCastExpr(CE);
5775           }
5776         }
5777       } else if (VD->getType()->isRecordType()) {
5778         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5779         if (RD->isCompleteDefinition())
5780           RewriteRecordBody(RD);
5781       }
5782       if (VD->getInit()) {
5783         GlobalVarDecl = VD;
5784         CurrentBody = VD->getInit();
5785         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5786         CurrentBody = 0;
5787         if (PropParentMap) {
5788           delete PropParentMap;
5789           PropParentMap = 0;
5790         }
5791         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5792         GlobalVarDecl = 0;
5793           
5794         // This is needed for blocks.
5795         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5796             RewriteCastExpr(CE);
5797         }
5798       }
5799       break;
5800     }
5801     case Decl::TypeAlias:
5802     case Decl::Typedef: {
5803       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5804         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5805           RewriteBlockPointerDecl(TD);
5806         else if (TD->getUnderlyingType()->isFunctionPointerType())
5807           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5808       }
5809       break;
5810     }
5811     case Decl::CXXRecord:
5812     case Decl::Record: {
5813       RecordDecl *RD = cast<RecordDecl>(D);
5814       if (RD->isCompleteDefinition()) 
5815         RewriteRecordBody(RD);
5816       break;
5817     }
5818     default:
5819       break;
5820   }
5821   // Nothing yet.
5822 }
5823
5824 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5825 /// protocol reference symbols in the for of:
5826 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5827 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, 
5828                                                  ObjCProtocolDecl *PDecl,
5829                                                  std::string &Result) {
5830   // Also output .objc_protorefs$B section and its meta-data.
5831   if (Context->getLangOpts().MicrosoftExt)
5832     Result += "static ";
5833   Result += "struct _protocol_t *";
5834   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5835   Result += PDecl->getNameAsString();
5836   Result += " = &";
5837   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5838   Result += ";\n";
5839 }
5840
5841 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5842   if (Diags.hasErrorOccurred())
5843     return;
5844
5845   RewriteInclude();
5846
5847   // Here's a great place to add any extra declarations that may be needed.
5848   // Write out meta data for each @protocol(<expr>).
5849   for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5850        E = ProtocolExprDecls.end(); I != E; ++I) {
5851     RewriteObjCProtocolMetaData(*I, Preamble);
5852     Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5853   }
5854
5855   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5856   
5857   if (ClassImplementation.size() || CategoryImplementation.size())
5858     RewriteImplementations();
5859   
5860   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5861     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5862     // Write struct declaration for the class matching its ivar declarations.
5863     // Note that for modern abi, this is postponed until the end of TU
5864     // because class extensions and the implementation might declare their own
5865     // private ivars.
5866     RewriteInterfaceDecl(CDecl);
5867   }
5868
5869   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5870   // we are done.
5871   if (const RewriteBuffer *RewriteBuf =
5872       Rewrite.getRewriteBufferFor(MainFileID)) {
5873     //printf("Changed:\n");
5874     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5875   } else {
5876     llvm::errs() << "No changes\n";
5877   }
5878
5879   if (ClassImplementation.size() || CategoryImplementation.size() ||
5880       ProtocolExprDecls.size()) {
5881     // Rewrite Objective-c meta data*
5882     std::string ResultStr;
5883     RewriteMetaDataIntoBuffer(ResultStr);
5884     // Emit metadata.
5885     *OutFile << ResultStr;
5886   }
5887   // Emit ImageInfo;
5888   {
5889     std::string ResultStr;
5890     WriteImageInfo(ResultStr);
5891     *OutFile << ResultStr;
5892   }
5893   OutFile->flush();
5894 }
5895
5896 void RewriteModernObjC::Initialize(ASTContext &context) {
5897   InitializeCommon(context);
5898   
5899   Preamble += "#ifndef __OBJC2__\n";
5900   Preamble += "#define __OBJC2__\n";
5901   Preamble += "#endif\n";
5902
5903   // declaring objc_selector outside the parameter list removes a silly
5904   // scope related warning...
5905   if (IsHeader)
5906     Preamble = "#pragma once\n";
5907   Preamble += "struct objc_selector; struct objc_class;\n";
5908   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5909   Preamble += "\n\tstruct objc_object *superClass; ";
5910   // Add a constructor for creating temporary objects.
5911   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5912   Preamble += ": object(o), superClass(s) {} ";
5913   Preamble += "\n};\n";
5914   
5915   if (LangOpts.MicrosoftExt) {
5916     // Define all sections using syntax that makes sense.
5917     // These are currently generated.
5918     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5919     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5920     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5921     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5922     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5923     // These are generated but not necessary for functionality.
5924     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5925     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5926     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5927     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5928     
5929     // These need be generated for performance. Currently they are not,
5930     // using API calls instead.
5931     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5932     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5933     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5934     
5935   }
5936   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5937   Preamble += "typedef struct objc_object Protocol;\n";
5938   Preamble += "#define _REWRITER_typedef_Protocol\n";
5939   Preamble += "#endif\n";
5940   if (LangOpts.MicrosoftExt) {
5941     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5942     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5943   } 
5944   else
5945     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5946   
5947   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5948   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5949   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5950   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5951   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5952
5953   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5954   Preamble += "(const char *);\n";
5955   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5956   Preamble += "(struct objc_class *);\n";
5957   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5958   Preamble += "(const char *);\n";
5959   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5960   // @synchronized hooks.
5961   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5962   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5963   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5964   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5965   Preamble += "struct __objcFastEnumerationState {\n\t";
5966   Preamble += "unsigned long state;\n\t";
5967   Preamble += "void **itemsPtr;\n\t";
5968   Preamble += "unsigned long *mutationsPtr;\n\t";
5969   Preamble += "unsigned long extra[5];\n};\n";
5970   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5971   Preamble += "#define __FASTENUMERATIONSTATE\n";
5972   Preamble += "#endif\n";
5973   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5974   Preamble += "struct __NSConstantStringImpl {\n";
5975   Preamble += "  int *isa;\n";
5976   Preamble += "  int flags;\n";
5977   Preamble += "  char *str;\n";
5978   Preamble += "  long length;\n";
5979   Preamble += "};\n";
5980   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5981   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5982   Preamble += "#else\n";
5983   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5984   Preamble += "#endif\n";
5985   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5986   Preamble += "#endif\n";
5987   // Blocks preamble.
5988   Preamble += "#ifndef BLOCK_IMPL\n";
5989   Preamble += "#define BLOCK_IMPL\n";
5990   Preamble += "struct __block_impl {\n";
5991   Preamble += "  void *isa;\n";
5992   Preamble += "  int Flags;\n";
5993   Preamble += "  int Reserved;\n";
5994   Preamble += "  void *FuncPtr;\n";
5995   Preamble += "};\n";
5996   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5997   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5998   Preamble += "extern \"C\" __declspec(dllexport) "
5999   "void _Block_object_assign(void *, const void *, const int);\n";
6000   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6001   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6002   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6003   Preamble += "#else\n";
6004   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6005   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6006   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6007   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6008   Preamble += "#endif\n";
6009   Preamble += "#endif\n";
6010   if (LangOpts.MicrosoftExt) {
6011     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6012     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6013     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
6014     Preamble += "#define __attribute__(X)\n";
6015     Preamble += "#endif\n";
6016     Preamble += "#ifndef __weak\n";
6017     Preamble += "#define __weak\n";
6018     Preamble += "#endif\n";
6019     Preamble += "#ifndef __block\n";
6020     Preamble += "#define __block\n";
6021     Preamble += "#endif\n";
6022   }
6023   else {
6024     Preamble += "#define __block\n";
6025     Preamble += "#define __weak\n";
6026   }
6027   
6028   // Declarations required for modern objective-c array and dictionary literals.
6029   Preamble += "\n#include <stdarg.h>\n";
6030   Preamble += "struct __NSContainer_literal {\n";
6031   Preamble += "  void * *arr;\n";
6032   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
6033   Preamble += "\tva_list marker;\n";
6034   Preamble += "\tva_start(marker, count);\n";
6035   Preamble += "\tarr = new void *[count];\n";
6036   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6037   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6038   Preamble += "\tva_end( marker );\n";
6039   Preamble += "  };\n";
6040   Preamble += "  ~__NSContainer_literal() {\n";
6041   Preamble += "\tdelete[] arr;\n";
6042   Preamble += "  }\n";
6043   Preamble += "};\n";
6044   
6045   // Declaration required for implementation of @autoreleasepool statement.
6046   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6047   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6048   Preamble += "struct __AtAutoreleasePool {\n";
6049   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6050   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6051   Preamble += "  void * atautoreleasepoolobj;\n";
6052   Preamble += "};\n";
6053   
6054   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6055   // as this avoids warning in any 64bit/32bit compilation model.
6056   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6057 }
6058
6059 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6060 /// ivar offset.
6061 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6062                                                          std::string &Result) {
6063   if (ivar->isBitField()) {
6064     // FIXME: The hack below doesn't work for bitfields. For now, we simply
6065     // place all bitfields at offset 0.
6066     Result += "0";
6067   } else {
6068     Result += "__OFFSETOFIVAR__(struct ";
6069     Result += ivar->getContainingInterface()->getNameAsString();
6070     if (LangOpts.MicrosoftExt)
6071       Result += "_IMPL";
6072     Result += ", ";
6073     Result += ivar->getNameAsString();
6074     Result += ")";
6075   }
6076 }
6077
6078 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6079 /// struct _prop_t {
6080 ///   const char *name;
6081 ///   char *attributes;
6082 /// }
6083
6084 /// struct _prop_list_t {
6085 ///   uint32_t entsize;      // sizeof(struct _prop_t)
6086 ///   uint32_t count_of_properties;
6087 ///   struct _prop_t prop_list[count_of_properties];
6088 /// }
6089
6090 /// struct _protocol_t;
6091
6092 /// struct _protocol_list_t {
6093 ///   long protocol_count;   // Note, this is 32/64 bit
6094 ///   struct _protocol_t * protocol_list[protocol_count];
6095 /// }
6096
6097 /// struct _objc_method {
6098 ///   SEL _cmd;
6099 ///   const char *method_type;
6100 ///   char *_imp;
6101 /// }
6102
6103 /// struct _method_list_t {
6104 ///   uint32_t entsize;  // sizeof(struct _objc_method)
6105 ///   uint32_t method_count;
6106 ///   struct _objc_method method_list[method_count];
6107 /// }
6108
6109 /// struct _protocol_t {
6110 ///   id isa;  // NULL
6111 ///   const char *protocol_name;
6112 ///   const struct _protocol_list_t * protocol_list; // super protocols
6113 ///   const struct method_list_t *instance_methods;
6114 ///   const struct method_list_t *class_methods;
6115 ///   const struct method_list_t *optionalInstanceMethods;
6116 ///   const struct method_list_t *optionalClassMethods;
6117 ///   const struct _prop_list_t * properties;
6118 ///   const uint32_t size;  // sizeof(struct _protocol_t)
6119 ///   const uint32_t flags;  // = 0
6120 ///   const char ** extendedMethodTypes;
6121 /// }
6122
6123 /// struct _ivar_t {
6124 ///   unsigned long int *offset;  // pointer to ivar offset location
6125 ///   const char *name;
6126 ///   const char *type;
6127 ///   uint32_t alignment;
6128 ///   uint32_t size;
6129 /// }
6130
6131 /// struct _ivar_list_t {
6132 ///   uint32 entsize;  // sizeof(struct _ivar_t)
6133 ///   uint32 count;
6134 ///   struct _ivar_t list[count];
6135 /// }
6136
6137 /// struct _class_ro_t {
6138 ///   uint32_t flags;
6139 ///   uint32_t instanceStart;
6140 ///   uint32_t instanceSize;
6141 ///   uint32_t reserved;  // only when building for 64bit targets
6142 ///   const uint8_t *ivarLayout;
6143 ///   const char *name;
6144 ///   const struct _method_list_t *baseMethods;
6145 ///   const struct _protocol_list_t *baseProtocols;
6146 ///   const struct _ivar_list_t *ivars;
6147 ///   const uint8_t *weakIvarLayout;
6148 ///   const struct _prop_list_t *properties;
6149 /// }
6150
6151 /// struct _class_t {
6152 ///   struct _class_t *isa;
6153 ///   struct _class_t *superclass;
6154 ///   void *cache;
6155 ///   IMP *vtable;
6156 ///   struct _class_ro_t *ro;
6157 /// }
6158
6159 /// struct _category_t {
6160 ///   const char *name;
6161 ///   struct _class_t *cls;
6162 ///   const struct _method_list_t *instance_methods;
6163 ///   const struct _method_list_t *class_methods;
6164 ///   const struct _protocol_list_t *protocols;
6165 ///   const struct _prop_list_t *properties;
6166 /// }
6167
6168 /// MessageRefTy - LLVM for:
6169 /// struct _message_ref_t {
6170 ///   IMP messenger;
6171 ///   SEL name;
6172 /// };
6173
6174 /// SuperMessageRefTy - LLVM for:
6175 /// struct _super_message_ref_t {
6176 ///   SUPER_IMP messenger;
6177 ///   SEL name;
6178 /// };
6179
6180 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6181   static bool meta_data_declared = false;
6182   if (meta_data_declared)
6183     return;
6184   
6185   Result += "\nstruct _prop_t {\n";
6186   Result += "\tconst char *name;\n";
6187   Result += "\tconst char *attributes;\n";
6188   Result += "};\n";
6189   
6190   Result += "\nstruct _protocol_t;\n";
6191   
6192   Result += "\nstruct _objc_method {\n";
6193   Result += "\tstruct objc_selector * _cmd;\n";
6194   Result += "\tconst char *method_type;\n";
6195   Result += "\tvoid  *_imp;\n";
6196   Result += "};\n";
6197   
6198   Result += "\nstruct _protocol_t {\n";
6199   Result += "\tvoid * isa;  // NULL\n";
6200   Result += "\tconst char *protocol_name;\n";
6201   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6202   Result += "\tconst struct method_list_t *instance_methods;\n";
6203   Result += "\tconst struct method_list_t *class_methods;\n";
6204   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6205   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6206   Result += "\tconst struct _prop_list_t * properties;\n";
6207   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6208   Result += "\tconst unsigned int flags;  // = 0\n";
6209   Result += "\tconst char ** extendedMethodTypes;\n";
6210   Result += "};\n";
6211   
6212   Result += "\nstruct _ivar_t {\n";
6213   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6214   Result += "\tconst char *name;\n";
6215   Result += "\tconst char *type;\n";
6216   Result += "\tunsigned int alignment;\n";
6217   Result += "\tunsigned int  size;\n";
6218   Result += "};\n";
6219   
6220   Result += "\nstruct _class_ro_t {\n";
6221   Result += "\tunsigned int flags;\n";
6222   Result += "\tunsigned int instanceStart;\n";
6223   Result += "\tunsigned int instanceSize;\n";
6224   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6225   if (Triple.getArch() == llvm::Triple::x86_64)
6226     Result += "\tunsigned int reserved;\n";
6227   Result += "\tconst unsigned char *ivarLayout;\n";
6228   Result += "\tconst char *name;\n";
6229   Result += "\tconst struct _method_list_t *baseMethods;\n";
6230   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6231   Result += "\tconst struct _ivar_list_t *ivars;\n";
6232   Result += "\tconst unsigned char *weakIvarLayout;\n";
6233   Result += "\tconst struct _prop_list_t *properties;\n";
6234   Result += "};\n";
6235   
6236   Result += "\nstruct _class_t {\n";
6237   Result += "\tstruct _class_t *isa;\n";
6238   Result += "\tstruct _class_t *superclass;\n";
6239   Result += "\tvoid *cache;\n";
6240   Result += "\tvoid *vtable;\n";
6241   Result += "\tstruct _class_ro_t *ro;\n";
6242   Result += "};\n";
6243   
6244   Result += "\nstruct _category_t {\n";
6245   Result += "\tconst char *name;\n";
6246   Result += "\tstruct _class_t *cls;\n";
6247   Result += "\tconst struct _method_list_t *instance_methods;\n";
6248   Result += "\tconst struct _method_list_t *class_methods;\n";
6249   Result += "\tconst struct _protocol_list_t *protocols;\n";
6250   Result += "\tconst struct _prop_list_t *properties;\n";
6251   Result += "};\n";
6252   
6253   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6254   Result += "#pragma warning(disable:4273)\n";
6255   meta_data_declared = true;
6256 }
6257
6258 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6259                                            long super_protocol_count) {
6260   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6261   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6262   Result += "\tstruct _protocol_t *super_protocols[";
6263   Result += utostr(super_protocol_count); Result += "];\n";
6264   Result += "}";
6265 }
6266
6267 static void Write_method_list_t_TypeDecl(std::string &Result,
6268                                          unsigned int method_count) {
6269   Result += "struct /*_method_list_t*/"; Result += " {\n";
6270   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6271   Result += "\tunsigned int method_count;\n";
6272   Result += "\tstruct _objc_method method_list[";
6273   Result += utostr(method_count); Result += "];\n";
6274   Result += "}";
6275 }
6276
6277 static void Write__prop_list_t_TypeDecl(std::string &Result,
6278                                         unsigned int property_count) {
6279   Result += "struct /*_prop_list_t*/"; Result += " {\n";
6280   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6281   Result += "\tunsigned int count_of_properties;\n";
6282   Result += "\tstruct _prop_t prop_list[";
6283   Result += utostr(property_count); Result += "];\n";
6284   Result += "}";
6285 }
6286
6287 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6288                                         unsigned int ivar_count) {
6289   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6290   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6291   Result += "\tunsigned int count;\n";
6292   Result += "\tstruct _ivar_t ivar_list[";
6293   Result += utostr(ivar_count); Result += "];\n";
6294   Result += "}";
6295 }
6296
6297 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6298                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6299                                             StringRef VarName,
6300                                             StringRef ProtocolName) {
6301   if (SuperProtocols.size() > 0) {
6302     Result += "\nstatic ";
6303     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6304     Result += " "; Result += VarName;
6305     Result += ProtocolName; 
6306     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6307     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6308     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6309       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6310       Result += "\t&"; Result += "_OBJC_PROTOCOL_"; 
6311       Result += SuperPD->getNameAsString();
6312       if (i == e-1)
6313         Result += "\n};\n";
6314       else
6315         Result += ",\n";
6316     }
6317   }
6318 }
6319
6320 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6321                                             ASTContext *Context, std::string &Result,
6322                                             ArrayRef<ObjCMethodDecl *> Methods,
6323                                             StringRef VarName,
6324                                             StringRef TopLevelDeclName,
6325                                             bool MethodImpl) {
6326   if (Methods.size() > 0) {
6327     Result += "\nstatic ";
6328     Write_method_list_t_TypeDecl(Result, Methods.size());
6329     Result += " "; Result += VarName;
6330     Result += TopLevelDeclName; 
6331     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6332     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6333     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6334     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6335       ObjCMethodDecl *MD = Methods[i];
6336       if (i == 0)
6337         Result += "\t{{(struct objc_selector *)\"";
6338       else
6339         Result += "\t{(struct objc_selector *)\"";
6340       Result += (MD)->getSelector().getAsString(); Result += "\"";
6341       Result += ", ";
6342       std::string MethodTypeString;
6343       Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6344       Result += "\""; Result += MethodTypeString; Result += "\"";
6345       Result += ", ";
6346       if (!MethodImpl)
6347         Result += "0";
6348       else {
6349         Result += "(void *)";
6350         Result += RewriteObj.MethodInternalNames[MD];
6351       }
6352       if (i  == e-1)
6353         Result += "}}\n";
6354       else
6355         Result += "},\n";
6356     }
6357     Result += "};\n";
6358   }
6359 }
6360
6361 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6362                                            ASTContext *Context, std::string &Result,
6363                                            ArrayRef<ObjCPropertyDecl *> Properties,
6364                                            const Decl *Container,
6365                                            StringRef VarName,
6366                                            StringRef ProtocolName) {
6367   if (Properties.size() > 0) {
6368     Result += "\nstatic ";
6369     Write__prop_list_t_TypeDecl(Result, Properties.size());
6370     Result += " "; Result += VarName;
6371     Result += ProtocolName; 
6372     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6373     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6374     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6375     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6376       ObjCPropertyDecl *PropDecl = Properties[i];
6377       if (i == 0)
6378         Result += "\t{{\"";
6379       else
6380         Result += "\t{\"";
6381       Result += PropDecl->getName(); Result += "\",";
6382       std::string PropertyTypeString, QuotePropertyTypeString;
6383       Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6384       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6385       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6386       if (i  == e-1)
6387         Result += "}}\n";
6388       else
6389         Result += "},\n";
6390     }
6391     Result += "};\n";
6392   }
6393 }
6394
6395 // Metadata flags
6396 enum MetaDataDlags {
6397   CLS = 0x0,
6398   CLS_META = 0x1,
6399   CLS_ROOT = 0x2,
6400   OBJC2_CLS_HIDDEN = 0x10,
6401   CLS_EXCEPTION = 0x20,
6402   
6403   /// (Obsolete) ARC-specific: this class has a .release_ivars method
6404   CLS_HAS_IVAR_RELEASER = 0x40,
6405   /// class was compiled with -fobjc-arr
6406   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6407 };
6408
6409 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, 
6410                                           unsigned int flags, 
6411                                           const std::string &InstanceStart, 
6412                                           const std::string &InstanceSize,
6413                                           ArrayRef<ObjCMethodDecl *>baseMethods,
6414                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
6415                                           ArrayRef<ObjCIvarDecl *>ivars,
6416                                           ArrayRef<ObjCPropertyDecl *>Properties,
6417                                           StringRef VarName,
6418                                           StringRef ClassName) {
6419   Result += "\nstatic struct _class_ro_t ";
6420   Result += VarName; Result += ClassName;
6421   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6422   Result += "\t"; 
6423   Result += llvm::utostr(flags); Result += ", "; 
6424   Result += InstanceStart; Result += ", ";
6425   Result += InstanceSize; Result += ", \n";
6426   Result += "\t";
6427   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6428   if (Triple.getArch() == llvm::Triple::x86_64)
6429     // uint32_t const reserved; // only when building for 64bit targets
6430     Result += "(unsigned int)0, \n\t";
6431   // const uint8_t * const ivarLayout;
6432   Result += "0, \n\t";
6433   Result += "\""; Result += ClassName; Result += "\",\n\t";
6434   bool metaclass = ((flags & CLS_META) != 0);
6435   if (baseMethods.size() > 0) {
6436     Result += "(const struct _method_list_t *)&";
6437     if (metaclass)
6438       Result += "_OBJC_$_CLASS_METHODS_";
6439     else
6440       Result += "_OBJC_$_INSTANCE_METHODS_";
6441     Result += ClassName;
6442     Result += ",\n\t";
6443   }
6444   else
6445     Result += "0, \n\t";
6446
6447   if (!metaclass && baseProtocols.size() > 0) {
6448     Result += "(const struct _objc_protocol_list *)&";
6449     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6450     Result += ",\n\t";
6451   }
6452   else
6453     Result += "0, \n\t";
6454
6455   if (!metaclass && ivars.size() > 0) {
6456     Result += "(const struct _ivar_list_t *)&";
6457     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6458     Result += ",\n\t";
6459   }
6460   else
6461     Result += "0, \n\t";
6462
6463   // weakIvarLayout
6464   Result += "0, \n\t";
6465   if (!metaclass && Properties.size() > 0) {
6466     Result += "(const struct _prop_list_t *)&";
6467     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6468     Result += ",\n";
6469   }
6470   else
6471     Result += "0, \n";
6472
6473   Result += "};\n";
6474 }
6475
6476 static void Write_class_t(ASTContext *Context, std::string &Result,
6477                           StringRef VarName,
6478                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
6479   bool rootClass = (!CDecl->getSuperClass());
6480   const ObjCInterfaceDecl *RootClass = CDecl;
6481   
6482   if (!rootClass) {
6483     // Find the Root class
6484     RootClass = CDecl->getSuperClass();
6485     while (RootClass->getSuperClass()) {
6486       RootClass = RootClass->getSuperClass();
6487     }
6488   }
6489
6490   if (metaclass && rootClass) {
6491     // Need to handle a case of use of forward declaration.
6492     Result += "\n";
6493     Result += "extern \"C\" ";
6494     if (CDecl->getImplementation())
6495       Result += "__declspec(dllexport) ";
6496     else
6497       Result += "__declspec(dllimport) ";
6498     
6499     Result += "struct _class_t OBJC_CLASS_$_";
6500     Result += CDecl->getNameAsString();
6501     Result += ";\n";
6502   }
6503   // Also, for possibility of 'super' metadata class not having been defined yet.
6504   if (!rootClass) {
6505     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6506     Result += "\n";
6507     Result += "extern \"C\" ";
6508     if (SuperClass->getImplementation())
6509       Result += "__declspec(dllexport) ";
6510     else
6511       Result += "__declspec(dllimport) ";
6512
6513     Result += "struct _class_t "; 
6514     Result += VarName;
6515     Result += SuperClass->getNameAsString();
6516     Result += ";\n";
6517     
6518     if (metaclass && RootClass != SuperClass) {
6519       Result += "extern \"C\" ";
6520       if (RootClass->getImplementation())
6521         Result += "__declspec(dllexport) ";
6522       else
6523         Result += "__declspec(dllimport) ";
6524
6525       Result += "struct _class_t "; 
6526       Result += VarName;
6527       Result += RootClass->getNameAsString();
6528       Result += ";\n";
6529     }
6530   }
6531   
6532   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; 
6533   Result += VarName; Result += CDecl->getNameAsString();
6534   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6535   Result += "\t";
6536   if (metaclass) {
6537     if (!rootClass) {
6538       Result += "0, // &"; Result += VarName;
6539       Result += RootClass->getNameAsString();
6540       Result += ",\n\t";
6541       Result += "0, // &"; Result += VarName;
6542       Result += CDecl->getSuperClass()->getNameAsString();
6543       Result += ",\n\t";
6544     }
6545     else {
6546       Result += "0, // &"; Result += VarName; 
6547       Result += CDecl->getNameAsString();
6548       Result += ",\n\t";
6549       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6550       Result += ",\n\t";
6551     }
6552   }
6553   else {
6554     Result += "0, // &OBJC_METACLASS_$_"; 
6555     Result += CDecl->getNameAsString();
6556     Result += ",\n\t";
6557     if (!rootClass) {
6558       Result += "0, // &"; Result += VarName;
6559       Result += CDecl->getSuperClass()->getNameAsString();
6560       Result += ",\n\t";
6561     }
6562     else 
6563       Result += "0,\n\t";
6564   }
6565   Result += "0, // (void *)&_objc_empty_cache,\n\t";
6566   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6567   if (metaclass)
6568     Result += "&_OBJC_METACLASS_RO_$_";
6569   else
6570     Result += "&_OBJC_CLASS_RO_$_";
6571   Result += CDecl->getNameAsString();
6572   Result += ",\n};\n";
6573   
6574   // Add static function to initialize some of the meta-data fields.
6575   // avoid doing it twice.
6576   if (metaclass)
6577     return;
6578   
6579   const ObjCInterfaceDecl *SuperClass = 
6580     rootClass ? CDecl : CDecl->getSuperClass();
6581   
6582   Result += "static void OBJC_CLASS_SETUP_$_";
6583   Result += CDecl->getNameAsString();
6584   Result += "(void ) {\n";
6585   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6586   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6587   Result += RootClass->getNameAsString(); Result += ";\n";
6588   
6589   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6590   Result += ".superclass = ";
6591   if (rootClass)
6592     Result += "&OBJC_CLASS_$_";
6593   else
6594      Result += "&OBJC_METACLASS_$_";
6595
6596   Result += SuperClass->getNameAsString(); Result += ";\n";
6597   
6598   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6599   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6600   
6601   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6602   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6603   Result += CDecl->getNameAsString(); Result += ";\n";
6604   
6605   if (!rootClass) {
6606     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6607     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6608     Result += SuperClass->getNameAsString(); Result += ";\n";
6609   }
6610   
6611   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6612   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6613   Result += "}\n";
6614 }
6615
6616 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, 
6617                              std::string &Result,
6618                              ObjCCategoryDecl *CatDecl,
6619                              ObjCInterfaceDecl *ClassDecl,
6620                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
6621                              ArrayRef<ObjCMethodDecl *> ClassMethods,
6622                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6623                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6624   StringRef CatName = CatDecl->getName();
6625   StringRef ClassName = ClassDecl->getName();
6626   // must declare an extern class object in case this class is not implemented 
6627   // in this TU.
6628   Result += "\n";
6629   Result += "extern \"C\" ";
6630   if (ClassDecl->getImplementation())
6631     Result += "__declspec(dllexport) ";
6632   else
6633     Result += "__declspec(dllimport) ";
6634   
6635   Result += "struct _class_t ";
6636   Result += "OBJC_CLASS_$_"; Result += ClassName;
6637   Result += ";\n";
6638   
6639   Result += "\nstatic struct _category_t ";
6640   Result += "_OBJC_$_CATEGORY_";
6641   Result += ClassName; Result += "_$_"; Result += CatName;
6642   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6643   Result += "{\n";
6644   Result += "\t\""; Result += ClassName; Result += "\",\n";
6645   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6646   Result += ",\n";
6647   if (InstanceMethods.size() > 0) {
6648     Result += "\t(const struct _method_list_t *)&";  
6649     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6650     Result += ClassName; Result += "_$_"; Result += CatName;
6651     Result += ",\n";
6652   }
6653   else
6654     Result += "\t0,\n";
6655   
6656   if (ClassMethods.size() > 0) {
6657     Result += "\t(const struct _method_list_t *)&";  
6658     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6659     Result += ClassName; Result += "_$_"; Result += CatName;
6660     Result += ",\n";
6661   }
6662   else
6663     Result += "\t0,\n";
6664   
6665   if (RefedProtocols.size() > 0) {
6666     Result += "\t(const struct _protocol_list_t *)&";  
6667     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6668     Result += ClassName; Result += "_$_"; Result += CatName;
6669     Result += ",\n";
6670   }
6671   else
6672     Result += "\t0,\n";
6673   
6674   if (ClassProperties.size() > 0) {
6675     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6676     Result += ClassName; Result += "_$_"; Result += CatName;
6677     Result += ",\n";
6678   }
6679   else
6680     Result += "\t0,\n";
6681   
6682   Result += "};\n";
6683   
6684   // Add static function to initialize the class pointer in the category structure.
6685   Result += "static void OBJC_CATEGORY_SETUP_$_";
6686   Result += ClassDecl->getNameAsString();
6687   Result += "_$_";
6688   Result += CatName;
6689   Result += "(void ) {\n";
6690   Result += "\t_OBJC_$_CATEGORY_"; 
6691   Result += ClassDecl->getNameAsString();
6692   Result += "_$_";
6693   Result += CatName;
6694   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6695   Result += ";\n}\n";
6696 }
6697
6698 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6699                                            ASTContext *Context, std::string &Result,
6700                                            ArrayRef<ObjCMethodDecl *> Methods,
6701                                            StringRef VarName,
6702                                            StringRef ProtocolName) {
6703   if (Methods.size() == 0)
6704     return;
6705   
6706   Result += "\nstatic const char *";
6707   Result += VarName; Result += ProtocolName;
6708   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6709   Result += "{\n";
6710   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6711     ObjCMethodDecl *MD = Methods[i];
6712     std::string MethodTypeString, QuoteMethodTypeString;
6713     Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6714     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6715     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6716     if (i == e-1)
6717       Result += "\n};\n";
6718     else {
6719       Result += ",\n";
6720     }
6721   }
6722 }
6723
6724 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6725                                 ASTContext *Context,
6726                                 std::string &Result, 
6727                                 ArrayRef<ObjCIvarDecl *> Ivars, 
6728                                 ObjCInterfaceDecl *CDecl) {
6729   // FIXME. visibilty of offset symbols may have to be set; for Darwin
6730   // this is what happens:
6731   /**
6732    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6733        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6734        Class->getVisibility() == HiddenVisibility)
6735      Visibility shoud be: HiddenVisibility;
6736    else
6737      Visibility shoud be: DefaultVisibility;
6738   */
6739   
6740   Result += "\n";
6741   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6742     ObjCIvarDecl *IvarDecl = Ivars[i];
6743     if (Context->getLangOpts().MicrosoftExt)
6744       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6745     
6746     if (!Context->getLangOpts().MicrosoftExt ||
6747         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6748         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6749       Result += "extern \"C\" unsigned long int "; 
6750     else
6751       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6752     WriteInternalIvarName(CDecl, IvarDecl, Result);
6753     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6754     Result += " = ";
6755     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6756     Result += ";\n";
6757   }
6758 }
6759
6760 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6761                                            ASTContext *Context, std::string &Result,
6762                                            ArrayRef<ObjCIvarDecl *> Ivars,
6763                                            StringRef VarName,
6764                                            ObjCInterfaceDecl *CDecl) {
6765   if (Ivars.size() > 0) {
6766     Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
6767     
6768     Result += "\nstatic ";
6769     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6770     Result += " "; Result += VarName;
6771     Result += CDecl->getNameAsString();
6772     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6773     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6774     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6775     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6776       ObjCIvarDecl *IvarDecl = Ivars[i];
6777       if (i == 0)
6778         Result += "\t{{";
6779       else
6780         Result += "\t {";
6781       Result += "(unsigned long int *)&";
6782       WriteInternalIvarName(CDecl, IvarDecl, Result);
6783       Result += ", ";
6784       
6785       Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6786       std::string IvarTypeString, QuoteIvarTypeString;
6787       Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6788                                       IvarDecl);
6789       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6790       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6791       
6792       // FIXME. this alignment represents the host alignment and need be changed to
6793       // represent the target alignment.
6794       unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6795       Align = llvm::Log2_32(Align);
6796       Result += llvm::utostr(Align); Result += ", ";
6797       CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6798       Result += llvm::utostr(Size.getQuantity());
6799       if (i  == e-1)
6800         Result += "}}\n";
6801       else
6802         Result += "},\n";
6803     }
6804     Result += "};\n";
6805   }
6806 }
6807
6808 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6809 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, 
6810                                                     std::string &Result) {
6811   
6812   // Do not synthesize the protocol more than once.
6813   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6814     return;
6815   WriteModernMetadataDeclarations(Context, Result);
6816   
6817   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6818     PDecl = Def;
6819   // Must write out all protocol definitions in current qualifier list,
6820   // and in their nested qualifiers before writing out current definition.
6821   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6822        E = PDecl->protocol_end(); I != E; ++I)
6823     RewriteObjCProtocolMetaData(*I, Result);
6824   
6825   // Construct method lists.
6826   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6827   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6828   for (ObjCProtocolDecl::instmeth_iterator
6829        I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6830        I != E; ++I) {
6831     ObjCMethodDecl *MD = *I;
6832     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6833       OptInstanceMethods.push_back(MD);
6834     } else {
6835       InstanceMethods.push_back(MD);
6836     }
6837   }
6838   
6839   for (ObjCProtocolDecl::classmeth_iterator
6840        I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6841        I != E; ++I) {
6842     ObjCMethodDecl *MD = *I;
6843     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6844       OptClassMethods.push_back(MD);
6845     } else {
6846       ClassMethods.push_back(MD);
6847     }
6848   }
6849   std::vector<ObjCMethodDecl *> AllMethods;
6850   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6851     AllMethods.push_back(InstanceMethods[i]);
6852   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6853     AllMethods.push_back(ClassMethods[i]);
6854   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6855     AllMethods.push_back(OptInstanceMethods[i]);
6856   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6857     AllMethods.push_back(OptClassMethods[i]);
6858
6859   Write__extendedMethodTypes_initializer(*this, Context, Result,
6860                                          AllMethods,
6861                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
6862                                          PDecl->getNameAsString());
6863   // Protocol's super protocol list
6864   std::vector<ObjCProtocolDecl *> SuperProtocols;
6865   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6866        E = PDecl->protocol_end(); I != E; ++I)
6867     SuperProtocols.push_back(*I);
6868   
6869   Write_protocol_list_initializer(Context, Result, SuperProtocols,
6870                                   "_OBJC_PROTOCOL_REFS_",
6871                                   PDecl->getNameAsString());
6872   
6873   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, 
6874                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6875                                   PDecl->getNameAsString(), false);
6876   
6877   Write_method_list_t_initializer(*this, Context, Result, ClassMethods, 
6878                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
6879                                   PDecl->getNameAsString(), false);
6880
6881   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, 
6882                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6883                                   PDecl->getNameAsString(), false);
6884   
6885   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, 
6886                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6887                                   PDecl->getNameAsString(), false);
6888   
6889   // Protocol's property metadata.
6890   std::vector<ObjCPropertyDecl *> ProtocolProperties;
6891   for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6892        E = PDecl->prop_end(); I != E; ++I)
6893     ProtocolProperties.push_back(*I);
6894   
6895   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6896                                  /* Container */0,
6897                                  "_OBJC_PROTOCOL_PROPERTIES_",
6898                                  PDecl->getNameAsString());
6899   
6900   // Writer out root metadata for current protocol: struct _protocol_t
6901   Result += "\n";
6902   if (LangOpts.MicrosoftExt)
6903     Result += "static ";
6904   Result += "struct _protocol_t _OBJC_PROTOCOL_";
6905   Result += PDecl->getNameAsString();
6906   Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6907   Result += "\t0,\n"; // id is; is null
6908   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6909   if (SuperProtocols.size() > 0) {
6910     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6911     Result += PDecl->getNameAsString(); Result += ",\n";
6912   }
6913   else
6914     Result += "\t0,\n";
6915   if (InstanceMethods.size() > 0) {
6916     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; 
6917     Result += PDecl->getNameAsString(); Result += ",\n";
6918   }
6919   else
6920     Result += "\t0,\n";
6921
6922   if (ClassMethods.size() > 0) {
6923     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; 
6924     Result += PDecl->getNameAsString(); Result += ",\n";
6925   }
6926   else
6927     Result += "\t0,\n";
6928   
6929   if (OptInstanceMethods.size() > 0) {
6930     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; 
6931     Result += PDecl->getNameAsString(); Result += ",\n";
6932   }
6933   else
6934     Result += "\t0,\n";
6935   
6936   if (OptClassMethods.size() > 0) {
6937     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; 
6938     Result += PDecl->getNameAsString(); Result += ",\n";
6939   }
6940   else
6941     Result += "\t0,\n";
6942   
6943   if (ProtocolProperties.size() > 0) {
6944     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; 
6945     Result += PDecl->getNameAsString(); Result += ",\n";
6946   }
6947   else
6948     Result += "\t0,\n";
6949   
6950   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6951   Result += "\t0,\n";
6952   
6953   if (AllMethods.size() > 0) {
6954     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6955     Result += PDecl->getNameAsString();
6956     Result += "\n};\n";
6957   }
6958   else
6959     Result += "\t0\n};\n";
6960   
6961   if (LangOpts.MicrosoftExt)
6962     Result += "static ";
6963   Result += "struct _protocol_t *";
6964   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6965   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6966   Result += ";\n";
6967     
6968   // Mark this protocol as having been generated.
6969   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6970     llvm_unreachable("protocol already synthesized");
6971   
6972 }
6973
6974 void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6975                                 const ObjCList<ObjCProtocolDecl> &Protocols,
6976                                 StringRef prefix, StringRef ClassName,
6977                                 std::string &Result) {
6978   if (Protocols.empty()) return;
6979   
6980   for (unsigned i = 0; i != Protocols.size(); i++)
6981     RewriteObjCProtocolMetaData(Protocols[i], Result);
6982   
6983   // Output the top lovel protocol meta-data for the class.
6984   /* struct _objc_protocol_list {
6985    struct _objc_protocol_list *next;
6986    int    protocol_count;
6987    struct _objc_protocol *class_protocols[];
6988    }
6989    */
6990   Result += "\n";
6991   if (LangOpts.MicrosoftExt)
6992     Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6993   Result += "static struct {\n";
6994   Result += "\tstruct _objc_protocol_list *next;\n";
6995   Result += "\tint    protocol_count;\n";
6996   Result += "\tstruct _objc_protocol *class_protocols[";
6997   Result += utostr(Protocols.size());
6998   Result += "];\n} _OBJC_";
6999   Result += prefix;
7000   Result += "_PROTOCOLS_";
7001   Result += ClassName;
7002   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7003   "{\n\t0, ";
7004   Result += utostr(Protocols.size());
7005   Result += "\n";
7006   
7007   Result += "\t,{&_OBJC_PROTOCOL_";
7008   Result += Protocols[0]->getNameAsString();
7009   Result += " \n";
7010   
7011   for (unsigned i = 1; i != Protocols.size(); i++) {
7012     Result += "\t ,&_OBJC_PROTOCOL_";
7013     Result += Protocols[i]->getNameAsString();
7014     Result += "\n";
7015   }
7016   Result += "\t }\n};\n";
7017 }
7018
7019 /// hasObjCExceptionAttribute - Return true if this class or any super
7020 /// class has the __objc_exception__ attribute.
7021 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7022 static bool hasObjCExceptionAttribute(ASTContext &Context,
7023                                       const ObjCInterfaceDecl *OID) {
7024   if (OID->hasAttr<ObjCExceptionAttr>())
7025     return true;
7026   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7027     return hasObjCExceptionAttribute(Context, Super);
7028   return false;
7029 }
7030
7031 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7032                                            std::string &Result) {
7033   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7034   
7035   // Explicitly declared @interface's are already synthesized.
7036   if (CDecl->isImplicitInterfaceDecl())
7037     assert(false && 
7038            "Legacy implicit interface rewriting not supported in moder abi");
7039   
7040   WriteModernMetadataDeclarations(Context, Result);
7041   SmallVector<ObjCIvarDecl *, 8> IVars;
7042   
7043   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7044       IVD; IVD = IVD->getNextIvar()) {
7045     // Ignore unnamed bit-fields.
7046     if (!IVD->getDeclName())
7047       continue;
7048     IVars.push_back(IVD);
7049   }
7050   
7051   Write__ivar_list_t_initializer(*this, Context, Result, IVars, 
7052                                  "_OBJC_$_INSTANCE_VARIABLES_",
7053                                  CDecl);
7054   
7055   // Build _objc_method_list for class's instance methods if needed
7056   SmallVector<ObjCMethodDecl *, 32>
7057     InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7058   
7059   // If any of our property implementations have associated getters or
7060   // setters, produce metadata for them as well.
7061   for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7062        PropEnd = IDecl->propimpl_end();
7063        Prop != PropEnd; ++Prop) {
7064     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7065       continue;
7066     if (!Prop->getPropertyIvarDecl())
7067       continue;
7068     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7069     if (!PD)
7070       continue;
7071     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7072       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7073         InstanceMethods.push_back(Getter);
7074     if (PD->isReadOnly())
7075       continue;
7076     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7077       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7078         InstanceMethods.push_back(Setter);
7079   }
7080   
7081   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7082                                   "_OBJC_$_INSTANCE_METHODS_",
7083                                   IDecl->getNameAsString(), true);
7084   
7085   SmallVector<ObjCMethodDecl *, 32>
7086     ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7087   
7088   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7089                                   "_OBJC_$_CLASS_METHODS_",
7090                                   IDecl->getNameAsString(), true);
7091   
7092   // Protocols referenced in class declaration?
7093   // Protocol's super protocol list
7094   std::vector<ObjCProtocolDecl *> RefedProtocols;
7095   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7096   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7097        E = Protocols.end();
7098        I != E; ++I) {
7099     RefedProtocols.push_back(*I);
7100     // Must write out all protocol definitions in current qualifier list,
7101     // and in their nested qualifiers before writing out current definition.
7102     RewriteObjCProtocolMetaData(*I, Result);
7103   }
7104   
7105   Write_protocol_list_initializer(Context, Result, 
7106                                   RefedProtocols,
7107                                   "_OBJC_CLASS_PROTOCOLS_$_",
7108                                   IDecl->getNameAsString());
7109   
7110   // Protocol's property metadata.
7111   std::vector<ObjCPropertyDecl *> ClassProperties;
7112   for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7113        E = CDecl->prop_end(); I != E; ++I)
7114     ClassProperties.push_back(*I);
7115   
7116   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7117                                  /* Container */IDecl,
7118                                  "_OBJC_$_PROP_LIST_",
7119                                  CDecl->getNameAsString());
7120
7121   
7122   // Data for initializing _class_ro_t  metaclass meta-data
7123   uint32_t flags = CLS_META;
7124   std::string InstanceSize;
7125   std::string InstanceStart;
7126   
7127   
7128   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7129   if (classIsHidden)
7130     flags |= OBJC2_CLS_HIDDEN;
7131   
7132   if (!CDecl->getSuperClass())
7133     // class is root
7134     flags |= CLS_ROOT;
7135   InstanceSize = "sizeof(struct _class_t)";
7136   InstanceStart = InstanceSize;
7137   Write__class_ro_t_initializer(Context, Result, flags, 
7138                                 InstanceStart, InstanceSize,
7139                                 ClassMethods,
7140                                 0,
7141                                 0,
7142                                 0,
7143                                 "_OBJC_METACLASS_RO_$_",
7144                                 CDecl->getNameAsString());
7145
7146   
7147   // Data for initializing _class_ro_t meta-data
7148   flags = CLS;
7149   if (classIsHidden)
7150     flags |= OBJC2_CLS_HIDDEN;
7151   
7152   if (hasObjCExceptionAttribute(*Context, CDecl))
7153     flags |= CLS_EXCEPTION;
7154
7155   if (!CDecl->getSuperClass())
7156     // class is root
7157     flags |= CLS_ROOT;
7158   
7159   InstanceSize.clear();
7160   InstanceStart.clear();
7161   if (!ObjCSynthesizedStructs.count(CDecl)) {
7162     InstanceSize = "0";
7163     InstanceStart = "0";
7164   }
7165   else {
7166     InstanceSize = "sizeof(struct ";
7167     InstanceSize += CDecl->getNameAsString();
7168     InstanceSize += "_IMPL)";
7169     
7170     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7171     if (IVD) {
7172       RewriteIvarOffsetComputation(IVD, InstanceStart);
7173     }
7174     else 
7175       InstanceStart = InstanceSize;
7176   }
7177   Write__class_ro_t_initializer(Context, Result, flags, 
7178                                 InstanceStart, InstanceSize,
7179                                 InstanceMethods,
7180                                 RefedProtocols,
7181                                 IVars,
7182                                 ClassProperties,
7183                                 "_OBJC_CLASS_RO_$_",
7184                                 CDecl->getNameAsString());
7185   
7186   Write_class_t(Context, Result,
7187                 "OBJC_METACLASS_$_",
7188                 CDecl, /*metaclass*/true);
7189   
7190   Write_class_t(Context, Result,
7191                 "OBJC_CLASS_$_",
7192                 CDecl, /*metaclass*/false);
7193   
7194   if (ImplementationIsNonLazy(IDecl))
7195     DefinedNonLazyClasses.push_back(CDecl);
7196                 
7197 }
7198
7199 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7200   int ClsDefCount = ClassImplementation.size();
7201   if (!ClsDefCount)
7202     return;
7203   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7204   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7205   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7206   for (int i = 0; i < ClsDefCount; i++) {
7207     ObjCImplementationDecl *IDecl = ClassImplementation[i];
7208     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7209     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7210     Result  += CDecl->getName(); Result += ",\n";
7211   }
7212   Result += "};\n";
7213 }
7214
7215 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7216   int ClsDefCount = ClassImplementation.size();
7217   int CatDefCount = CategoryImplementation.size();
7218   
7219   // For each implemented class, write out all its meta data.
7220   for (int i = 0; i < ClsDefCount; i++)
7221     RewriteObjCClassMetaData(ClassImplementation[i], Result);
7222   
7223   RewriteClassSetupInitHook(Result);
7224   
7225   // For each implemented category, write out all its meta data.
7226   for (int i = 0; i < CatDefCount; i++)
7227     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7228   
7229   RewriteCategorySetupInitHook(Result);
7230   
7231   if (ClsDefCount > 0) {
7232     if (LangOpts.MicrosoftExt)
7233       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7234     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7235     Result += llvm::utostr(ClsDefCount); Result += "]";
7236     Result += 
7237       " __attribute__((used, section (\"__DATA, __objc_classlist,"
7238       "regular,no_dead_strip\")))= {\n";
7239     for (int i = 0; i < ClsDefCount; i++) {
7240       Result += "\t&OBJC_CLASS_$_";
7241       Result += ClassImplementation[i]->getNameAsString();
7242       Result += ",\n";
7243     }
7244     Result += "};\n";
7245     
7246     if (!DefinedNonLazyClasses.empty()) {
7247       if (LangOpts.MicrosoftExt)
7248         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7249       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7250       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7251         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7252         Result += ",\n";
7253       }
7254       Result += "};\n";
7255     }
7256   }
7257   
7258   if (CatDefCount > 0) {
7259     if (LangOpts.MicrosoftExt)
7260       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7261     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7262     Result += llvm::utostr(CatDefCount); Result += "]";
7263     Result += 
7264     " __attribute__((used, section (\"__DATA, __objc_catlist,"
7265     "regular,no_dead_strip\")))= {\n";
7266     for (int i = 0; i < CatDefCount; i++) {
7267       Result += "\t&_OBJC_$_CATEGORY_";
7268       Result += 
7269         CategoryImplementation[i]->getClassInterface()->getNameAsString(); 
7270       Result += "_$_";
7271       Result += CategoryImplementation[i]->getNameAsString();
7272       Result += ",\n";
7273     }
7274     Result += "};\n";
7275   }
7276   
7277   if (!DefinedNonLazyCategories.empty()) {
7278     if (LangOpts.MicrosoftExt)
7279       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7280     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7281     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7282       Result += "\t&_OBJC_$_CATEGORY_";
7283       Result += 
7284         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); 
7285       Result += "_$_";
7286       Result += DefinedNonLazyCategories[i]->getNameAsString();
7287       Result += ",\n";
7288     }
7289     Result += "};\n";
7290   }
7291 }
7292
7293 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7294   if (LangOpts.MicrosoftExt)
7295     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7296   
7297   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7298   // version 0, ObjCABI is 2
7299   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7300 }
7301
7302 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7303 /// implementation.
7304 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7305                                               std::string &Result) {
7306   WriteModernMetadataDeclarations(Context, Result);
7307   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7308   // Find category declaration for this implementation.
7309   ObjCCategoryDecl *CDecl=0;
7310   for (CDecl = ClassDecl->getCategoryList(); CDecl;
7311        CDecl = CDecl->getNextClassCategory())
7312     if (CDecl->getIdentifier() == IDecl->getIdentifier())
7313       break;
7314   
7315   std::string FullCategoryName = ClassDecl->getNameAsString();
7316   FullCategoryName += "_$_";
7317   FullCategoryName += CDecl->getNameAsString();
7318   
7319   // Build _objc_method_list for class's instance methods if needed
7320   SmallVector<ObjCMethodDecl *, 32>
7321   InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7322   
7323   // If any of our property implementations have associated getters or
7324   // setters, produce metadata for them as well.
7325   for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7326        PropEnd = IDecl->propimpl_end();
7327        Prop != PropEnd; ++Prop) {
7328     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7329       continue;
7330     if (!Prop->getPropertyIvarDecl())
7331       continue;
7332     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7333     if (!PD)
7334       continue;
7335     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7336       InstanceMethods.push_back(Getter);
7337     if (PD->isReadOnly())
7338       continue;
7339     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7340       InstanceMethods.push_back(Setter);
7341   }
7342   
7343   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7344                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7345                                   FullCategoryName, true);
7346   
7347   SmallVector<ObjCMethodDecl *, 32>
7348     ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7349   
7350   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7351                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
7352                                   FullCategoryName, true);
7353   
7354   // Protocols referenced in class declaration?
7355   // Protocol's super protocol list
7356   std::vector<ObjCProtocolDecl *> RefedProtocols;
7357   for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7358                                             E = CDecl->protocol_end();
7359
7360          I != E; ++I) {
7361     RefedProtocols.push_back(*I);
7362     // Must write out all protocol definitions in current qualifier list,
7363     // and in their nested qualifiers before writing out current definition.
7364     RewriteObjCProtocolMetaData(*I, Result);
7365   }
7366   
7367   Write_protocol_list_initializer(Context, Result, 
7368                                   RefedProtocols,
7369                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
7370                                   FullCategoryName);
7371   
7372   // Protocol's property metadata.
7373   std::vector<ObjCPropertyDecl *> ClassProperties;
7374   for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7375        E = CDecl->prop_end(); I != E; ++I)
7376     ClassProperties.push_back(*I);
7377   
7378   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7379                                 /* Container */IDecl,
7380                                 "_OBJC_$_PROP_LIST_",
7381                                 FullCategoryName);
7382   
7383   Write_category_t(*this, Context, Result,
7384                    CDecl,
7385                    ClassDecl,
7386                    InstanceMethods,
7387                    ClassMethods,
7388                    RefedProtocols,
7389                    ClassProperties);
7390   
7391   // Determine if this category is also "non-lazy".
7392   if (ImplementationIsNonLazy(IDecl))
7393     DefinedNonLazyCategories.push_back(CDecl);
7394     
7395 }
7396
7397 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7398   int CatDefCount = CategoryImplementation.size();
7399   if (!CatDefCount)
7400     return;
7401   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7402   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7403   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7404   for (int i = 0; i < CatDefCount; i++) {
7405     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7406     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7407     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7408     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7409     Result += ClassDecl->getName();
7410     Result += "_$_";
7411     Result += CatDecl->getName();
7412     Result += ",\n";
7413   }
7414   Result += "};\n";
7415 }
7416
7417 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7418 /// class methods.
7419 template<typename MethodIterator>
7420 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7421                                              MethodIterator MethodEnd,
7422                                              bool IsInstanceMethod,
7423                                              StringRef prefix,
7424                                              StringRef ClassName,
7425                                              std::string &Result) {
7426   if (MethodBegin == MethodEnd) return;
7427   
7428   if (!objc_impl_method) {
7429     /* struct _objc_method {
7430      SEL _cmd;
7431      char *method_types;
7432      void *_imp;
7433      }
7434      */
7435     Result += "\nstruct _objc_method {\n";
7436     Result += "\tSEL _cmd;\n";
7437     Result += "\tchar *method_types;\n";
7438     Result += "\tvoid *_imp;\n";
7439     Result += "};\n";
7440     
7441     objc_impl_method = true;
7442   }
7443   
7444   // Build _objc_method_list for class's methods if needed
7445   
7446   /* struct  {
7447    struct _objc_method_list *next_method;
7448    int method_count;
7449    struct _objc_method method_list[];
7450    }
7451    */
7452   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7453   Result += "\n";
7454   if (LangOpts.MicrosoftExt) {
7455     if (IsInstanceMethod)
7456       Result += "__declspec(allocate(\".inst_meth$B\")) ";
7457     else
7458       Result += "__declspec(allocate(\".cls_meth$B\")) ";
7459   }
7460   Result += "static struct {\n";
7461   Result += "\tstruct _objc_method_list *next_method;\n";
7462   Result += "\tint method_count;\n";
7463   Result += "\tstruct _objc_method method_list[";
7464   Result += utostr(NumMethods);
7465   Result += "];\n} _OBJC_";
7466   Result += prefix;
7467   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7468   Result += "_METHODS_";
7469   Result += ClassName;
7470   Result += " __attribute__ ((used, section (\"__OBJC, __";
7471   Result += IsInstanceMethod ? "inst" : "cls";
7472   Result += "_meth\")))= ";
7473   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7474   
7475   Result += "\t,{{(SEL)\"";
7476   Result += (*MethodBegin)->getSelector().getAsString().c_str();
7477   std::string MethodTypeString;
7478   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7479   Result += "\", \"";
7480   Result += MethodTypeString;
7481   Result += "\", (void *)";
7482   Result += MethodInternalNames[*MethodBegin];
7483   Result += "}\n";
7484   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7485     Result += "\t  ,{(SEL)\"";
7486     Result += (*MethodBegin)->getSelector().getAsString().c_str();
7487     std::string MethodTypeString;
7488     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7489     Result += "\", \"";
7490     Result += MethodTypeString;
7491     Result += "\", (void *)";
7492     Result += MethodInternalNames[*MethodBegin];
7493     Result += "}\n";
7494   }
7495   Result += "\t }\n};\n";
7496 }
7497
7498 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7499   SourceRange OldRange = IV->getSourceRange();
7500   Expr *BaseExpr = IV->getBase();
7501   
7502   // Rewrite the base, but without actually doing replaces.
7503   {
7504     DisableReplaceStmtScope S(*this);
7505     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7506     IV->setBase(BaseExpr);
7507   }
7508   
7509   ObjCIvarDecl *D = IV->getDecl();
7510   
7511   Expr *Replacement = IV;
7512   
7513     if (BaseExpr->getType()->isObjCObjectPointerType()) {
7514       const ObjCInterfaceType *iFaceDecl =
7515         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7516       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7517       // lookup which class implements the instance variable.
7518       ObjCInterfaceDecl *clsDeclared = 0;
7519       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7520                                                    clsDeclared);
7521       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7522       
7523       // Build name of symbol holding ivar offset.
7524       std::string IvarOffsetName;
7525       WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7526       
7527       ReferencedIvars[clsDeclared].insert(D);
7528       
7529       // cast offset to "char *".
7530       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, 
7531                                                     Context->getPointerType(Context->CharTy),
7532                                                     CK_BitCast,
7533                                                     BaseExpr);
7534       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7535                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
7536                                        Context->UnsignedLongTy, 0, SC_Extern, SC_None);
7537       DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7538                                                    Context->UnsignedLongTy, VK_LValue,
7539                                                    SourceLocation());
7540       BinaryOperator *addExpr = 
7541         new (Context) BinaryOperator(castExpr, DRE, BO_Add, 
7542                                      Context->getPointerType(Context->CharTy),
7543                                      VK_RValue, OK_Ordinary, SourceLocation(), false);
7544       // Don't forget the parens to enforce the proper binding.
7545       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7546                                               SourceLocation(),
7547                                               addExpr);
7548       QualType IvarT = D->getType();
7549
7550       if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7551         RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7552         RD = RD->getDefinition();
7553         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7554           // decltype(((Foo_IMPL*)0)->bar) *
7555           ObjCContainerDecl *CDecl = 
7556             dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7557           // ivar in class extensions requires special treatment.
7558           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7559             CDecl = CatDecl->getClassInterface();
7560           std::string RecName = CDecl->getName();
7561           RecName += "_IMPL";
7562           RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7563                                               SourceLocation(), SourceLocation(),
7564                                               &Context->Idents.get(RecName.c_str()));
7565           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7566           unsigned UnsignedIntSize = 
7567             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7568           Expr *Zero = IntegerLiteral::Create(*Context,
7569                                               llvm::APInt(UnsignedIntSize, 0),
7570                                               Context->UnsignedIntTy, SourceLocation());
7571           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7572           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7573                                                   Zero);
7574           FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7575                                             SourceLocation(),
7576                                             &Context->Idents.get(D->getNameAsString()),
7577                                             IvarT, 0,
7578                                             /*BitWidth=*/0, /*Mutable=*/true,
7579                                             ICIS_NoInit);
7580           MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7581                                                     FD->getType(), VK_LValue,
7582                                                     OK_Ordinary);
7583           IvarT = Context->getDecltypeType(ME, ME->getType());
7584         }
7585       }
7586       convertObjCTypeToCStyleType(IvarT);
7587       QualType castT = Context->getPointerType(IvarT);
7588           
7589       castExpr = NoTypeInfoCStyleCastExpr(Context, 
7590                                           castT,
7591                                           CK_BitCast,
7592                                           PE);
7593       
7594       
7595       Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7596                                               VK_LValue, OK_Ordinary,
7597                                               SourceLocation());
7598       PE = new (Context) ParenExpr(OldRange.getBegin(),
7599                                    OldRange.getEnd(),
7600                                    Exp);
7601
7602       Replacement = PE;
7603     }
7604   
7605     ReplaceStmtWithRange(IV, Replacement, OldRange);
7606     return Replacement;  
7607 }