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