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