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