xref: /llvm-project/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp (revision 671088be4e7883f9907d22bb64248996a33f9bae)
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/AST/AST.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Config/config.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Rewrite/Core/Rewriter.h"
25 #include "clang/Rewrite/Frontend/ASTConsumers.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <memory>
33 
34 #if CLANG_ENABLE_OBJC_REWRITER
35 
36 using namespace clang;
37 using llvm::RewriteBuffer;
38 using llvm::utostr;
39 
40 namespace {
41   class RewriteModernObjC : public ASTConsumer {
42   protected:
43 
44     enum {
45       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
46                                         block, ... */
47       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
48       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
49                                         __block variable */
50       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
51                                         helpers */
52       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
53                                         support routines */
54       BLOCK_BYREF_CURRENT_MAX = 256
55     };
56 
57     enum {
58       BLOCK_NEEDS_FREE =        (1 << 24),
59       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
60       BLOCK_HAS_CXX_OBJ =       (1 << 26),
61       BLOCK_IS_GC =             (1 << 27),
62       BLOCK_IS_GLOBAL =         (1 << 28),
63       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
64     };
65 
66     Rewriter Rewrite;
67     DiagnosticsEngine &Diags;
68     const LangOptions &LangOpts;
69     ASTContext *Context;
70     SourceManager *SM;
71     TranslationUnitDecl *TUDecl;
72     FileID MainFileID;
73     const char *MainFileStart, *MainFileEnd;
74     Stmt *CurrentBody;
75     ParentMap *PropParentMap; // created lazily.
76     std::string InFileName;
77     std::unique_ptr<raw_ostream> OutFile;
78     std::string Preamble;
79 
80     TypeDecl *ProtocolTypeDecl;
81     VarDecl *GlobalVarDecl;
82     Expr *GlobalConstructionExp;
83     unsigned RewriteFailedDiag;
84     unsigned GlobalBlockRewriteFailedDiag;
85     // ObjC string constant support.
86     unsigned NumObjCStringLiterals;
87     VarDecl *ConstantStringClassReference;
88     RecordDecl *NSStringRecord;
89 
90     // ObjC foreach break/continue generation support.
91     int BcLabelCount;
92 
93     unsigned TryFinallyContainsReturnDiag;
94     // Needed for super.
95     ObjCMethodDecl *CurMethodDef;
96     RecordDecl *SuperStructDecl;
97     RecordDecl *ConstantStringDecl;
98 
99     FunctionDecl *MsgSendFunctionDecl;
100     FunctionDecl *MsgSendSuperFunctionDecl;
101     FunctionDecl *MsgSendStretFunctionDecl;
102     FunctionDecl *MsgSendSuperStretFunctionDecl;
103     FunctionDecl *MsgSendFpretFunctionDecl;
104     FunctionDecl *GetClassFunctionDecl;
105     FunctionDecl *GetMetaClassFunctionDecl;
106     FunctionDecl *GetSuperClassFunctionDecl;
107     FunctionDecl *SelGetUidFunctionDecl;
108     FunctionDecl *CFStringFunctionDecl;
109     FunctionDecl *SuperConstructorFunctionDecl;
110     FunctionDecl *CurFunctionDef;
111 
112     /* Misc. containers needed for meta-data rewrite. */
113     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
114     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
115     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
116     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
117     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
118     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
119     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
120     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
121     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
122 
123     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
124     SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
125 
126     SmallVector<Stmt *, 32> Stmts;
127     SmallVector<int, 8> ObjCBcLabelNo;
128     // Remember all the @protocol(<expr>) expressions.
129     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
130 
131     llvm::DenseSet<uint64_t> CopyDestroyCache;
132 
133     // Block expressions.
134     SmallVector<BlockExpr *, 32> Blocks;
135     SmallVector<int, 32> InnerDeclRefsCount;
136     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
137 
138     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
139 
140     // Block related declarations.
141     llvm::SmallSetVector<ValueDecl *, 8> BlockByCopyDecls;
142     llvm::SmallSetVector<ValueDecl *, 8> BlockByRefDecls;
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 
276       // If replacement succeeded or warning disabled return with no warning.
277       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, SStr)) {
278         ReplacedNodes[Old] = New;
279         return;
280       }
281       if (SilenceRewriteMacroWarning)
282         return;
283       Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
284           << Old->getSourceRange();
285     }
286 
287     void InsertText(SourceLocation Loc, StringRef Str,
288                     bool InsertAfter = true) {
289       // If insertion succeeded or warning disabled return with no warning.
290       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
291           SilenceRewriteMacroWarning)
292         return;
293 
294       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
295     }
296 
297     void ReplaceText(SourceLocation Start, unsigned OrigLength,
298                      StringRef Str) {
299       // If removal succeeded or warning disabled return with no warning.
300       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
301           SilenceRewriteMacroWarning)
302         return;
303 
304       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
305     }
306 
307     // Syntactic Rewriting.
308     void RewriteRecordBody(RecordDecl *RD);
309     void RewriteInclude();
310     void RewriteLineDirective(const Decl *D);
311     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
312                                               std::string &LineString);
313     void RewriteForwardClassDecl(DeclGroupRef D);
314     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
315     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
316                                      const std::string &typedefString);
317     void RewriteImplementations();
318     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
319                                  ObjCImplementationDecl *IMD,
320                                  ObjCCategoryImplDecl *CID);
321     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
322     void RewriteImplementationDecl(Decl *Dcl);
323     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
324                                ObjCMethodDecl *MDecl, std::string &ResultStr);
325     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
326                                const FunctionType *&FPRetType);
327     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
328                             ValueDecl *VD, bool def=false);
329     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
330     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
331     void RewriteForwardProtocolDecl(DeclGroupRef D);
332     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
333     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
334     void RewriteProperty(ObjCPropertyDecl *prop);
335     void RewriteFunctionDecl(FunctionDecl *FD);
336     void RewriteBlockPointerType(std::string& Str, QualType Type);
337     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
338     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
339     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
340     void RewriteTypeOfDecl(VarDecl *VD);
341     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
342 
343     std::string getIvarAccessString(ObjCIvarDecl *D);
344 
345     // Expression Rewriting.
346     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
347     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
348     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
349     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
350     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
351     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
352     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
353     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
354     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
355     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
356     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
357     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
358     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
359     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
360     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
361     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
362     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
363                                        SourceLocation OrigEnd);
364     Stmt *RewriteBreakStmt(BreakStmt *S);
365     Stmt *RewriteContinueStmt(ContinueStmt *S);
366     void RewriteCastExpr(CStyleCastExpr *CE);
367     void RewriteImplicitCastObjCExpr(CastExpr *IE);
368 
369     // Computes ivar bitfield group no.
370     unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
371     // Names field decl. for ivar bitfield group.
372     void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
373     // Names struct type for ivar bitfield group.
374     void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
375     // Names symbol for ivar bitfield group field offset.
376     void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
377     // Given an ivar bitfield, it builds (or finds) its group record type.
378     QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
379     QualType SynthesizeBitfieldGroupStructType(
380                                     ObjCIvarDecl *IV,
381                                     SmallVectorImpl<ObjCIvarDecl *> &IVars);
382 
383     // Block rewriting.
384     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
385 
386     // Block specific rewrite rules.
387     void RewriteBlockPointerDecl(NamedDecl *VD);
388     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
389     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
390     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
391     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
392 
393     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
394                                       std::string &Result);
395 
396     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
397     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
398                                  bool &IsNamedDefinition);
399     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
400                                               std::string &Result);
401 
402     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
403 
404     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
405                                   std::string &Result);
406 
407     void Initialize(ASTContext &context) override;
408 
409     // Misc. AST transformation routines. Sometimes they end up calling
410     // rewriting routines on the new ASTs.
411     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
412                                            ArrayRef<Expr *> Args,
413                                            SourceLocation StartLoc=SourceLocation(),
414                                            SourceLocation EndLoc=SourceLocation());
415 
416     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
417                                         QualType returnType,
418                                         SmallVectorImpl<QualType> &ArgTypes,
419                                         SmallVectorImpl<Expr*> &MsgExprs,
420                                         ObjCMethodDecl *Method);
421 
422     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
423                            SourceLocation StartLoc=SourceLocation(),
424                            SourceLocation EndLoc=SourceLocation());
425 
426     void SynthCountByEnumWithState(std::string &buf);
427     void SynthMsgSendFunctionDecl();
428     void SynthMsgSendSuperFunctionDecl();
429     void SynthMsgSendStretFunctionDecl();
430     void SynthMsgSendFpretFunctionDecl();
431     void SynthMsgSendSuperStretFunctionDecl();
432     void SynthGetClassFunctionDecl();
433     void SynthGetMetaClassFunctionDecl();
434     void SynthGetSuperClassFunctionDecl();
435     void SynthSelGetUidFunctionDecl();
436     void SynthSuperConstructorFunctionDecl();
437 
438     // Rewriting metadata
439     template<typename MethodIterator>
440     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
441                                     MethodIterator MethodEnd,
442                                     bool IsInstanceMethod,
443                                     StringRef prefix,
444                                     StringRef ClassName,
445                                     std::string &Result);
446     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
447                                      std::string &Result);
448     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
449                                           std::string &Result);
450     void RewriteClassSetupInitHook(std::string &Result);
451 
452     void RewriteMetaDataIntoBuffer(std::string &Result);
453     void WriteImageInfo(std::string &Result);
454     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
455                                              std::string &Result);
456     void RewriteCategorySetupInitHook(std::string &Result);
457 
458     // Rewriting ivar
459     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
460                                               std::string &Result);
461     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
462 
463 
464     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
465     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
466                                            StringRef funcName,
467                                            const std::string &Tag);
468     std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName,
469                                     const std::string &Tag);
470     std::string SynthesizeBlockImpl(BlockExpr *CE, const std::string &Tag,
471                                     const std::string &Desc);
472     std::string SynthesizeBlockDescriptor(const std::string &DescTag,
473                                           const std::string &ImplTag, int i,
474                                           StringRef funcName, unsigned hasCopy);
475     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
476     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
477                                  StringRef FunName);
478     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
479     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
480                       const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
481 
482     // Misc. helper routines.
483     QualType getProtocolType();
484     void WarnAboutReturnGotoStmts(Stmt *S);
485     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
486     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
487     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
488 
489     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
490     void CollectBlockDeclRefInfo(BlockExpr *Exp);
491     void GetBlockDeclRefExprs(Stmt *S);
492     void GetInnerBlockDeclRefExprs(Stmt *S,
493                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
494                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
495 
496     // We avoid calling Type::isBlockPointerType(), since it operates on the
497     // canonical type. We only care if the top-level type is a closure pointer.
498     bool isTopLevelBlockPointerType(QualType T) {
499       return isa<BlockPointerType>(T);
500     }
501 
502     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
503     /// to a function pointer type and upon success, returns true; false
504     /// otherwise.
505     bool convertBlockPointerToFunctionPointer(QualType &T) {
506       if (isTopLevelBlockPointerType(T)) {
507         const auto *BPT = T->castAs<BlockPointerType>();
508         T = Context->getPointerType(BPT->getPointeeType());
509         return true;
510       }
511       return false;
512     }
513 
514     bool convertObjCTypeToCStyleType(QualType &T);
515 
516     bool needToScanForQualifiers(QualType T);
517     QualType getSuperStructType();
518     QualType getConstantStringStructType();
519     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
520 
521     void convertToUnqualifiedObjCType(QualType &T) {
522       if (T->isObjCQualifiedIdType()) {
523         bool isConst = T.isConstQualified();
524         T = isConst ? Context->getObjCIdType().withConst()
525                     : Context->getObjCIdType();
526       }
527       else if (T->isObjCQualifiedClassType())
528         T = Context->getObjCClassType();
529       else if (T->isObjCObjectPointerType() &&
530                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
531         if (const ObjCObjectPointerType * OBJPT =
532               T->getAsObjCInterfacePointerType()) {
533           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
534           T = QualType(IFaceT, 0);
535           T = Context->getPointerType(T);
536         }
537      }
538     }
539 
540     // FIXME: This predicate seems like it would be useful to add to ASTContext.
541     bool isObjCType(QualType T) {
542       if (!LangOpts.ObjC)
543         return false;
544 
545       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
546 
547       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
548           OCT == Context->getCanonicalType(Context->getObjCClassType()))
549         return true;
550 
551       if (const PointerType *PT = OCT->getAs<PointerType>()) {
552         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
553             PT->getPointeeType()->isObjCQualifiedIdType())
554           return true;
555       }
556       return false;
557     }
558 
559     bool PointerTypeTakesAnyBlockArguments(QualType QT);
560     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
561     void GetExtentOfArgList(const char *Name, const char *&LParen,
562                             const char *&RParen);
563 
564     void QuoteDoublequotes(std::string &From, std::string &To) {
565       for (unsigned i = 0; i < From.length(); i++) {
566         if (From[i] == '"')
567           To += "\\\"";
568         else
569           To += From[i];
570       }
571     }
572 
573     QualType getSimpleFunctionType(QualType result,
574                                    ArrayRef<QualType> args,
575                                    bool variadic = false) {
576       if (result == Context->getObjCInstanceType())
577         result =  Context->getObjCIdType();
578       FunctionProtoType::ExtProtoInfo fpi;
579       fpi.Variadic = variadic;
580       return Context->getFunctionType(result, args, fpi);
581     }
582 
583     // Helper function: create a CStyleCastExpr with trivial type source info.
584     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
585                                              CastKind Kind, Expr *E) {
586       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
587       return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
588                                     FPOptionsOverride(), TInfo,
589                                     SourceLocation(), SourceLocation());
590     }
591 
592     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593       const 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           ArraySizeModifier::Normal, 0);
602       return StringLiteral::Create(*Context, Str, StringLiteralKind::Ordinary,
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 = Filename.substr(DotPos + 1);
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   llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(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 (!IvarT->getAs<TypedefType>() && 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 = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
866                                           SourceLocation(), SourceLocation(),
867                                           &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 (ObjCAtCatchStmt *Catch : S->catch_stmts()) {
1960     VarDecl *catchDecl = Catch->getCatchParamDecl();
1961 
1962     startLoc = Catch->getBeginLoc();
1963     bool AtRemoved = false;
1964     if (catchDecl) {
1965       QualType t = catchDecl->getType();
1966       if (const ObjCObjectPointerType *Ptr =
1967               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_PRValue, FPOptionsOverride());
2110 
2111   const auto *FT = msgSendType->castAs<FunctionType>();
2112   CallExpr *Exp =
2113       CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2114                        VK_PRValue, 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 += prettyBufS;
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_PRValue, 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_PRValue, 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_PRValue, 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_PRValue, 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_PRValue, 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_PRValue, 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(
2980         *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
2981         SourceLocation(), &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(
3008         *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
3009         SourceLocation(), &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_PRValue, 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(NoTypeInfoCStyleCastExpr(
3245         Context, Context->getObjCIdType(), CK_BitCast,
3246         new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3247                                   Context->getObjCIdType(), VK_PRValue,
3248                                   SourceLocation()))); // set the 'receiver'.
3249 
3250     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3251     SmallVector<Expr*, 8> ClsExprs;
3252     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3253     // (Class)objc_getClass("CurrentClass")
3254     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3255                                                  ClsExprs, StartLoc, EndLoc);
3256     ClsExprs.clear();
3257     ClsExprs.push_back(Cls);
3258     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3259                                        StartLoc, EndLoc);
3260 
3261     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262     // To turn off a warning, type-cast to 'id'
3263     InitExprs.push_back( // set 'super class', using class_getSuperclass().
3264                         NoTypeInfoCStyleCastExpr(Context,
3265                                                  Context->getObjCIdType(),
3266                                                  CK_BitCast, Cls));
3267     // struct __rw_objc_super
3268     QualType superType = getSuperStructType();
3269     Expr *SuperRep;
3270 
3271     if (LangOpts.MicrosoftExt) {
3272       SynthSuperConstructorFunctionDecl();
3273       // Simulate a constructor call...
3274       DeclRefExpr *DRE = new (Context)
3275           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3276                       VK_LValue, SourceLocation());
3277       SuperRep =
3278           CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3279                            SourceLocation(), FPOptionsOverride());
3280       // The code for super is a little tricky to prevent collision with
3281       // the structure definition in the header. The rewriter has it's own
3282       // internal definition (__rw_objc_super) that is uses. This is why
3283       // we need the cast below. For example:
3284       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3285       //
3286       SuperRep = UnaryOperator::Create(
3287           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3288           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3289           SourceLocation(), false, FPOptionsOverride());
3290       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3291                                           Context->getPointerType(superType),
3292                                           CK_BitCast, SuperRep);
3293     } else {
3294       // (struct __rw_objc_super) { <exprs from above> }
3295       InitListExpr *ILE =
3296         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3297                                    SourceLocation());
3298       TypeSourceInfo *superTInfo
3299         = Context->getTrivialTypeSourceInfo(superType);
3300       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3301                                                    superType, VK_LValue,
3302                                                    ILE, false);
3303       // struct __rw_objc_super *
3304       SuperRep = UnaryOperator::Create(
3305           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3306           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3307           SourceLocation(), false, FPOptionsOverride());
3308     }
3309     MsgExprs.push_back(SuperRep);
3310     break;
3311   }
3312 
3313   case ObjCMessageExpr::Class: {
3314     SmallVector<Expr*, 8> ClsExprs;
3315     ObjCInterfaceDecl *Class
3316       = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3317     IdentifierInfo *clsName = Class->getIdentifier();
3318     ClsExprs.push_back(getStringLiteral(clsName->getName()));
3319     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3320                                                  StartLoc, EndLoc);
3321     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3322                                                  Context->getObjCIdType(),
3323                                                  CK_BitCast, Cls);
3324     MsgExprs.push_back(ArgExpr);
3325     break;
3326   }
3327 
3328   case ObjCMessageExpr::SuperInstance:{
3329     MsgSendFlavor = MsgSendSuperFunctionDecl;
3330     if (MsgSendStretFlavor)
3331       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3332     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3333     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3334     SmallVector<Expr*, 4> InitExprs;
3335 
3336     InitExprs.push_back(NoTypeInfoCStyleCastExpr(
3337         Context, Context->getObjCIdType(), CK_BitCast,
3338         new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
3339                                   Context->getObjCIdType(), VK_PRValue,
3340                                   SourceLocation()))); // set the 'receiver'.
3341 
3342     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3343     SmallVector<Expr*, 8> ClsExprs;
3344     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3345     // (Class)objc_getClass("CurrentClass")
3346     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3347                                                  StartLoc, EndLoc);
3348     ClsExprs.clear();
3349     ClsExprs.push_back(Cls);
3350     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3351                                        StartLoc, EndLoc);
3352 
3353     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3354     // To turn off a warning, type-cast to 'id'
3355     InitExprs.push_back(
3356       // set 'super class', using class_getSuperclass().
3357       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3358                                CK_BitCast, Cls));
3359     // struct __rw_objc_super
3360     QualType superType = getSuperStructType();
3361     Expr *SuperRep;
3362 
3363     if (LangOpts.MicrosoftExt) {
3364       SynthSuperConstructorFunctionDecl();
3365       // Simulate a constructor call...
3366       DeclRefExpr *DRE = new (Context)
3367           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3368                       VK_LValue, SourceLocation());
3369       SuperRep =
3370           CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
3371                            SourceLocation(), FPOptionsOverride());
3372       // The code for super is a little tricky to prevent collision with
3373       // the structure definition in the header. The rewriter has it's own
3374       // internal definition (__rw_objc_super) that is uses. This is why
3375       // we need the cast below. For example:
3376       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3377       //
3378       SuperRep = UnaryOperator::Create(
3379           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
3380           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
3381           SourceLocation(), false, FPOptionsOverride());
3382       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3383                                Context->getPointerType(superType),
3384                                CK_BitCast, SuperRep);
3385     } else {
3386       // (struct __rw_objc_super) { <exprs from above> }
3387       InitListExpr *ILE =
3388         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3389                                    SourceLocation());
3390       TypeSourceInfo *superTInfo
3391         = Context->getTrivialTypeSourceInfo(superType);
3392       SuperRep = new (Context) CompoundLiteralExpr(
3393           SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
3394     }
3395     MsgExprs.push_back(SuperRep);
3396     break;
3397   }
3398 
3399   case ObjCMessageExpr::Instance: {
3400     // Remove all type-casts because it may contain objc-style types; e.g.
3401     // Foo<Proto> *.
3402     Expr *recExpr = Exp->getInstanceReceiver();
3403     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3404       recExpr = CE->getSubExpr();
3405     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3406                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3407                                      ? CK_BlockPointerToObjCPointerCast
3408                                      : CK_CPointerToObjCPointerCast;
3409 
3410     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3411                                        CK, recExpr);
3412     MsgExprs.push_back(recExpr);
3413     break;
3414   }
3415   }
3416 
3417   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3418   SmallVector<Expr*, 8> SelExprs;
3419   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3420   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3421                                                   SelExprs, StartLoc, EndLoc);
3422   MsgExprs.push_back(SelExp);
3423 
3424   // Now push any user supplied arguments.
3425   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3426     Expr *userExpr = Exp->getArg(i);
3427     // Make all implicit casts explicit...ICE comes in handy:-)
3428     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3429       // Reuse the ICE type, it is exactly what the doctor ordered.
3430       QualType type = ICE->getType();
3431       if (needToScanForQualifiers(type))
3432         type = Context->getObjCIdType();
3433       // Make sure we convert "type (^)(...)" to "type (*)(...)".
3434       (void)convertBlockPointerToFunctionPointer(type);
3435       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3436       CastKind CK;
3437       if (SubExpr->getType()->isIntegralType(*Context) &&
3438           type->isBooleanType()) {
3439         CK = CK_IntegralToBoolean;
3440       } else if (type->isObjCObjectPointerType()) {
3441         if (SubExpr->getType()->isBlockPointerType()) {
3442           CK = CK_BlockPointerToObjCPointerCast;
3443         } else if (SubExpr->getType()->isPointerType()) {
3444           CK = CK_CPointerToObjCPointerCast;
3445         } else {
3446           CK = CK_BitCast;
3447         }
3448       } else {
3449         CK = CK_BitCast;
3450       }
3451 
3452       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3453     }
3454     // Make id<P...> cast into an 'id' cast.
3455     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3456       if (CE->getType()->isObjCQualifiedIdType()) {
3457         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3458           userExpr = CE->getSubExpr();
3459         CastKind CK;
3460         if (userExpr->getType()->isIntegralType(*Context)) {
3461           CK = CK_IntegralToPointer;
3462         } else if (userExpr->getType()->isBlockPointerType()) {
3463           CK = CK_BlockPointerToObjCPointerCast;
3464         } else if (userExpr->getType()->isPointerType()) {
3465           CK = CK_CPointerToObjCPointerCast;
3466         } else {
3467           CK = CK_BitCast;
3468         }
3469         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3470                                             CK, userExpr);
3471       }
3472     }
3473     MsgExprs.push_back(userExpr);
3474     // We've transferred the ownership to MsgExprs. For now, we *don't* null
3475     // out the argument in the original expression (since we aren't deleting
3476     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3477     //Exp->setArg(i, 0);
3478   }
3479   // Generate the funky cast.
3480   CastExpr *cast;
3481   SmallVector<QualType, 8> ArgTypes;
3482   QualType returnType;
3483 
3484   // Push 'id' and 'SEL', the 2 implicit arguments.
3485   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3486     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3487   else
3488     ArgTypes.push_back(Context->getObjCIdType());
3489   ArgTypes.push_back(Context->getObjCSelType());
3490   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3491     // Push any user argument types.
3492     for (const auto *PI : OMD->parameters()) {
3493       QualType t = PI->getType()->isObjCQualifiedIdType()
3494                      ? Context->getObjCIdType()
3495                      : PI->getType();
3496       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3497       (void)convertBlockPointerToFunctionPointer(t);
3498       ArgTypes.push_back(t);
3499     }
3500     returnType = Exp->getType();
3501     convertToUnqualifiedObjCType(returnType);
3502     (void)convertBlockPointerToFunctionPointer(returnType);
3503   } else {
3504     returnType = Context->getObjCIdType();
3505   }
3506   // Get the type, we will need to reference it in a couple spots.
3507   QualType msgSendType = MsgSendFlavor->getType();
3508 
3509   // Create a reference to the objc_msgSend() declaration.
3510   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3511       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3512 
3513   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3514   // If we don't do this cast, we get the following bizarre warning/note:
3515   // xx.m:13: warning: function called through a non-compatible type
3516   // xx.m:13: note: if this code is reached, the program will abort
3517   cast = NoTypeInfoCStyleCastExpr(Context,
3518                                   Context->getPointerType(Context->VoidTy),
3519                                   CK_BitCast, DRE);
3520 
3521   // Now do the "normal" pointer to function cast.
3522   // If we don't have a method decl, force a variadic cast.
3523   const ObjCMethodDecl *MD = Exp->getMethodDecl();
3524   QualType castType =
3525     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3526   castType = Context->getPointerType(castType);
3527   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3528                                   cast);
3529 
3530   // Don't forget the parens to enforce the proper binding.
3531   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3532 
3533   const FunctionType *FT = msgSendType->castAs<FunctionType>();
3534   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3535                                   VK_PRValue, EndLoc, FPOptionsOverride());
3536   Stmt *ReplacingStmt = CE;
3537   if (MsgSendStretFlavor) {
3538     // We have the method which returns a struct/union. Must also generate
3539     // call to objc_msgSend_stret and hang both varieties on a conditional
3540     // expression which dictate which one to envoke depending on size of
3541     // method's return type.
3542 
3543     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3544                                            returnType,
3545                                            ArgTypes, MsgExprs,
3546                                            Exp->getMethodDecl());
3547     ReplacingStmt = STCE;
3548   }
3549   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3550   return ReplacingStmt;
3551 }
3552 
3553 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3554   Stmt *ReplacingStmt =
3555       SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3556 
3557   // Now do the actual rewrite.
3558   ReplaceStmt(Exp, ReplacingStmt);
3559 
3560   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3561   return ReplacingStmt;
3562 }
3563 
3564 // typedef struct objc_object Protocol;
3565 QualType RewriteModernObjC::getProtocolType() {
3566   if (!ProtocolTypeDecl) {
3567     TypeSourceInfo *TInfo
3568       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3569     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3570                                            SourceLocation(), SourceLocation(),
3571                                            &Context->Idents.get("Protocol"),
3572                                            TInfo);
3573   }
3574   return Context->getTypeDeclType(ProtocolTypeDecl);
3575 }
3576 
3577 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3578 /// a synthesized/forward data reference (to the protocol's metadata).
3579 /// The forward references (and metadata) are generated in
3580 /// RewriteModernObjC::HandleTranslationUnit().
3581 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3582   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3583                       Exp->getProtocol()->getNameAsString();
3584   IdentifierInfo *ID = &Context->Idents.get(Name);
3585   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3586                                 SourceLocation(), ID, getProtocolType(),
3587                                 nullptr, SC_Extern);
3588   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3589       *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3590   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3591       Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3592   ReplaceStmt(Exp, castExpr);
3593   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3594   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3595   return castExpr;
3596 }
3597 
3598 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3599 /// is defined inside an objective-c class. If so, it returns true.
3600 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3601                                                 TagDecl *Tag,
3602                                                 bool &IsNamedDefinition) {
3603   if (!IDecl)
3604     return false;
3605   SourceLocation TagLocation;
3606   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3607     RD = RD->getDefinition();
3608     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3609       return false;
3610     IsNamedDefinition = true;
3611     TagLocation = RD->getLocation();
3612     return Context->getSourceManager().isBeforeInTranslationUnit(
3613                                           IDecl->getLocation(), TagLocation);
3614   }
3615   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3616     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3617       return false;
3618     IsNamedDefinition = true;
3619     TagLocation = ED->getLocation();
3620     return Context->getSourceManager().isBeforeInTranslationUnit(
3621                                           IDecl->getLocation(), TagLocation);
3622   }
3623   return false;
3624 }
3625 
3626 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3627 /// It handles elaborated types, as well as enum types in the process.
3628 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3629                                                  std::string &Result) {
3630   if (Type->getAs<TypedefType>()) {
3631     Result += "\t";
3632     return false;
3633   }
3634 
3635   if (Type->isArrayType()) {
3636     QualType ElemTy = Context->getBaseElementType(Type);
3637     return RewriteObjCFieldDeclType(ElemTy, Result);
3638   }
3639   else if (Type->isRecordType()) {
3640     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3641     if (RD->isCompleteDefinition()) {
3642       if (RD->isStruct())
3643         Result += "\n\tstruct ";
3644       else if (RD->isUnion())
3645         Result += "\n\tunion ";
3646       else
3647         assert(false && "class not allowed as an ivar type");
3648 
3649       Result += RD->getName();
3650       if (GlobalDefinedTags.count(RD)) {
3651         // struct/union is defined globally, use it.
3652         Result += " ";
3653         return true;
3654       }
3655       Result += " {\n";
3656       for (auto *FD : RD->fields())
3657         RewriteObjCFieldDecl(FD, Result);
3658       Result += "\t} ";
3659       return true;
3660     }
3661   }
3662   else if (Type->isEnumeralType()) {
3663     EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3664     if (ED->isCompleteDefinition()) {
3665       Result += "\n\tenum ";
3666       Result += ED->getName();
3667       if (GlobalDefinedTags.count(ED)) {
3668         // Enum is globall defined, use it.
3669         Result += " ";
3670         return true;
3671       }
3672 
3673       Result += " {\n";
3674       for (const auto *EC : ED->enumerators()) {
3675         Result += "\t"; Result += EC->getName(); Result += " = ";
3676         Result += toString(EC->getInitVal(), 10);
3677         Result += ",\n";
3678       }
3679       Result += "\t} ";
3680       return true;
3681     }
3682   }
3683 
3684   Result += "\t";
3685   convertObjCTypeToCStyleType(Type);
3686   return false;
3687 }
3688 
3689 
3690 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3691 /// It handles elaborated types, as well as enum types in the process.
3692 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3693                                              std::string &Result) {
3694   QualType Type = fieldDecl->getType();
3695   std::string Name = fieldDecl->getNameAsString();
3696 
3697   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3698   if (!EleboratedType)
3699     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3700   Result += Name;
3701   if (fieldDecl->isBitField()) {
3702     Result += " : ";
3703     Result += utostr(fieldDecl->getBitWidthValue());
3704   }
3705   else if (EleboratedType && Type->isArrayType()) {
3706     const ArrayType *AT = Context->getAsArrayType(Type);
3707     do {
3708       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3709         Result += "[";
3710         llvm::APInt Dim = CAT->getSize();
3711         Result += utostr(Dim.getZExtValue());
3712         Result += "]";
3713       }
3714       AT = Context->getAsArrayType(AT->getElementType());
3715     } while (AT);
3716   }
3717 
3718   Result += ";\n";
3719 }
3720 
3721 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3722 /// named aggregate types into the input buffer.
3723 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3724                                              std::string &Result) {
3725   QualType Type = fieldDecl->getType();
3726   if (Type->getAs<TypedefType>())
3727     return;
3728   if (Type->isArrayType())
3729     Type = Context->getBaseElementType(Type);
3730 
3731   auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3732 
3733   TagDecl *TD = nullptr;
3734   if (Type->isRecordType()) {
3735     TD = Type->castAs<RecordType>()->getDecl();
3736   }
3737   else if (Type->isEnumeralType()) {
3738     TD = Type->castAs<EnumType>()->getDecl();
3739   }
3740 
3741   if (TD) {
3742     if (GlobalDefinedTags.count(TD))
3743       return;
3744 
3745     bool IsNamedDefinition = false;
3746     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3747       RewriteObjCFieldDeclType(Type, Result);
3748       Result += ";";
3749     }
3750     if (IsNamedDefinition)
3751       GlobalDefinedTags.insert(TD);
3752   }
3753 }
3754 
3755 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3756   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3757   if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3758     return IvarGroupNumber[IV];
3759   }
3760   unsigned GroupNo = 0;
3761   SmallVector<const ObjCIvarDecl *, 8> IVars;
3762   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3763        IVD; IVD = IVD->getNextIvar())
3764     IVars.push_back(IVD);
3765 
3766   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3767     if (IVars[i]->isBitField()) {
3768       IvarGroupNumber[IVars[i++]] = ++GroupNo;
3769       while (i < e && IVars[i]->isBitField())
3770         IvarGroupNumber[IVars[i++]] = GroupNo;
3771       if (i < e)
3772         --i;
3773     }
3774 
3775   ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3776   return IvarGroupNumber[IV];
3777 }
3778 
3779 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3780                               ObjCIvarDecl *IV,
3781                               SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3782   std::string StructTagName;
3783   ObjCIvarBitfieldGroupType(IV, StructTagName);
3784   RecordDecl *RD = RecordDecl::Create(
3785       *Context, TagTypeKind::Struct, Context->getTranslationUnitDecl(),
3786       SourceLocation(), SourceLocation(), &Context->Idents.get(StructTagName));
3787   for (unsigned i=0, e = IVars.size(); i < e; i++) {
3788     ObjCIvarDecl *Ivar = IVars[i];
3789     RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3790                                   &Context->Idents.get(Ivar->getName()),
3791                                   Ivar->getType(),
3792                                   nullptr, /*Expr *BW */Ivar->getBitWidth(),
3793                                   false, ICIS_NoInit));
3794   }
3795   RD->completeDefinition();
3796   return Context->getTagDeclType(RD);
3797 }
3798 
3799 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3800   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3801   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3802   std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3803   if (auto It = GroupRecordType.find(tuple); It != GroupRecordType.end())
3804     return It->second;
3805 
3806   SmallVector<ObjCIvarDecl *, 8> IVars;
3807   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3808        IVD; IVD = IVD->getNextIvar()) {
3809     if (IVD->isBitField())
3810       IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3811     else {
3812       if (!IVars.empty()) {
3813         unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3814         // Generate the struct type for this group of bitfield ivars.
3815         GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3816           SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3817         IVars.clear();
3818       }
3819     }
3820   }
3821   if (!IVars.empty()) {
3822     // Do the last one.
3823     unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3824     GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3825       SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3826   }
3827   QualType RetQT = GroupRecordType[tuple];
3828   assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3829 
3830   return RetQT;
3831 }
3832 
3833 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3834 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3835 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3836                                                   std::string &Result) {
3837   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3838   Result += CDecl->getName();
3839   Result += "__GRBF_";
3840   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3841   Result += utostr(GroupNo);
3842 }
3843 
3844 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3845 /// Name of the struct would be: classname__T_n where n is the group number for
3846 /// this ivar.
3847 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3848                                                   std::string &Result) {
3849   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3850   Result += CDecl->getName();
3851   Result += "__T_";
3852   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3853   Result += utostr(GroupNo);
3854 }
3855 
3856 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3857 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3858 /// this ivar.
3859 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3860                                                     std::string &Result) {
3861   Result += "OBJC_IVAR_$_";
3862   ObjCIvarBitfieldGroupDecl(IV, Result);
3863 }
3864 
3865 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3866       while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3867         ++IX; \
3868       if (IX < ENDIX) \
3869         --IX; \
3870 }
3871 
3872 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3873 /// an objective-c class with ivars.
3874 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3875                                                std::string &Result) {
3876   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3877   assert(CDecl->getName() != "" &&
3878          "Name missing in SynthesizeObjCInternalStruct");
3879   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3880   SmallVector<ObjCIvarDecl *, 8> IVars;
3881   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3882        IVD; IVD = IVD->getNextIvar())
3883     IVars.push_back(IVD);
3884 
3885   SourceLocation LocStart = CDecl->getBeginLoc();
3886   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3887 
3888   const char *startBuf = SM->getCharacterData(LocStart);
3889   const char *endBuf = SM->getCharacterData(LocEnd);
3890 
3891   // If no ivars and no root or if its root, directly or indirectly,
3892   // have no ivars (thus not synthesized) then no need to synthesize this class.
3893   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3894       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3895     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3896     ReplaceText(LocStart, endBuf-startBuf, Result);
3897     return;
3898   }
3899 
3900   // Insert named struct/union definitions inside class to
3901   // outer scope. This follows semantics of locally defined
3902   // struct/unions in objective-c classes.
3903   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3904     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3905 
3906   // Insert named structs which are syntheized to group ivar bitfields
3907   // to outer scope as well.
3908   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3909     if (IVars[i]->isBitField()) {
3910       ObjCIvarDecl *IV = IVars[i];
3911       QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3912       RewriteObjCFieldDeclType(QT, Result);
3913       Result += ";";
3914       // skip over ivar bitfields in this group.
3915       SKIP_BITFIELDS(i , e, IVars);
3916     }
3917 
3918   Result += "\nstruct ";
3919   Result += CDecl->getNameAsString();
3920   Result += "_IMPL {\n";
3921 
3922   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3923     Result += "\tstruct "; Result += RCDecl->getNameAsString();
3924     Result += "_IMPL "; Result += RCDecl->getNameAsString();
3925     Result += "_IVARS;\n";
3926   }
3927 
3928   for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3929     if (IVars[i]->isBitField()) {
3930       ObjCIvarDecl *IV = IVars[i];
3931       Result += "\tstruct ";
3932       ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3933       ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3934       // skip over ivar bitfields in this group.
3935       SKIP_BITFIELDS(i , e, IVars);
3936     }
3937     else
3938       RewriteObjCFieldDecl(IVars[i], Result);
3939   }
3940 
3941   Result += "};\n";
3942   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3943   ReplaceText(LocStart, endBuf-startBuf, Result);
3944   // Mark this struct as having been generated.
3945   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3946     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3947 }
3948 
3949 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3950 /// have been referenced in an ivar access expression.
3951 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3952                                                   std::string &Result) {
3953   // write out ivar offset symbols which have been referenced in an ivar
3954   // access expression.
3955   llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3956 
3957   if (Ivars.empty())
3958     return;
3959 
3960   llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3961   for (ObjCIvarDecl *IvarDecl : Ivars) {
3962     const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3963     unsigned GroupNo = 0;
3964     if (IvarDecl->isBitField()) {
3965       GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3966       if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3967         continue;
3968     }
3969     Result += "\n";
3970     if (LangOpts.MicrosoftExt)
3971       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3972     Result += "extern \"C\" ";
3973     if (LangOpts.MicrosoftExt &&
3974         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3975         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3976         Result += "__declspec(dllimport) ";
3977 
3978     Result += "unsigned long ";
3979     if (IvarDecl->isBitField()) {
3980       ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3981       GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3982     }
3983     else
3984       WriteInternalIvarName(CDecl, IvarDecl, Result);
3985     Result += ";";
3986   }
3987 }
3988 
3989 //===----------------------------------------------------------------------===//
3990 // Meta Data Emission
3991 //===----------------------------------------------------------------------===//
3992 
3993 /// RewriteImplementations - This routine rewrites all method implementations
3994 /// and emits meta-data.
3995 
3996 void RewriteModernObjC::RewriteImplementations() {
3997   int ClsDefCount = ClassImplementation.size();
3998   int CatDefCount = CategoryImplementation.size();
3999 
4000   // Rewrite implemented methods
4001   for (int i = 0; i < ClsDefCount; i++) {
4002     ObjCImplementationDecl *OIMP = ClassImplementation[i];
4003     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4004     if (CDecl->isImplicitInterfaceDecl())
4005       assert(false &&
4006              "Legacy implicit interface rewriting not supported in moder abi");
4007     RewriteImplementationDecl(OIMP);
4008   }
4009 
4010   for (int i = 0; i < CatDefCount; i++) {
4011     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4012     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4013     if (CDecl->isImplicitInterfaceDecl())
4014       assert(false &&
4015              "Legacy implicit interface rewriting not supported in moder abi");
4016     RewriteImplementationDecl(CIMP);
4017   }
4018 }
4019 
4020 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4021                                      const std::string &Name,
4022                                      ValueDecl *VD, bool def) {
4023   assert(BlockByRefDeclNo.count(VD) &&
4024          "RewriteByRefString: ByRef decl missing");
4025   if (def)
4026     ResultStr += "struct ";
4027   ResultStr += "__Block_byref_" + Name +
4028     "_" + utostr(BlockByRefDeclNo[VD]) ;
4029 }
4030 
4031 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4032   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4033     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4034   return false;
4035 }
4036 
4037 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4038                                                    StringRef funcName,
4039                                                    const std::string &Tag) {
4040   const FunctionType *AFT = CE->getFunctionType();
4041   QualType RT = AFT->getReturnType();
4042   std::string StructRef = "struct " + Tag;
4043   SourceLocation BlockLoc = CE->getExprLoc();
4044   std::string S;
4045   ConvertSourceLocationToLineDirective(BlockLoc, S);
4046 
4047   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4048          funcName.str() + "_block_func_" + utostr(i);
4049 
4050   BlockDecl *BD = CE->getBlockDecl();
4051 
4052   if (isa<FunctionNoProtoType>(AFT)) {
4053     // No user-supplied arguments. Still need to pass in a pointer to the
4054     // block (to reference imported block decl refs).
4055     S += "(" + StructRef + " *__cself)";
4056   } else if (BD->param_empty()) {
4057     S += "(" + StructRef + " *__cself)";
4058   } else {
4059     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4060     assert(FT && "SynthesizeBlockFunc: No function proto");
4061     S += '(';
4062     // first add the implicit argument.
4063     S += StructRef + " *__cself, ";
4064     std::string ParamStr;
4065     for (BlockDecl::param_iterator AI = BD->param_begin(),
4066          E = BD->param_end(); AI != E; ++AI) {
4067       if (AI != BD->param_begin()) S += ", ";
4068       ParamStr = (*AI)->getNameAsString();
4069       QualType QT = (*AI)->getType();
4070       (void)convertBlockPointerToFunctionPointer(QT);
4071       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4072       S += ParamStr;
4073     }
4074     if (FT->isVariadic()) {
4075       if (!BD->param_empty()) S += ", ";
4076       S += "...";
4077     }
4078     S += ')';
4079   }
4080   S += " {\n";
4081 
4082   // Create local declarations to avoid rewriting all closure decl ref exprs.
4083   // First, emit a declaration for all "by ref" decls.
4084   for (ValueDecl *VD : BlockByRefDecls) {
4085     S += "  ";
4086     std::string Name = VD->getNameAsString();
4087     std::string TypeString;
4088     RewriteByRefString(TypeString, Name, VD);
4089     TypeString += " *";
4090     Name = TypeString + Name;
4091     S += Name + " = __cself->" + VD->getNameAsString() + "; // bound by ref\n";
4092   }
4093   // Next, emit a declaration for all "by copy" declarations.
4094   for (ValueDecl *VD : BlockByCopyDecls) {
4095     S += "  ";
4096     // Handle nested closure invocation. For example:
4097     //
4098     //   void (^myImportedClosure)(void);
4099     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4100     //
4101     //   void (^anotherClosure)(void);
4102     //   anotherClosure = ^(void) {
4103     //     myImportedClosure(); // import and invoke the closure
4104     //   };
4105     //
4106     if (isTopLevelBlockPointerType(VD->getType())) {
4107       RewriteBlockPointerTypeVariable(S, VD);
4108       S += " = (";
4109       RewriteBlockPointerType(S, VD->getType());
4110       S += ")";
4111       S += "__cself->" + VD->getNameAsString() + "; // bound by copy\n";
4112     } else {
4113       std::string Name = VD->getNameAsString();
4114       QualType QT = VD->getType();
4115       if (HasLocalVariableExternalStorage(VD))
4116         QT = Context->getPointerType(QT);
4117       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4118       S += Name + " = __cself->" + VD->getNameAsString() +
4119            "; // bound by copy\n";
4120     }
4121   }
4122   std::string RewrittenStr = RewrittenBlockExprs[CE];
4123   const char *cstr = RewrittenStr.c_str();
4124   while (*cstr++ != '{') ;
4125   S += cstr;
4126   S += "\n";
4127   return S;
4128 }
4129 
4130 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(
4131     BlockExpr *CE, int i, StringRef funcName, const std::string &Tag) {
4132   std::string StructRef = "struct " + Tag;
4133   std::string S = "static void __";
4134 
4135   S += funcName;
4136   S += "_block_copy_" + utostr(i);
4137   S += "(" + StructRef;
4138   S += "*dst, " + StructRef;
4139   S += "*src) {";
4140   for (ValueDecl *VD : ImportedBlockDecls) {
4141     S += "_Block_object_assign((void*)&dst->";
4142     S += VD->getNameAsString();
4143     S += ", (void*)src->";
4144     S += VD->getNameAsString();
4145     if (BlockByRefDecls.count(VD))
4146       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4147     else if (VD->getType()->isBlockPointerType())
4148       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4149     else
4150       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4151   }
4152   S += "}\n";
4153 
4154   S += "\nstatic void __";
4155   S += funcName;
4156   S += "_block_dispose_" + utostr(i);
4157   S += "(" + StructRef;
4158   S += "*src) {";
4159   for (ValueDecl *VD : ImportedBlockDecls) {
4160     S += "_Block_object_dispose((void*)src->";
4161     S += VD->getNameAsString();
4162     if (BlockByRefDecls.count(VD))
4163       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4164     else if (VD->getType()->isBlockPointerType())
4165       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4166     else
4167       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4168   }
4169   S += "}\n";
4170   return S;
4171 }
4172 
4173 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE,
4174                                                    const std::string &Tag,
4175                                                    const std::string &Desc) {
4176   std::string S = "\nstruct " + Tag;
4177   std::string Constructor = "  " + Tag;
4178 
4179   S += " {\n  struct __block_impl impl;\n";
4180   S += "  struct " + Desc;
4181   S += "* Desc;\n";
4182 
4183   Constructor += "(void *fp, "; // Invoke function pointer.
4184   Constructor += "struct " + Desc; // Descriptor pointer.
4185   Constructor += " *desc";
4186 
4187   if (BlockDeclRefs.size()) {
4188     // Output all "by copy" declarations.
4189     for (ValueDecl *VD : BlockByCopyDecls) {
4190       S += "  ";
4191       std::string FieldName = VD->getNameAsString();
4192       std::string ArgName = "_" + FieldName;
4193       // Handle nested closure invocation. For example:
4194       //
4195       //   void (^myImportedBlock)(void);
4196       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4197       //
4198       //   void (^anotherBlock)(void);
4199       //   anotherBlock = ^(void) {
4200       //     myImportedBlock(); // import and invoke the closure
4201       //   };
4202       //
4203       if (isTopLevelBlockPointerType(VD->getType())) {
4204         S += "struct __block_impl *";
4205         Constructor += ", void *" + ArgName;
4206       } else {
4207         QualType QT = VD->getType();
4208         if (HasLocalVariableExternalStorage(VD))
4209           QT = Context->getPointerType(QT);
4210         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4211         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4212         Constructor += ", " + ArgName;
4213       }
4214       S += FieldName + ";\n";
4215     }
4216     // Output all "by ref" declarations.
4217     for (ValueDecl *VD : BlockByRefDecls) {
4218       S += "  ";
4219       std::string FieldName = VD->getNameAsString();
4220       std::string ArgName = "_" + FieldName;
4221       {
4222         std::string TypeString;
4223         RewriteByRefString(TypeString, FieldName, VD);
4224         TypeString += " *";
4225         FieldName = TypeString + FieldName;
4226         ArgName = TypeString + ArgName;
4227         Constructor += ", " + ArgName;
4228       }
4229       S += FieldName + "; // by ref\n";
4230     }
4231     // Finish writing the constructor.
4232     Constructor += ", int flags=0)";
4233     // Initialize all "by copy" arguments.
4234     bool firsTime = true;
4235     for (const ValueDecl *VD : BlockByCopyDecls) {
4236       std::string Name = VD->getNameAsString();
4237       if (firsTime) {
4238         Constructor += " : ";
4239         firsTime = false;
4240       } else
4241         Constructor += ", ";
4242       if (isTopLevelBlockPointerType(VD->getType()))
4243         Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4244       else
4245         Constructor += Name + "(_" + Name + ")";
4246     }
4247     // Initialize all "by ref" arguments.
4248     for (const ValueDecl *VD : BlockByRefDecls) {
4249       std::string Name = VD->getNameAsString();
4250       if (firsTime) {
4251         Constructor += " : ";
4252         firsTime = false;
4253       }
4254       else
4255         Constructor += ", ";
4256       Constructor += Name + "(_" + Name + "->__forwarding)";
4257     }
4258 
4259     Constructor += " {\n";
4260     if (GlobalVarDecl)
4261       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4262     else
4263       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4264     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4265 
4266     Constructor += "    Desc = desc;\n";
4267   } else {
4268     // Finish writing the constructor.
4269     Constructor += ", int flags=0) {\n";
4270     if (GlobalVarDecl)
4271       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4272     else
4273       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4274     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4275     Constructor += "    Desc = desc;\n";
4276   }
4277   Constructor += "  ";
4278   Constructor += "}\n";
4279   S += Constructor;
4280   S += "};\n";
4281   return S;
4282 }
4283 
4284 std::string RewriteModernObjC::SynthesizeBlockDescriptor(
4285     const std::string &DescTag, const std::string &ImplTag, int i,
4286     StringRef FunName, unsigned hasCopy) {
4287   std::string S = "\nstatic struct " + DescTag;
4288 
4289   S += " {\n  size_t reserved;\n";
4290   S += "  size_t Block_size;\n";
4291   if (hasCopy) {
4292     S += "  void (*copy)(struct ";
4293     S += ImplTag; S += "*, struct ";
4294     S += ImplTag; S += "*);\n";
4295 
4296     S += "  void (*dispose)(struct ";
4297     S += ImplTag; S += "*);\n";
4298   }
4299   S += "} ";
4300 
4301   S += DescTag + "_DATA = { 0, sizeof(struct ";
4302   S += ImplTag + ")";
4303   if (hasCopy) {
4304     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4305     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4306   }
4307   S += "};\n";
4308   return S;
4309 }
4310 
4311 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4312                                           StringRef FunName) {
4313   bool RewriteSC = (GlobalVarDecl &&
4314                     !Blocks.empty() &&
4315                     GlobalVarDecl->getStorageClass() == SC_Static &&
4316                     GlobalVarDecl->getType().getCVRQualifiers());
4317   if (RewriteSC) {
4318     std::string SC(" void __");
4319     SC += GlobalVarDecl->getNameAsString();
4320     SC += "() {}";
4321     InsertText(FunLocStart, SC);
4322   }
4323 
4324   // Insert closures that were part of the function.
4325   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4326     CollectBlockDeclRefInfo(Blocks[i]);
4327     // Need to copy-in the inner copied-in variables not actually used in this
4328     // block.
4329     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4330       DeclRefExpr *Exp = InnerDeclRefs[count++];
4331       ValueDecl *VD = Exp->getDecl();
4332       BlockDeclRefs.push_back(Exp);
4333       if (!VD->hasAttr<BlocksAttr>()) {
4334         BlockByCopyDecls.insert(VD);
4335         continue;
4336       }
4337 
4338       BlockByRefDecls.insert(VD);
4339 
4340       // imported objects in the inner blocks not used in the outer
4341       // blocks must be copied/disposed in the outer block as well.
4342       if (VD->getType()->isObjCObjectPointerType() ||
4343           VD->getType()->isBlockPointerType())
4344         ImportedBlockDecls.insert(VD);
4345     }
4346 
4347     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4348     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4349 
4350     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4351 
4352     InsertText(FunLocStart, CI);
4353 
4354     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4355 
4356     InsertText(FunLocStart, CF);
4357 
4358     if (ImportedBlockDecls.size()) {
4359       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4360       InsertText(FunLocStart, HF);
4361     }
4362     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4363                                                ImportedBlockDecls.size() > 0);
4364     InsertText(FunLocStart, BD);
4365 
4366     BlockDeclRefs.clear();
4367     BlockByRefDecls.clear();
4368     BlockByCopyDecls.clear();
4369     ImportedBlockDecls.clear();
4370   }
4371   if (RewriteSC) {
4372     // Must insert any 'const/volatile/static here. Since it has been
4373     // removed as result of rewriting of block literals.
4374     std::string SC;
4375     if (GlobalVarDecl->getStorageClass() == SC_Static)
4376       SC = "static ";
4377     if (GlobalVarDecl->getType().isConstQualified())
4378       SC += "const ";
4379     if (GlobalVarDecl->getType().isVolatileQualified())
4380       SC += "volatile ";
4381     if (GlobalVarDecl->getType().isRestrictQualified())
4382       SC += "restrict ";
4383     InsertText(FunLocStart, SC);
4384   }
4385   if (GlobalConstructionExp) {
4386     // extra fancy dance for global literal expression.
4387 
4388     // Always the latest block expression on the block stack.
4389     std::string Tag = "__";
4390     Tag += FunName;
4391     Tag += "_block_impl_";
4392     Tag += utostr(Blocks.size()-1);
4393     std::string globalBuf = "static ";
4394     globalBuf += Tag; globalBuf += " ";
4395     std::string SStr;
4396 
4397     llvm::raw_string_ostream constructorExprBuf(SStr);
4398     GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4399                                        PrintingPolicy(LangOpts));
4400     globalBuf += SStr;
4401     globalBuf += ";\n";
4402     InsertText(FunLocStart, globalBuf);
4403     GlobalConstructionExp = nullptr;
4404   }
4405 
4406   Blocks.clear();
4407   InnerDeclRefsCount.clear();
4408   InnerDeclRefs.clear();
4409   RewrittenBlockExprs.clear();
4410 }
4411 
4412 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4413   SourceLocation FunLocStart =
4414     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4415                       : FD->getTypeSpecStartLoc();
4416   StringRef FuncName = FD->getName();
4417 
4418   SynthesizeBlockLiterals(FunLocStart, FuncName);
4419 }
4420 
4421 static void BuildUniqueMethodName(std::string &Name,
4422                                   ObjCMethodDecl *MD) {
4423   ObjCInterfaceDecl *IFace = MD->getClassInterface();
4424   Name = std::string(IFace->getName());
4425   Name += "__" + MD->getSelector().getAsString();
4426   // Convert colons to underscores.
4427   std::string::size_type loc = 0;
4428   while ((loc = Name.find(':', loc)) != std::string::npos)
4429     Name.replace(loc, 1, "_");
4430 }
4431 
4432 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4433   // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4434   // SourceLocation FunLocStart = MD->getBeginLoc();
4435   SourceLocation FunLocStart = MD->getBeginLoc();
4436   std::string FuncName;
4437   BuildUniqueMethodName(FuncName, MD);
4438   SynthesizeBlockLiterals(FunLocStart, FuncName);
4439 }
4440 
4441 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4442   for (Stmt *SubStmt : S->children())
4443     if (SubStmt) {
4444       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4445         GetBlockDeclRefExprs(CBE->getBody());
4446       else
4447         GetBlockDeclRefExprs(SubStmt);
4448     }
4449   // Handle specific things.
4450   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4451     if (DRE->refersToEnclosingVariableOrCapture() ||
4452         HasLocalVariableExternalStorage(DRE->getDecl()))
4453       // FIXME: Handle enums.
4454       BlockDeclRefs.push_back(DRE);
4455 }
4456 
4457 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4458                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4459                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4460   for (Stmt *SubStmt : S->children())
4461     if (SubStmt) {
4462       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4463         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4464         GetInnerBlockDeclRefExprs(CBE->getBody(),
4465                                   InnerBlockDeclRefs,
4466                                   InnerContexts);
4467       }
4468       else
4469         GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4470     }
4471   // Handle specific things.
4472   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4473     if (DRE->refersToEnclosingVariableOrCapture() ||
4474         HasLocalVariableExternalStorage(DRE->getDecl())) {
4475       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4476         InnerBlockDeclRefs.push_back(DRE);
4477       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4478         if (Var->isFunctionOrMethodVarDecl())
4479           ImportedLocalExternalDecls.insert(Var);
4480     }
4481   }
4482 }
4483 
4484 /// convertObjCTypeToCStyleType - This routine converts such objc types
4485 /// as qualified objects, and blocks to their closest c/c++ types that
4486 /// it can. It returns true if input type was modified.
4487 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4488   QualType oldT = T;
4489   convertBlockPointerToFunctionPointer(T);
4490   if (T->isFunctionPointerType()) {
4491     QualType PointeeTy;
4492     if (const PointerType* PT = T->getAs<PointerType>()) {
4493       PointeeTy = PT->getPointeeType();
4494       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4495         T = convertFunctionTypeOfBlocks(FT);
4496         T = Context->getPointerType(T);
4497       }
4498     }
4499   }
4500 
4501   convertToUnqualifiedObjCType(T);
4502   return T != oldT;
4503 }
4504 
4505 /// convertFunctionTypeOfBlocks - This routine converts a function type
4506 /// whose result type may be a block pointer or whose argument type(s)
4507 /// might be block pointers to an equivalent function type replacing
4508 /// all block pointers to function pointers.
4509 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4510   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4511   // FTP will be null for closures that don't take arguments.
4512   // Generate a funky cast.
4513   SmallVector<QualType, 8> ArgTypes;
4514   QualType Res = FT->getReturnType();
4515   bool modified = convertObjCTypeToCStyleType(Res);
4516 
4517   if (FTP) {
4518     for (auto &I : FTP->param_types()) {
4519       QualType t = I;
4520       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4521       if (convertObjCTypeToCStyleType(t))
4522         modified = true;
4523       ArgTypes.push_back(t);
4524     }
4525   }
4526   QualType FuncType;
4527   if (modified)
4528     FuncType = getSimpleFunctionType(Res, ArgTypes);
4529   else FuncType = QualType(FT, 0);
4530   return FuncType;
4531 }
4532 
4533 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4534   // Navigate to relevant type information.
4535   const BlockPointerType *CPT = nullptr;
4536 
4537   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4538     CPT = DRE->getType()->getAs<BlockPointerType>();
4539   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4540     CPT = MExpr->getType()->getAs<BlockPointerType>();
4541   }
4542   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4543     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4544   }
4545   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4546     CPT = IEXPR->getType()->getAs<BlockPointerType>();
4547   else if (const ConditionalOperator *CEXPR =
4548             dyn_cast<ConditionalOperator>(BlockExp)) {
4549     Expr *LHSExp = CEXPR->getLHS();
4550     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4551     Expr *RHSExp = CEXPR->getRHS();
4552     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4553     Expr *CONDExp = CEXPR->getCond();
4554     ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
4555         CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
4556         cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
4557     return CondExpr;
4558   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4559     CPT = IRE->getType()->getAs<BlockPointerType>();
4560   } else if (const PseudoObjectExpr *POE
4561                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4562     CPT = POE->getType()->castAs<BlockPointerType>();
4563   } else {
4564     assert(false && "RewriteBlockClass: Bad type");
4565   }
4566   assert(CPT && "RewriteBlockClass: Bad type");
4567   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4568   assert(FT && "RewriteBlockClass: Bad type");
4569   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4570   // FTP will be null for closures that don't take arguments.
4571 
4572   RecordDecl *RD = RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
4573                                       SourceLocation(), SourceLocation(),
4574                                       &Context->Idents.get("__block_impl"));
4575   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4576 
4577   // Generate a funky cast.
4578   SmallVector<QualType, 8> ArgTypes;
4579 
4580   // Push the block argument type.
4581   ArgTypes.push_back(PtrBlock);
4582   if (FTP) {
4583     for (auto &I : FTP->param_types()) {
4584       QualType t = I;
4585       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4586       if (!convertBlockPointerToFunctionPointer(t))
4587         convertToUnqualifiedObjCType(t);
4588       ArgTypes.push_back(t);
4589     }
4590   }
4591   // Now do the pointer to function cast.
4592   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4593 
4594   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4595 
4596   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4597                                                CK_BitCast,
4598                                                const_cast<Expr*>(BlockExp));
4599   // Don't forget the parens to enforce the proper binding.
4600   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4601                                           BlkCast);
4602   //PE->dump();
4603 
4604   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4605                                     SourceLocation(),
4606                                     &Context->Idents.get("FuncPtr"),
4607                                     Context->VoidPtrTy, nullptr,
4608                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4609                                     ICIS_NoInit);
4610   MemberExpr *ME = MemberExpr::CreateImplicit(
4611       *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4612 
4613   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4614                                                 CK_BitCast, ME);
4615   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4616 
4617   SmallVector<Expr*, 8> BlkExprs;
4618   // Add the implicit argument.
4619   BlkExprs.push_back(BlkCast);
4620   // Add the user arguments.
4621   for (CallExpr::arg_iterator I = Exp->arg_begin(),
4622        E = Exp->arg_end(); I != E; ++I) {
4623     BlkExprs.push_back(*I);
4624   }
4625   CallExpr *CE =
4626       CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
4627                        SourceLocation(), FPOptionsOverride());
4628   return CE;
4629 }
4630 
4631 // We need to return the rewritten expression to handle cases where the
4632 // DeclRefExpr is embedded in another expression being rewritten.
4633 // For example:
4634 //
4635 // int main() {
4636 //    __block Foo *f;
4637 //    __block int i;
4638 //
4639 //    void (^myblock)() = ^() {
4640 //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4641 //        i = 77;
4642 //    };
4643 //}
4644 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4645   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4646   // for each DeclRefExp where BYREFVAR is name of the variable.
4647   ValueDecl *VD = DeclRefExp->getDecl();
4648   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4649                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4650 
4651   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4652                                     SourceLocation(),
4653                                     &Context->Idents.get("__forwarding"),
4654                                     Context->VoidPtrTy, nullptr,
4655                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4656                                     ICIS_NoInit);
4657   MemberExpr *ME = MemberExpr::CreateImplicit(
4658       *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4659 
4660   StringRef Name = VD->getName();
4661   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4662                          &Context->Idents.get(Name),
4663                          Context->VoidPtrTy, nullptr,
4664                          /*BitWidth=*/nullptr, /*Mutable=*/true,
4665                          ICIS_NoInit);
4666   ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4667                                   VK_LValue, OK_Ordinary);
4668 
4669   // Need parens to enforce precedence.
4670   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4671                                           DeclRefExp->getExprLoc(),
4672                                           ME);
4673   ReplaceStmt(DeclRefExp, PE);
4674   return PE;
4675 }
4676 
4677 // Rewrites the imported local variable V with external storage
4678 // (static, extern, etc.) as *V
4679 //
4680 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4681   ValueDecl *VD = DRE->getDecl();
4682   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4683     if (!ImportedLocalExternalDecls.count(Var))
4684       return DRE;
4685   Expr *Exp = UnaryOperator::Create(
4686       const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
4687       VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
4688   // Need parens to enforce precedence.
4689   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4690                                           Exp);
4691   ReplaceStmt(DRE, PE);
4692   return PE;
4693 }
4694 
4695 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4696   SourceLocation LocStart = CE->getLParenLoc();
4697   SourceLocation LocEnd = CE->getRParenLoc();
4698 
4699   // Need to avoid trying to rewrite synthesized casts.
4700   if (LocStart.isInvalid())
4701     return;
4702   // Need to avoid trying to rewrite casts contained in macros.
4703   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4704     return;
4705 
4706   const char *startBuf = SM->getCharacterData(LocStart);
4707   const char *endBuf = SM->getCharacterData(LocEnd);
4708   QualType QT = CE->getType();
4709   const Type* TypePtr = QT->getAs<Type>();
4710   if (isa<TypeOfExprType>(TypePtr)) {
4711     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4712     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4713     std::string TypeAsString = "(";
4714     RewriteBlockPointerType(TypeAsString, QT);
4715     TypeAsString += ")";
4716     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4717     return;
4718   }
4719   // advance the location to startArgList.
4720   const char *argPtr = startBuf;
4721 
4722   while (*argPtr++ && (argPtr < endBuf)) {
4723     switch (*argPtr) {
4724     case '^':
4725       // Replace the '^' with '*'.
4726       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4727       ReplaceText(LocStart, 1, "*");
4728       break;
4729     }
4730   }
4731 }
4732 
4733 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4734   CastKind CastKind = IC->getCastKind();
4735   if (CastKind != CK_BlockPointerToObjCPointerCast &&
4736       CastKind != CK_AnyPointerToBlockPointerCast)
4737     return;
4738 
4739   QualType QT = IC->getType();
4740   (void)convertBlockPointerToFunctionPointer(QT);
4741   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4742   std::string Str = "(";
4743   Str += TypeString;
4744   Str += ")";
4745   InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4746 }
4747 
4748 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4749   SourceLocation DeclLoc = FD->getLocation();
4750   unsigned parenCount = 0;
4751 
4752   // We have 1 or more arguments that have closure pointers.
4753   const char *startBuf = SM->getCharacterData(DeclLoc);
4754   const char *startArgList = strchr(startBuf, '(');
4755 
4756   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4757 
4758   parenCount++;
4759   // advance the location to startArgList.
4760   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4761   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4762 
4763   const char *argPtr = startArgList;
4764 
4765   while (*argPtr++ && parenCount) {
4766     switch (*argPtr) {
4767     case '^':
4768       // Replace the '^' with '*'.
4769       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4770       ReplaceText(DeclLoc, 1, "*");
4771       break;
4772     case '(':
4773       parenCount++;
4774       break;
4775     case ')':
4776       parenCount--;
4777       break;
4778     }
4779   }
4780 }
4781 
4782 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4783   const FunctionProtoType *FTP;
4784   const PointerType *PT = QT->getAs<PointerType>();
4785   if (PT) {
4786     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4787   } else {
4788     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4789     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4790     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4791   }
4792   if (FTP) {
4793     for (const auto &I : FTP->param_types())
4794       if (isTopLevelBlockPointerType(I))
4795         return true;
4796   }
4797   return false;
4798 }
4799 
4800 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4801   const FunctionProtoType *FTP;
4802   const PointerType *PT = QT->getAs<PointerType>();
4803   if (PT) {
4804     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4805   } else {
4806     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4807     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4808     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4809   }
4810   if (FTP) {
4811     for (const auto &I : FTP->param_types()) {
4812       if (I->isObjCQualifiedIdType())
4813         return true;
4814       if (I->isObjCObjectPointerType() &&
4815           I->getPointeeType()->isObjCQualifiedInterfaceType())
4816         return true;
4817     }
4818 
4819   }
4820   return false;
4821 }
4822 
4823 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4824                                      const char *&RParen) {
4825   const char *argPtr = strchr(Name, '(');
4826   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4827 
4828   LParen = argPtr; // output the start.
4829   argPtr++; // skip past the left paren.
4830   unsigned parenCount = 1;
4831 
4832   while (*argPtr && parenCount) {
4833     switch (*argPtr) {
4834     case '(': parenCount++; break;
4835     case ')': parenCount--; break;
4836     default: break;
4837     }
4838     if (parenCount) argPtr++;
4839   }
4840   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4841   RParen = argPtr; // output the end
4842 }
4843 
4844 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4845   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4846     RewriteBlockPointerFunctionArgs(FD);
4847     return;
4848   }
4849   // Handle Variables and Typedefs.
4850   SourceLocation DeclLoc = ND->getLocation();
4851   QualType DeclT;
4852   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4853     DeclT = VD->getType();
4854   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4855     DeclT = TDD->getUnderlyingType();
4856   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4857     DeclT = FD->getType();
4858   else
4859     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4860 
4861   const char *startBuf = SM->getCharacterData(DeclLoc);
4862   const char *endBuf = startBuf;
4863   // scan backward (from the decl location) for the end of the previous decl.
4864   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4865     startBuf--;
4866   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4867   std::string buf;
4868   unsigned OrigLength=0;
4869   // *startBuf != '^' if we are dealing with a pointer to function that
4870   // may take block argument types (which will be handled below).
4871   if (*startBuf == '^') {
4872     // Replace the '^' with '*', computing a negative offset.
4873     buf = '*';
4874     startBuf++;
4875     OrigLength++;
4876   }
4877   while (*startBuf != ')') {
4878     buf += *startBuf;
4879     startBuf++;
4880     OrigLength++;
4881   }
4882   buf += ')';
4883   OrigLength++;
4884 
4885   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4886       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4887     // Replace the '^' with '*' for arguments.
4888     // Replace id<P> with id/*<>*/
4889     DeclLoc = ND->getLocation();
4890     startBuf = SM->getCharacterData(DeclLoc);
4891     const char *argListBegin, *argListEnd;
4892     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4893     while (argListBegin < argListEnd) {
4894       if (*argListBegin == '^')
4895         buf += '*';
4896       else if (*argListBegin ==  '<') {
4897         buf += "/*";
4898         buf += *argListBegin++;
4899         OrigLength++;
4900         while (*argListBegin != '>') {
4901           buf += *argListBegin++;
4902           OrigLength++;
4903         }
4904         buf += *argListBegin;
4905         buf += "*/";
4906       }
4907       else
4908         buf += *argListBegin;
4909       argListBegin++;
4910       OrigLength++;
4911     }
4912     buf += ')';
4913     OrigLength++;
4914   }
4915   ReplaceText(Start, OrigLength, buf);
4916 }
4917 
4918 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4919 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4920 ///                    struct Block_byref_id_object *src) {
4921 ///  _Block_object_assign (&_dest->object, _src->object,
4922 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4923 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4924 ///  _Block_object_assign(&_dest->object, _src->object,
4925 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4926 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4927 /// }
4928 /// And:
4929 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4930 ///  _Block_object_dispose(_src->object,
4931 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4932 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4933 ///  _Block_object_dispose(_src->object,
4934 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4935 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4936 /// }
4937 
4938 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4939                                                           int flag) {
4940   std::string S;
4941   if (CopyDestroyCache.count(flag))
4942     return S;
4943   CopyDestroyCache.insert(flag);
4944   S = "static void __Block_byref_id_object_copy_";
4945   S += utostr(flag);
4946   S += "(void *dst, void *src) {\n";
4947 
4948   // offset into the object pointer is computed as:
4949   // void * + void* + int + int + void* + void *
4950   unsigned IntSize =
4951   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4952   unsigned VoidPtrSize =
4953   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4954 
4955   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4956   S += " _Block_object_assign((char*)dst + ";
4957   S += utostr(offset);
4958   S += ", *(void * *) ((char*)src + ";
4959   S += utostr(offset);
4960   S += "), ";
4961   S += utostr(flag);
4962   S += ");\n}\n";
4963 
4964   S += "static void __Block_byref_id_object_dispose_";
4965   S += utostr(flag);
4966   S += "(void *src) {\n";
4967   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4968   S += utostr(offset);
4969   S += "), ";
4970   S += utostr(flag);
4971   S += ");\n}\n";
4972   return S;
4973 }
4974 
4975 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4976 /// the declaration into:
4977 /// struct __Block_byref_ND {
4978 /// void *__isa;                  // NULL for everything except __weak pointers
4979 /// struct __Block_byref_ND *__forwarding;
4980 /// int32_t __flags;
4981 /// int32_t __size;
4982 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4983 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4984 /// typex ND;
4985 /// };
4986 ///
4987 /// It then replaces declaration of ND variable with:
4988 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4989 ///                               __size=sizeof(struct __Block_byref_ND),
4990 ///                               ND=initializer-if-any};
4991 ///
4992 ///
4993 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4994                                         bool lastDecl) {
4995   int flag = 0;
4996   int isa = 0;
4997   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4998   if (DeclLoc.isInvalid())
4999     // If type location is missing, it is because of missing type (a warning).
5000     // Use variable's location which is good for this case.
5001     DeclLoc = ND->getLocation();
5002   const char *startBuf = SM->getCharacterData(DeclLoc);
5003   SourceLocation X = ND->getEndLoc();
5004   X = SM->getExpansionLoc(X);
5005   const char *endBuf = SM->getCharacterData(X);
5006   std::string Name(ND->getNameAsString());
5007   std::string ByrefType;
5008   RewriteByRefString(ByrefType, Name, ND, true);
5009   ByrefType += " {\n";
5010   ByrefType += "  void *__isa;\n";
5011   RewriteByRefString(ByrefType, Name, ND);
5012   ByrefType += " *__forwarding;\n";
5013   ByrefType += " int __flags;\n";
5014   ByrefType += " int __size;\n";
5015   // Add void *__Block_byref_id_object_copy;
5016   // void *__Block_byref_id_object_dispose; if needed.
5017   QualType Ty = ND->getType();
5018   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5019   if (HasCopyAndDispose) {
5020     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5021     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5022   }
5023 
5024   QualType T = Ty;
5025   (void)convertBlockPointerToFunctionPointer(T);
5026   T.getAsStringInternal(Name, Context->getPrintingPolicy());
5027 
5028   ByrefType += " " + Name + ";\n";
5029   ByrefType += "};\n";
5030   // Insert this type in global scope. It is needed by helper function.
5031   SourceLocation FunLocStart;
5032   if (CurFunctionDef)
5033      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5034   else {
5035     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5036     FunLocStart = CurMethodDef->getBeginLoc();
5037   }
5038   InsertText(FunLocStart, ByrefType);
5039 
5040   if (Ty.isObjCGCWeak()) {
5041     flag |= BLOCK_FIELD_IS_WEAK;
5042     isa = 1;
5043   }
5044   if (HasCopyAndDispose) {
5045     flag = BLOCK_BYREF_CALLER;
5046     QualType Ty = ND->getType();
5047     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5048     if (Ty->isBlockPointerType())
5049       flag |= BLOCK_FIELD_IS_BLOCK;
5050     else
5051       flag |= BLOCK_FIELD_IS_OBJECT;
5052     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5053     if (!HF.empty())
5054       Preamble += HF;
5055   }
5056 
5057   // struct __Block_byref_ND ND =
5058   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5059   //  initializer-if-any};
5060   bool hasInit = (ND->getInit() != nullptr);
5061   // FIXME. rewriter does not support __block c++ objects which
5062   // require construction.
5063   if (hasInit)
5064     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5065       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5066       if (CXXDecl && CXXDecl->isDefaultConstructor())
5067         hasInit = false;
5068     }
5069 
5070   unsigned flags = 0;
5071   if (HasCopyAndDispose)
5072     flags |= BLOCK_HAS_COPY_DISPOSE;
5073   Name = ND->getNameAsString();
5074   ByrefType.clear();
5075   RewriteByRefString(ByrefType, Name, ND);
5076   std::string ForwardingCastType("(");
5077   ForwardingCastType += ByrefType + " *)";
5078   ByrefType += " " + Name + " = {(void*)";
5079   ByrefType += utostr(isa);
5080   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5081   ByrefType += utostr(flags);
5082   ByrefType += ", ";
5083   ByrefType += "sizeof(";
5084   RewriteByRefString(ByrefType, Name, ND);
5085   ByrefType += ")";
5086   if (HasCopyAndDispose) {
5087     ByrefType += ", __Block_byref_id_object_copy_";
5088     ByrefType += utostr(flag);
5089     ByrefType += ", __Block_byref_id_object_dispose_";
5090     ByrefType += utostr(flag);
5091   }
5092 
5093   if (!firstDecl) {
5094     // In multiple __block declarations, and for all but 1st declaration,
5095     // find location of the separating comma. This would be start location
5096     // where new text is to be inserted.
5097     DeclLoc = ND->getLocation();
5098     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5099     const char *commaBuf = startDeclBuf;
5100     while (*commaBuf != ',')
5101       commaBuf--;
5102     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5103     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5104     startBuf = commaBuf;
5105   }
5106 
5107   if (!hasInit) {
5108     ByrefType += "};\n";
5109     unsigned nameSize = Name.size();
5110     // for block or function pointer declaration. Name is already
5111     // part of the declaration.
5112     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5113       nameSize = 1;
5114     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5115   }
5116   else {
5117     ByrefType += ", ";
5118     SourceLocation startLoc;
5119     Expr *E = ND->getInit();
5120     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5121       startLoc = ECE->getLParenLoc();
5122     else
5123       startLoc = E->getBeginLoc();
5124     startLoc = SM->getExpansionLoc(startLoc);
5125     endBuf = SM->getCharacterData(startLoc);
5126     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5127 
5128     const char separator = lastDecl ? ';' : ',';
5129     const char *startInitializerBuf = SM->getCharacterData(startLoc);
5130     const char *separatorBuf = strchr(startInitializerBuf, separator);
5131     assert((*separatorBuf == separator) &&
5132            "RewriteByRefVar: can't find ';' or ','");
5133     SourceLocation separatorLoc =
5134       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5135 
5136     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5137   }
5138 }
5139 
5140 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5141   // Add initializers for any closure decl refs.
5142   GetBlockDeclRefExprs(Exp->getBody());
5143   if (BlockDeclRefs.size()) {
5144     // Unique all "by copy" declarations.
5145     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5146       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>())
5147         BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
5148     // Unique all "by ref" declarations.
5149     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5150       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>())
5151         BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
5152     // Find any imported blocks...they will need special attention.
5153     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5154       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5155           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5156           BlockDeclRefs[i]->getType()->isBlockPointerType())
5157         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5158   }
5159 }
5160 
5161 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5162   IdentifierInfo *ID = &Context->Idents.get(name);
5163   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5164   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5165                               SourceLocation(), ID, FType, nullptr, SC_Extern,
5166                               false, false);
5167 }
5168 
5169 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5170                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5171   const BlockDecl *block = Exp->getBlockDecl();
5172 
5173   Blocks.push_back(Exp);
5174 
5175   CollectBlockDeclRefInfo(Exp);
5176 
5177   // Add inner imported variables now used in current block.
5178   int countOfInnerDecls = 0;
5179   if (!InnerBlockDeclRefs.empty()) {
5180     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5181       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5182       ValueDecl *VD = Exp->getDecl();
5183       if (!VD->hasAttr<BlocksAttr>() && BlockByCopyDecls.insert(VD)) {
5184         // We need to save the copied-in variables in nested
5185         // blocks because it is needed at the end for some of the API
5186         // generations. See SynthesizeBlockLiterals routine.
5187         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5188         BlockDeclRefs.push_back(Exp);
5189       }
5190       if (VD->hasAttr<BlocksAttr>() && BlockByRefDecls.insert(VD)) {
5191         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5192         BlockDeclRefs.push_back(Exp);
5193       }
5194     }
5195     // Find any imported blocks...they will need special attention.
5196     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5197       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5198           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5199           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5200         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5201   }
5202   InnerDeclRefsCount.push_back(countOfInnerDecls);
5203 
5204   std::string FuncName;
5205 
5206   if (CurFunctionDef)
5207     FuncName = CurFunctionDef->getNameAsString();
5208   else if (CurMethodDef)
5209     BuildUniqueMethodName(FuncName, CurMethodDef);
5210   else if (GlobalVarDecl)
5211     FuncName = std::string(GlobalVarDecl->getNameAsString());
5212 
5213   bool GlobalBlockExpr =
5214     block->getDeclContext()->getRedeclContext()->isFileContext();
5215 
5216   if (GlobalBlockExpr && !GlobalVarDecl) {
5217     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5218     GlobalBlockExpr = false;
5219   }
5220 
5221   std::string BlockNumber = utostr(Blocks.size()-1);
5222 
5223   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5224 
5225   // Get a pointer to the function type so we can cast appropriately.
5226   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5227   QualType FType = Context->getPointerType(BFT);
5228 
5229   FunctionDecl *FD;
5230   Expr *NewRep;
5231 
5232   // Simulate a constructor call...
5233   std::string Tag;
5234 
5235   if (GlobalBlockExpr)
5236     Tag = "__global_";
5237   else
5238     Tag = "__";
5239   Tag += FuncName + "_block_impl_" + BlockNumber;
5240 
5241   FD = SynthBlockInitFunctionDecl(Tag);
5242   DeclRefExpr *DRE = new (Context)
5243       DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation());
5244 
5245   SmallVector<Expr*, 4> InitExprs;
5246 
5247   // Initialize the block function.
5248   FD = SynthBlockInitFunctionDecl(Func);
5249   DeclRefExpr *Arg = new (Context) DeclRefExpr(
5250       *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5251   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5252                                                 CK_BitCast, Arg);
5253   InitExprs.push_back(castExpr);
5254 
5255   // Initialize the block descriptor.
5256   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5257 
5258   VarDecl *NewVD = VarDecl::Create(
5259       *Context, TUDecl, SourceLocation(), SourceLocation(),
5260       &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5261   UnaryOperator *DescRefExpr = UnaryOperator::Create(
5262       const_cast<ASTContext &>(*Context),
5263       new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5264                                 VK_LValue, SourceLocation()),
5265       UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
5266       OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
5267   InitExprs.push_back(DescRefExpr);
5268 
5269   // Add initializers for any closure decl refs.
5270   if (BlockDeclRefs.size()) {
5271     Expr *Exp;
5272     // Output all "by copy" declarations.
5273     for (ValueDecl *VD : BlockByCopyDecls) {
5274       if (isObjCType(VD->getType())) {
5275         // FIXME: Conform to ABI ([[obj retain] autorelease]).
5276         FD = SynthBlockInitFunctionDecl(VD->getName());
5277         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5278                                         VK_LValue, SourceLocation());
5279         if (HasLocalVariableExternalStorage(VD)) {
5280           QualType QT = VD->getType();
5281           QT = Context->getPointerType(QT);
5282           Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
5283                                       UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
5284                                       SourceLocation(), false,
5285                                       FPOptionsOverride());
5286         }
5287       } else if (isTopLevelBlockPointerType(VD->getType())) {
5288         FD = SynthBlockInitFunctionDecl(VD->getName());
5289         Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5290                                         VK_LValue, SourceLocation());
5291         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5292                                        CK_BitCast, Arg);
5293       } else {
5294         FD = SynthBlockInitFunctionDecl(VD->getName());
5295         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5296                                         VK_LValue, SourceLocation());
5297         if (HasLocalVariableExternalStorage(VD)) {
5298           QualType QT = VD->getType();
5299           QT = Context->getPointerType(QT);
5300           Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
5301                                       UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
5302                                       SourceLocation(), false,
5303                                       FPOptionsOverride());
5304         }
5305       }
5306       InitExprs.push_back(Exp);
5307     }
5308     // Output all "by ref" declarations.
5309     for (ValueDecl *ND : BlockByRefDecls) {
5310       std::string Name(ND->getNameAsString());
5311       std::string RecName;
5312       RewriteByRefString(RecName, Name, ND, true);
5313       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5314                                                 + sizeof("struct"));
5315       RecordDecl *RD =
5316           RecordDecl::Create(*Context, TagTypeKind::Struct, TUDecl,
5317                              SourceLocation(), SourceLocation(), II);
5318       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5319       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5320 
5321       FD = SynthBlockInitFunctionDecl(ND->getName());
5322       Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5323                                       VK_LValue, SourceLocation());
5324       bool isNestedCapturedVar = false;
5325       for (const auto &CI : block->captures()) {
5326         const VarDecl *variable = CI.getVariable();
5327         if (variable == ND && CI.isNested()) {
5328           assert(CI.isByRef() &&
5329                  "SynthBlockInitExpr - captured block variable is not byref");
5330           isNestedCapturedVar = true;
5331           break;
5332         }
5333       }
5334       // captured nested byref variable has its address passed. Do not take
5335       // its address again.
5336       if (!isNestedCapturedVar)
5337         Exp = UnaryOperator::Create(
5338             const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
5339             Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary,
5340             SourceLocation(), false, FPOptionsOverride());
5341       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5342       InitExprs.push_back(Exp);
5343     }
5344   }
5345   if (ImportedBlockDecls.size()) {
5346     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5347     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5348     unsigned IntSize =
5349       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5350     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5351                                            Context->IntTy, SourceLocation());
5352     InitExprs.push_back(FlagExp);
5353   }
5354   NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5355                             SourceLocation(), FPOptionsOverride());
5356 
5357   if (GlobalBlockExpr) {
5358     assert (!GlobalConstructionExp &&
5359             "SynthBlockInitExpr - GlobalConstructionExp must be null");
5360     GlobalConstructionExp = NewRep;
5361     NewRep = DRE;
5362   }
5363 
5364   NewRep = UnaryOperator::Create(
5365       const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
5366       Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary,
5367       SourceLocation(), false, FPOptionsOverride());
5368   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5369                                     NewRep);
5370   // Put Paren around the call.
5371   NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5372                                    NewRep);
5373 
5374   BlockDeclRefs.clear();
5375   BlockByRefDecls.clear();
5376   BlockByCopyDecls.clear();
5377   ImportedBlockDecls.clear();
5378   return NewRep;
5379 }
5380 
5381 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5382   if (const ObjCForCollectionStmt * CS =
5383       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5384         return CS->getElement() == DS;
5385   return false;
5386 }
5387 
5388 //===----------------------------------------------------------------------===//
5389 // Function Body / Expression rewriting
5390 //===----------------------------------------------------------------------===//
5391 
5392 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5393   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5394       isa<DoStmt>(S) || isa<ForStmt>(S))
5395     Stmts.push_back(S);
5396   else if (isa<ObjCForCollectionStmt>(S)) {
5397     Stmts.push_back(S);
5398     ObjCBcLabelNo.push_back(++BcLabelCount);
5399   }
5400 
5401   // Pseudo-object operations and ivar references need special
5402   // treatment because we're going to recursively rewrite them.
5403   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5404     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5405       return RewritePropertyOrImplicitSetter(PseudoOp);
5406     } else {
5407       return RewritePropertyOrImplicitGetter(PseudoOp);
5408     }
5409   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5410     return RewriteObjCIvarRefExpr(IvarRefExpr);
5411   }
5412   else if (isa<OpaqueValueExpr>(S))
5413     S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5414 
5415   SourceRange OrigStmtRange = S->getSourceRange();
5416 
5417   // Perform a bottom up rewrite of all children.
5418   for (Stmt *&childStmt : S->children())
5419     if (childStmt) {
5420       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5421       if (newStmt) {
5422         childStmt = newStmt;
5423       }
5424     }
5425 
5426   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5427     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5428     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5429     InnerContexts.insert(BE->getBlockDecl());
5430     ImportedLocalExternalDecls.clear();
5431     GetInnerBlockDeclRefExprs(BE->getBody(),
5432                               InnerBlockDeclRefs, InnerContexts);
5433     // Rewrite the block body in place.
5434     Stmt *SaveCurrentBody = CurrentBody;
5435     CurrentBody = BE->getBody();
5436     PropParentMap = nullptr;
5437     // block literal on rhs of a property-dot-sytax assignment
5438     // must be replaced by its synthesize ast so getRewrittenText
5439     // works as expected. In this case, what actually ends up on RHS
5440     // is the blockTranscribed which is the helper function for the
5441     // block literal; as in: self.c = ^() {[ace ARR];};
5442     bool saveDisableReplaceStmt = DisableReplaceStmt;
5443     DisableReplaceStmt = false;
5444     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5445     DisableReplaceStmt = saveDisableReplaceStmt;
5446     CurrentBody = SaveCurrentBody;
5447     PropParentMap = nullptr;
5448     ImportedLocalExternalDecls.clear();
5449     // Now we snarf the rewritten text and stash it away for later use.
5450     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5451     RewrittenBlockExprs[BE] = Str;
5452 
5453     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5454 
5455     //blockTranscribed->dump();
5456     ReplaceStmt(S, blockTranscribed);
5457     return blockTranscribed;
5458   }
5459   // Handle specific things.
5460   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5461     return RewriteAtEncode(AtEncode);
5462 
5463   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5464     return RewriteAtSelector(AtSelector);
5465 
5466   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5467     return RewriteObjCStringLiteral(AtString);
5468 
5469   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5470     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5471 
5472   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5473     return RewriteObjCBoxedExpr(BoxedExpr);
5474 
5475   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5476     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5477 
5478   if (ObjCDictionaryLiteral *DictionaryLitExpr =
5479         dyn_cast<ObjCDictionaryLiteral>(S))
5480     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5481 
5482   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5483 #if 0
5484     // Before we rewrite it, put the original message expression in a comment.
5485     SourceLocation startLoc = MessExpr->getBeginLoc();
5486     SourceLocation endLoc = MessExpr->getEndLoc();
5487 
5488     const char *startBuf = SM->getCharacterData(startLoc);
5489     const char *endBuf = SM->getCharacterData(endLoc);
5490 
5491     std::string messString;
5492     messString += "// ";
5493     messString.append(startBuf, endBuf-startBuf+1);
5494     messString += "\n";
5495 
5496     // FIXME: Missing definition of
5497     // InsertText(clang::SourceLocation, char const*, unsigned int).
5498     // InsertText(startLoc, messString);
5499     // Tried this, but it didn't work either...
5500     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5501 #endif
5502     return RewriteMessageExpr(MessExpr);
5503   }
5504 
5505   if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5506         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5507     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5508   }
5509 
5510   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5511     return RewriteObjCTryStmt(StmtTry);
5512 
5513   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5514     return RewriteObjCSynchronizedStmt(StmtTry);
5515 
5516   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5517     return RewriteObjCThrowStmt(StmtThrow);
5518 
5519   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5520     return RewriteObjCProtocolExpr(ProtocolExp);
5521 
5522   if (ObjCForCollectionStmt *StmtForCollection =
5523         dyn_cast<ObjCForCollectionStmt>(S))
5524     return RewriteObjCForCollectionStmt(StmtForCollection,
5525                                         OrigStmtRange.getEnd());
5526   if (BreakStmt *StmtBreakStmt =
5527       dyn_cast<BreakStmt>(S))
5528     return RewriteBreakStmt(StmtBreakStmt);
5529   if (ContinueStmt *StmtContinueStmt =
5530       dyn_cast<ContinueStmt>(S))
5531     return RewriteContinueStmt(StmtContinueStmt);
5532 
5533   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5534   // and cast exprs.
5535   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5536     // FIXME: What we're doing here is modifying the type-specifier that
5537     // precedes the first Decl.  In the future the DeclGroup should have
5538     // a separate type-specifier that we can rewrite.
5539     // NOTE: We need to avoid rewriting the DeclStmt if it is within
5540     // the context of an ObjCForCollectionStmt. For example:
5541     //   NSArray *someArray;
5542     //   for (id <FooProtocol> index in someArray) ;
5543     // This is because RewriteObjCForCollectionStmt() does textual rewriting
5544     // and it depends on the original text locations/positions.
5545     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5546       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5547 
5548     // Blocks rewrite rules.
5549     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5550          DI != DE; ++DI) {
5551       Decl *SD = *DI;
5552       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5553         if (isTopLevelBlockPointerType(ND->getType()))
5554           RewriteBlockPointerDecl(ND);
5555         else if (ND->getType()->isFunctionPointerType())
5556           CheckFunctionPointerDecl(ND->getType(), ND);
5557         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5558           if (VD->hasAttr<BlocksAttr>()) {
5559             static unsigned uniqueByrefDeclCount = 0;
5560             assert(!BlockByRefDeclNo.count(ND) &&
5561               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5562             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5563             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5564           }
5565           else
5566             RewriteTypeOfDecl(VD);
5567         }
5568       }
5569       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5570         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5571           RewriteBlockPointerDecl(TD);
5572         else if (TD->getUnderlyingType()->isFunctionPointerType())
5573           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5574       }
5575     }
5576   }
5577 
5578   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5579     RewriteObjCQualifiedInterfaceTypes(CE);
5580 
5581   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5582       isa<DoStmt>(S) || isa<ForStmt>(S)) {
5583     assert(!Stmts.empty() && "Statement stack is empty");
5584     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5585              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5586             && "Statement stack mismatch");
5587     Stmts.pop_back();
5588   }
5589   // Handle blocks rewriting.
5590   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5591     ValueDecl *VD = DRE->getDecl();
5592     if (VD->hasAttr<BlocksAttr>())
5593       return RewriteBlockDeclRefExpr(DRE);
5594     if (HasLocalVariableExternalStorage(VD))
5595       return RewriteLocalVariableExternalStorage(DRE);
5596   }
5597 
5598   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5599     if (CE->getCallee()->getType()->isBlockPointerType()) {
5600       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5601       ReplaceStmt(S, BlockCall);
5602       return BlockCall;
5603     }
5604   }
5605   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5606     RewriteCastExpr(CE);
5607   }
5608   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5609     RewriteImplicitCastObjCExpr(ICE);
5610   }
5611 #if 0
5612 
5613   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5614     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5615                                                    ICE->getSubExpr(),
5616                                                    SourceLocation());
5617     // Get the new text.
5618     std::string SStr;
5619     llvm::raw_string_ostream Buf(SStr);
5620     Replacement->printPretty(Buf);
5621     const std::string &Str = Buf.str();
5622 
5623     printf("CAST = %s\n", &Str[0]);
5624     InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5625     delete S;
5626     return Replacement;
5627   }
5628 #endif
5629   // Return this stmt unmodified.
5630   return S;
5631 }
5632 
5633 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5634   for (auto *FD : RD->fields()) {
5635     if (isTopLevelBlockPointerType(FD->getType()))
5636       RewriteBlockPointerDecl(FD);
5637     if (FD->getType()->isObjCQualifiedIdType() ||
5638         FD->getType()->isObjCQualifiedInterfaceType())
5639       RewriteObjCQualifiedInterfaceTypes(FD);
5640   }
5641 }
5642 
5643 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5644 /// main file of the input.
5645 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5646   switch (D->getKind()) {
5647     case Decl::Function: {
5648       FunctionDecl *FD = cast<FunctionDecl>(D);
5649       if (FD->isOverloadedOperator())
5650         return;
5651 
5652       // Since function prototypes don't have ParmDecl's, we check the function
5653       // prototype. This enables us to rewrite function declarations and
5654       // definitions using the same code.
5655       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5656 
5657       if (!FD->isThisDeclarationADefinition())
5658         break;
5659 
5660       // FIXME: If this should support Obj-C++, support CXXTryStmt
5661       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5662         CurFunctionDef = FD;
5663         CurrentBody = Body;
5664         Body =
5665         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5666         FD->setBody(Body);
5667         CurrentBody = nullptr;
5668         if (PropParentMap) {
5669           delete PropParentMap;
5670           PropParentMap = nullptr;
5671         }
5672         // This synthesizes and inserts the block "impl" struct, invoke function,
5673         // and any copy/dispose helper functions.
5674         InsertBlockLiteralsWithinFunction(FD);
5675         RewriteLineDirective(D);
5676         CurFunctionDef = nullptr;
5677       }
5678       break;
5679     }
5680     case Decl::ObjCMethod: {
5681       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5682       if (CompoundStmt *Body = MD->getCompoundBody()) {
5683         CurMethodDef = MD;
5684         CurrentBody = Body;
5685         Body =
5686           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5687         MD->setBody(Body);
5688         CurrentBody = nullptr;
5689         if (PropParentMap) {
5690           delete PropParentMap;
5691           PropParentMap = nullptr;
5692         }
5693         InsertBlockLiteralsWithinMethod(MD);
5694         RewriteLineDirective(D);
5695         CurMethodDef = nullptr;
5696       }
5697       break;
5698     }
5699     case Decl::ObjCImplementation: {
5700       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5701       ClassImplementation.push_back(CI);
5702       break;
5703     }
5704     case Decl::ObjCCategoryImpl: {
5705       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5706       CategoryImplementation.push_back(CI);
5707       break;
5708     }
5709     case Decl::Var: {
5710       VarDecl *VD = cast<VarDecl>(D);
5711       RewriteObjCQualifiedInterfaceTypes(VD);
5712       if (isTopLevelBlockPointerType(VD->getType()))
5713         RewriteBlockPointerDecl(VD);
5714       else if (VD->getType()->isFunctionPointerType()) {
5715         CheckFunctionPointerDecl(VD->getType(), VD);
5716         if (VD->getInit()) {
5717           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5718             RewriteCastExpr(CE);
5719           }
5720         }
5721       } else if (VD->getType()->isRecordType()) {
5722         RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
5723         if (RD->isCompleteDefinition())
5724           RewriteRecordBody(RD);
5725       }
5726       if (VD->getInit()) {
5727         GlobalVarDecl = VD;
5728         CurrentBody = VD->getInit();
5729         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5730         CurrentBody = nullptr;
5731         if (PropParentMap) {
5732           delete PropParentMap;
5733           PropParentMap = nullptr;
5734         }
5735         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5736         GlobalVarDecl = nullptr;
5737 
5738         // This is needed for blocks.
5739         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5740             RewriteCastExpr(CE);
5741         }
5742       }
5743       break;
5744     }
5745     case Decl::TypeAlias:
5746     case Decl::Typedef: {
5747       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5748         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5749           RewriteBlockPointerDecl(TD);
5750         else if (TD->getUnderlyingType()->isFunctionPointerType())
5751           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5752         else
5753           RewriteObjCQualifiedInterfaceTypes(TD);
5754       }
5755       break;
5756     }
5757     case Decl::CXXRecord:
5758     case Decl::Record: {
5759       RecordDecl *RD = cast<RecordDecl>(D);
5760       if (RD->isCompleteDefinition())
5761         RewriteRecordBody(RD);
5762       break;
5763     }
5764     default:
5765       break;
5766   }
5767   // Nothing yet.
5768 }
5769 
5770 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5771 /// protocol reference symbols in the for of:
5772 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5773 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5774                                                  ObjCProtocolDecl *PDecl,
5775                                                  std::string &Result) {
5776   // Also output .objc_protorefs$B section and its meta-data.
5777   if (Context->getLangOpts().MicrosoftExt)
5778     Result += "static ";
5779   Result += "struct _protocol_t *";
5780   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5781   Result += PDecl->getNameAsString();
5782   Result += " = &";
5783   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5784   Result += ";\n";
5785 }
5786 
5787 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5788   if (Diags.hasErrorOccurred())
5789     return;
5790 
5791   RewriteInclude();
5792 
5793   for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5794     // translation of function bodies were postponed until all class and
5795     // their extensions and implementations are seen. This is because, we
5796     // cannot build grouping structs for bitfields until they are all seen.
5797     FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5798     HandleTopLevelSingleDecl(FDecl);
5799   }
5800 
5801   // Here's a great place to add any extra declarations that may be needed.
5802   // Write out meta data for each @protocol(<expr>).
5803   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5804     RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5805     Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5806   }
5807 
5808   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5809 
5810   if (ClassImplementation.size() || CategoryImplementation.size())
5811     RewriteImplementations();
5812 
5813   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5814     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5815     // Write struct declaration for the class matching its ivar declarations.
5816     // Note that for modern abi, this is postponed until the end of TU
5817     // because class extensions and the implementation might declare their own
5818     // private ivars.
5819     RewriteInterfaceDecl(CDecl);
5820   }
5821 
5822   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5823   // we are done.
5824   if (const RewriteBuffer *RewriteBuf =
5825       Rewrite.getRewriteBufferFor(MainFileID)) {
5826     //printf("Changed:\n");
5827     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5828   } else {
5829     llvm::errs() << "No changes\n";
5830   }
5831 
5832   if (ClassImplementation.size() || CategoryImplementation.size() ||
5833       ProtocolExprDecls.size()) {
5834     // Rewrite Objective-c meta data*
5835     std::string ResultStr;
5836     RewriteMetaDataIntoBuffer(ResultStr);
5837     // Emit metadata.
5838     *OutFile << ResultStr;
5839   }
5840   // Emit ImageInfo;
5841   {
5842     std::string ResultStr;
5843     WriteImageInfo(ResultStr);
5844     *OutFile << ResultStr;
5845   }
5846   OutFile->flush();
5847 }
5848 
5849 void RewriteModernObjC::Initialize(ASTContext &context) {
5850   InitializeCommon(context);
5851 
5852   Preamble += "#ifndef __OBJC2__\n";
5853   Preamble += "#define __OBJC2__\n";
5854   Preamble += "#endif\n";
5855 
5856   // declaring objc_selector outside the parameter list removes a silly
5857   // scope related warning...
5858   if (IsHeader)
5859     Preamble = "#pragma once\n";
5860   Preamble += "struct objc_selector; struct objc_class;\n";
5861   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5862   Preamble += "\n\tstruct objc_object *superClass; ";
5863   // Add a constructor for creating temporary objects.
5864   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5865   Preamble += ": object(o), superClass(s) {} ";
5866   Preamble += "\n};\n";
5867 
5868   if (LangOpts.MicrosoftExt) {
5869     // Define all sections using syntax that makes sense.
5870     // These are currently generated.
5871     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5872     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5873     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5874     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5875     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5876     // These are generated but not necessary for functionality.
5877     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5878     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5879     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5880     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5881 
5882     // These need be generated for performance. Currently they are not,
5883     // using API calls instead.
5884     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5885     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5886     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5887 
5888   }
5889   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5890   Preamble += "typedef struct objc_object Protocol;\n";
5891   Preamble += "#define _REWRITER_typedef_Protocol\n";
5892   Preamble += "#endif\n";
5893   if (LangOpts.MicrosoftExt) {
5894     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5895     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5896   }
5897   else
5898     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5899 
5900   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5901   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5902   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5903   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5904   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5905 
5906   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5907   Preamble += "(const char *);\n";
5908   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5909   Preamble += "(struct objc_class *);\n";
5910   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5911   Preamble += "(const char *);\n";
5912   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5913   // @synchronized hooks.
5914   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5915   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5916   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5917   Preamble += "#ifdef _WIN64\n";
5918   Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
5919   Preamble += "#else\n";
5920   Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5921   Preamble += "#endif\n";
5922   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5923   Preamble += "struct __objcFastEnumerationState {\n\t";
5924   Preamble += "unsigned long state;\n\t";
5925   Preamble += "void **itemsPtr;\n\t";
5926   Preamble += "unsigned long *mutationsPtr;\n\t";
5927   Preamble += "unsigned long extra[5];\n};\n";
5928   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5929   Preamble += "#define __FASTENUMERATIONSTATE\n";
5930   Preamble += "#endif\n";
5931   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5932   Preamble += "struct __NSConstantStringImpl {\n";
5933   Preamble += "  int *isa;\n";
5934   Preamble += "  int flags;\n";
5935   Preamble += "  char *str;\n";
5936   Preamble += "#if _WIN64\n";
5937   Preamble += "  long long length;\n";
5938   Preamble += "#else\n";
5939   Preamble += "  long length;\n";
5940   Preamble += "#endif\n";
5941   Preamble += "};\n";
5942   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5943   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5944   Preamble += "#else\n";
5945   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5946   Preamble += "#endif\n";
5947   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5948   Preamble += "#endif\n";
5949   // Blocks preamble.
5950   Preamble += "#ifndef BLOCK_IMPL\n";
5951   Preamble += "#define BLOCK_IMPL\n";
5952   Preamble += "struct __block_impl {\n";
5953   Preamble += "  void *isa;\n";
5954   Preamble += "  int Flags;\n";
5955   Preamble += "  int Reserved;\n";
5956   Preamble += "  void *FuncPtr;\n";
5957   Preamble += "};\n";
5958   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5959   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5960   Preamble += "extern \"C\" __declspec(dllexport) "
5961   "void _Block_object_assign(void *, const void *, const int);\n";
5962   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5963   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5964   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5965   Preamble += "#else\n";
5966   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5967   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5968   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5969   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5970   Preamble += "#endif\n";
5971   Preamble += "#endif\n";
5972   if (LangOpts.MicrosoftExt) {
5973     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5974     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5975     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5976     Preamble += "#define __attribute__(X)\n";
5977     Preamble += "#endif\n";
5978     Preamble += "#ifndef __weak\n";
5979     Preamble += "#define __weak\n";
5980     Preamble += "#endif\n";
5981     Preamble += "#ifndef __block\n";
5982     Preamble += "#define __block\n";
5983     Preamble += "#endif\n";
5984   }
5985   else {
5986     Preamble += "#define __block\n";
5987     Preamble += "#define __weak\n";
5988   }
5989 
5990   // Declarations required for modern objective-c array and dictionary literals.
5991   Preamble += "\n#include <stdarg.h>\n";
5992   Preamble += "struct __NSContainer_literal {\n";
5993   Preamble += "  void * *arr;\n";
5994   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
5995   Preamble += "\tva_list marker;\n";
5996   Preamble += "\tva_start(marker, count);\n";
5997   Preamble += "\tarr = new void *[count];\n";
5998   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5999   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6000   Preamble += "\tva_end( marker );\n";
6001   Preamble += "  };\n";
6002   Preamble += "  ~__NSContainer_literal() {\n";
6003   Preamble += "\tdelete[] arr;\n";
6004   Preamble += "  }\n";
6005   Preamble += "};\n";
6006 
6007   // Declaration required for implementation of @autoreleasepool statement.
6008   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6009   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6010   Preamble += "struct __AtAutoreleasePool {\n";
6011   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6012   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6013   Preamble += "  void * atautoreleasepoolobj;\n";
6014   Preamble += "};\n";
6015 
6016   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6017   // as this avoids warning in any 64bit/32bit compilation model.
6018   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6019 }
6020 
6021 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
6022 /// ivar offset.
6023 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6024                                                          std::string &Result) {
6025   Result += "__OFFSETOFIVAR__(struct ";
6026   Result += ivar->getContainingInterface()->getNameAsString();
6027   if (LangOpts.MicrosoftExt)
6028     Result += "_IMPL";
6029   Result += ", ";
6030   if (ivar->isBitField())
6031     ObjCIvarBitfieldGroupDecl(ivar, Result);
6032   else
6033     Result += ivar->getNameAsString();
6034   Result += ")";
6035 }
6036 
6037 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6038 /// struct _prop_t {
6039 ///   const char *name;
6040 ///   char *attributes;
6041 /// }
6042 
6043 /// struct _prop_list_t {
6044 ///   uint32_t entsize;      // sizeof(struct _prop_t)
6045 ///   uint32_t count_of_properties;
6046 ///   struct _prop_t prop_list[count_of_properties];
6047 /// }
6048 
6049 /// struct _protocol_t;
6050 
6051 /// struct _protocol_list_t {
6052 ///   long protocol_count;   // Note, this is 32/64 bit
6053 ///   struct _protocol_t * protocol_list[protocol_count];
6054 /// }
6055 
6056 /// struct _objc_method {
6057 ///   SEL _cmd;
6058 ///   const char *method_type;
6059 ///   char *_imp;
6060 /// }
6061 
6062 /// struct _method_list_t {
6063 ///   uint32_t entsize;  // sizeof(struct _objc_method)
6064 ///   uint32_t method_count;
6065 ///   struct _objc_method method_list[method_count];
6066 /// }
6067 
6068 /// struct _protocol_t {
6069 ///   id isa;  // NULL
6070 ///   const char *protocol_name;
6071 ///   const struct _protocol_list_t * protocol_list; // super protocols
6072 ///   const struct method_list_t *instance_methods;
6073 ///   const struct method_list_t *class_methods;
6074 ///   const struct method_list_t *optionalInstanceMethods;
6075 ///   const struct method_list_t *optionalClassMethods;
6076 ///   const struct _prop_list_t * properties;
6077 ///   const uint32_t size;  // sizeof(struct _protocol_t)
6078 ///   const uint32_t flags;  // = 0
6079 ///   const char ** extendedMethodTypes;
6080 /// }
6081 
6082 /// struct _ivar_t {
6083 ///   unsigned long int *offset;  // pointer to ivar offset location
6084 ///   const char *name;
6085 ///   const char *type;
6086 ///   uint32_t alignment;
6087 ///   uint32_t size;
6088 /// }
6089 
6090 /// struct _ivar_list_t {
6091 ///   uint32 entsize;  // sizeof(struct _ivar_t)
6092 ///   uint32 count;
6093 ///   struct _ivar_t list[count];
6094 /// }
6095 
6096 /// struct _class_ro_t {
6097 ///   uint32_t flags;
6098 ///   uint32_t instanceStart;
6099 ///   uint32_t instanceSize;
6100 ///   uint32_t reserved;  // only when building for 64bit targets
6101 ///   const uint8_t *ivarLayout;
6102 ///   const char *name;
6103 ///   const struct _method_list_t *baseMethods;
6104 ///   const struct _protocol_list_t *baseProtocols;
6105 ///   const struct _ivar_list_t *ivars;
6106 ///   const uint8_t *weakIvarLayout;
6107 ///   const struct _prop_list_t *properties;
6108 /// }
6109 
6110 /// struct _class_t {
6111 ///   struct _class_t *isa;
6112 ///   struct _class_t *superclass;
6113 ///   void *cache;
6114 ///   IMP *vtable;
6115 ///   struct _class_ro_t *ro;
6116 /// }
6117 
6118 /// struct _category_t {
6119 ///   const char *name;
6120 ///   struct _class_t *cls;
6121 ///   const struct _method_list_t *instance_methods;
6122 ///   const struct _method_list_t *class_methods;
6123 ///   const struct _protocol_list_t *protocols;
6124 ///   const struct _prop_list_t *properties;
6125 /// }
6126 
6127 /// MessageRefTy - LLVM for:
6128 /// struct _message_ref_t {
6129 ///   IMP messenger;
6130 ///   SEL name;
6131 /// };
6132 
6133 /// SuperMessageRefTy - LLVM for:
6134 /// struct _super_message_ref_t {
6135 ///   SUPER_IMP messenger;
6136 ///   SEL name;
6137 /// };
6138 
6139 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6140   static bool meta_data_declared = false;
6141   if (meta_data_declared)
6142     return;
6143 
6144   Result += "\nstruct _prop_t {\n";
6145   Result += "\tconst char *name;\n";
6146   Result += "\tconst char *attributes;\n";
6147   Result += "};\n";
6148 
6149   Result += "\nstruct _protocol_t;\n";
6150 
6151   Result += "\nstruct _objc_method {\n";
6152   Result += "\tstruct objc_selector * _cmd;\n";
6153   Result += "\tconst char *method_type;\n";
6154   Result += "\tvoid  *_imp;\n";
6155   Result += "};\n";
6156 
6157   Result += "\nstruct _protocol_t {\n";
6158   Result += "\tvoid * isa;  // NULL\n";
6159   Result += "\tconst char *protocol_name;\n";
6160   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6161   Result += "\tconst struct method_list_t *instance_methods;\n";
6162   Result += "\tconst struct method_list_t *class_methods;\n";
6163   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6164   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6165   Result += "\tconst struct _prop_list_t * properties;\n";
6166   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6167   Result += "\tconst unsigned int flags;  // = 0\n";
6168   Result += "\tconst char ** extendedMethodTypes;\n";
6169   Result += "};\n";
6170 
6171   Result += "\nstruct _ivar_t {\n";
6172   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6173   Result += "\tconst char *name;\n";
6174   Result += "\tconst char *type;\n";
6175   Result += "\tunsigned int alignment;\n";
6176   Result += "\tunsigned int  size;\n";
6177   Result += "};\n";
6178 
6179   Result += "\nstruct _class_ro_t {\n";
6180   Result += "\tunsigned int flags;\n";
6181   Result += "\tunsigned int instanceStart;\n";
6182   Result += "\tunsigned int instanceSize;\n";
6183   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6184   if (Triple.getArch() == llvm::Triple::x86_64)
6185     Result += "\tunsigned int reserved;\n";
6186   Result += "\tconst unsigned char *ivarLayout;\n";
6187   Result += "\tconst char *name;\n";
6188   Result += "\tconst struct _method_list_t *baseMethods;\n";
6189   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6190   Result += "\tconst struct _ivar_list_t *ivars;\n";
6191   Result += "\tconst unsigned char *weakIvarLayout;\n";
6192   Result += "\tconst struct _prop_list_t *properties;\n";
6193   Result += "};\n";
6194 
6195   Result += "\nstruct _class_t {\n";
6196   Result += "\tstruct _class_t *isa;\n";
6197   Result += "\tstruct _class_t *superclass;\n";
6198   Result += "\tvoid *cache;\n";
6199   Result += "\tvoid *vtable;\n";
6200   Result += "\tstruct _class_ro_t *ro;\n";
6201   Result += "};\n";
6202 
6203   Result += "\nstruct _category_t {\n";
6204   Result += "\tconst char *name;\n";
6205   Result += "\tstruct _class_t *cls;\n";
6206   Result += "\tconst struct _method_list_t *instance_methods;\n";
6207   Result += "\tconst struct _method_list_t *class_methods;\n";
6208   Result += "\tconst struct _protocol_list_t *protocols;\n";
6209   Result += "\tconst struct _prop_list_t *properties;\n";
6210   Result += "};\n";
6211 
6212   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6213   Result += "#pragma warning(disable:4273)\n";
6214   meta_data_declared = true;
6215 }
6216 
6217 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6218                                            long super_protocol_count) {
6219   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6220   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6221   Result += "\tstruct _protocol_t *super_protocols[";
6222   Result += utostr(super_protocol_count); Result += "];\n";
6223   Result += "}";
6224 }
6225 
6226 static void Write_method_list_t_TypeDecl(std::string &Result,
6227                                          unsigned int method_count) {
6228   Result += "struct /*_method_list_t*/"; Result += " {\n";
6229   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6230   Result += "\tunsigned int method_count;\n";
6231   Result += "\tstruct _objc_method method_list[";
6232   Result += utostr(method_count); Result += "];\n";
6233   Result += "}";
6234 }
6235 
6236 static void Write__prop_list_t_TypeDecl(std::string &Result,
6237                                         unsigned int property_count) {
6238   Result += "struct /*_prop_list_t*/"; Result += " {\n";
6239   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6240   Result += "\tunsigned int count_of_properties;\n";
6241   Result += "\tstruct _prop_t prop_list[";
6242   Result += utostr(property_count); Result += "];\n";
6243   Result += "}";
6244 }
6245 
6246 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6247                                         unsigned int ivar_count) {
6248   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6249   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6250   Result += "\tunsigned int count;\n";
6251   Result += "\tstruct _ivar_t ivar_list[";
6252   Result += utostr(ivar_count); Result += "];\n";
6253   Result += "}";
6254 }
6255 
6256 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6257                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6258                                             StringRef VarName,
6259                                             StringRef ProtocolName) {
6260   if (SuperProtocols.size() > 0) {
6261     Result += "\nstatic ";
6262     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6263     Result += " "; Result += VarName;
6264     Result += ProtocolName;
6265     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6266     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6267     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6268       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6269       Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6270       Result += SuperPD->getNameAsString();
6271       if (i == e-1)
6272         Result += "\n};\n";
6273       else
6274         Result += ",\n";
6275     }
6276   }
6277 }
6278 
6279 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6280                                             ASTContext *Context, std::string &Result,
6281                                             ArrayRef<ObjCMethodDecl *> Methods,
6282                                             StringRef VarName,
6283                                             StringRef TopLevelDeclName,
6284                                             bool MethodImpl) {
6285   if (Methods.size() > 0) {
6286     Result += "\nstatic ";
6287     Write_method_list_t_TypeDecl(Result, Methods.size());
6288     Result += " "; Result += VarName;
6289     Result += TopLevelDeclName;
6290     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6291     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6292     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6293     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6294       ObjCMethodDecl *MD = Methods[i];
6295       if (i == 0)
6296         Result += "\t{{(struct objc_selector *)\"";
6297       else
6298         Result += "\t{(struct objc_selector *)\"";
6299       Result += (MD)->getSelector().getAsString(); Result += "\"";
6300       Result += ", ";
6301       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6302       Result += "\""; Result += MethodTypeString; Result += "\"";
6303       Result += ", ";
6304       if (!MethodImpl)
6305         Result += "0";
6306       else {
6307         Result += "(void *)";
6308         Result += RewriteObj.MethodInternalNames[MD];
6309       }
6310       if (i  == e-1)
6311         Result += "}}\n";
6312       else
6313         Result += "},\n";
6314     }
6315     Result += "};\n";
6316   }
6317 }
6318 
6319 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6320                                            ASTContext *Context, std::string &Result,
6321                                            ArrayRef<ObjCPropertyDecl *> Properties,
6322                                            const Decl *Container,
6323                                            StringRef VarName,
6324                                            StringRef ProtocolName) {
6325   if (Properties.size() > 0) {
6326     Result += "\nstatic ";
6327     Write__prop_list_t_TypeDecl(Result, Properties.size());
6328     Result += " "; Result += VarName;
6329     Result += ProtocolName;
6330     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6331     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6332     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6333     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6334       ObjCPropertyDecl *PropDecl = Properties[i];
6335       if (i == 0)
6336         Result += "\t{{\"";
6337       else
6338         Result += "\t{\"";
6339       Result += PropDecl->getName(); Result += "\",";
6340       std::string PropertyTypeString =
6341         Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6342       std::string QuotePropertyTypeString;
6343       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6344       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6345       if (i  == e-1)
6346         Result += "}}\n";
6347       else
6348         Result += "},\n";
6349     }
6350     Result += "};\n";
6351   }
6352 }
6353 
6354 // Metadata flags
6355 enum MetaDataDlags {
6356   CLS = 0x0,
6357   CLS_META = 0x1,
6358   CLS_ROOT = 0x2,
6359   OBJC2_CLS_HIDDEN = 0x10,
6360   CLS_EXCEPTION = 0x20,
6361 
6362   /// (Obsolete) ARC-specific: this class has a .release_ivars method
6363   CLS_HAS_IVAR_RELEASER = 0x40,
6364   /// class was compiled with -fobjc-arr
6365   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6366 };
6367 
6368 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6369                                           unsigned int flags,
6370                                           const std::string &InstanceStart,
6371                                           const std::string &InstanceSize,
6372                                           ArrayRef<ObjCMethodDecl *>baseMethods,
6373                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
6374                                           ArrayRef<ObjCIvarDecl *>ivars,
6375                                           ArrayRef<ObjCPropertyDecl *>Properties,
6376                                           StringRef VarName,
6377                                           StringRef ClassName) {
6378   Result += "\nstatic struct _class_ro_t ";
6379   Result += VarName; Result += ClassName;
6380   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6381   Result += "\t";
6382   Result += llvm::utostr(flags); Result += ", ";
6383   Result += InstanceStart; Result += ", ";
6384   Result += InstanceSize; Result += ", \n";
6385   Result += "\t";
6386   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6387   if (Triple.getArch() == llvm::Triple::x86_64)
6388     // uint32_t const reserved; // only when building for 64bit targets
6389     Result += "(unsigned int)0, \n\t";
6390   // const uint8_t * const ivarLayout;
6391   Result += "0, \n\t";
6392   Result += "\""; Result += ClassName; Result += "\",\n\t";
6393   bool metaclass = ((flags & CLS_META) != 0);
6394   if (baseMethods.size() > 0) {
6395     Result += "(const struct _method_list_t *)&";
6396     if (metaclass)
6397       Result += "_OBJC_$_CLASS_METHODS_";
6398     else
6399       Result += "_OBJC_$_INSTANCE_METHODS_";
6400     Result += ClassName;
6401     Result += ",\n\t";
6402   }
6403   else
6404     Result += "0, \n\t";
6405 
6406   if (!metaclass && baseProtocols.size() > 0) {
6407     Result += "(const struct _objc_protocol_list *)&";
6408     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6409     Result += ",\n\t";
6410   }
6411   else
6412     Result += "0, \n\t";
6413 
6414   if (!metaclass && ivars.size() > 0) {
6415     Result += "(const struct _ivar_list_t *)&";
6416     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6417     Result += ",\n\t";
6418   }
6419   else
6420     Result += "0, \n\t";
6421 
6422   // weakIvarLayout
6423   Result += "0, \n\t";
6424   if (!metaclass && Properties.size() > 0) {
6425     Result += "(const struct _prop_list_t *)&";
6426     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6427     Result += ",\n";
6428   }
6429   else
6430     Result += "0, \n";
6431 
6432   Result += "};\n";
6433 }
6434 
6435 static void Write_class_t(ASTContext *Context, std::string &Result,
6436                           StringRef VarName,
6437                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
6438   bool rootClass = (!CDecl->getSuperClass());
6439   const ObjCInterfaceDecl *RootClass = CDecl;
6440 
6441   if (!rootClass) {
6442     // Find the Root class
6443     RootClass = CDecl->getSuperClass();
6444     while (RootClass->getSuperClass()) {
6445       RootClass = RootClass->getSuperClass();
6446     }
6447   }
6448 
6449   if (metaclass && rootClass) {
6450     // Need to handle a case of use of forward declaration.
6451     Result += "\n";
6452     Result += "extern \"C\" ";
6453     if (CDecl->getImplementation())
6454       Result += "__declspec(dllexport) ";
6455     else
6456       Result += "__declspec(dllimport) ";
6457 
6458     Result += "struct _class_t OBJC_CLASS_$_";
6459     Result += CDecl->getNameAsString();
6460     Result += ";\n";
6461   }
6462   // Also, for possibility of 'super' metadata class not having been defined yet.
6463   if (!rootClass) {
6464     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6465     Result += "\n";
6466     Result += "extern \"C\" ";
6467     if (SuperClass->getImplementation())
6468       Result += "__declspec(dllexport) ";
6469     else
6470       Result += "__declspec(dllimport) ";
6471 
6472     Result += "struct _class_t ";
6473     Result += VarName;
6474     Result += SuperClass->getNameAsString();
6475     Result += ";\n";
6476 
6477     if (metaclass && RootClass != SuperClass) {
6478       Result += "extern \"C\" ";
6479       if (RootClass->getImplementation())
6480         Result += "__declspec(dllexport) ";
6481       else
6482         Result += "__declspec(dllimport) ";
6483 
6484       Result += "struct _class_t ";
6485       Result += VarName;
6486       Result += RootClass->getNameAsString();
6487       Result += ";\n";
6488     }
6489   }
6490 
6491   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6492   Result += VarName; Result += CDecl->getNameAsString();
6493   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6494   Result += "\t";
6495   if (metaclass) {
6496     if (!rootClass) {
6497       Result += "0, // &"; Result += VarName;
6498       Result += RootClass->getNameAsString();
6499       Result += ",\n\t";
6500       Result += "0, // &"; Result += VarName;
6501       Result += CDecl->getSuperClass()->getNameAsString();
6502       Result += ",\n\t";
6503     }
6504     else {
6505       Result += "0, // &"; Result += VarName;
6506       Result += CDecl->getNameAsString();
6507       Result += ",\n\t";
6508       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6509       Result += ",\n\t";
6510     }
6511   }
6512   else {
6513     Result += "0, // &OBJC_METACLASS_$_";
6514     Result += CDecl->getNameAsString();
6515     Result += ",\n\t";
6516     if (!rootClass) {
6517       Result += "0, // &"; Result += VarName;
6518       Result += CDecl->getSuperClass()->getNameAsString();
6519       Result += ",\n\t";
6520     }
6521     else
6522       Result += "0,\n\t";
6523   }
6524   Result += "0, // (void *)&_objc_empty_cache,\n\t";
6525   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6526   if (metaclass)
6527     Result += "&_OBJC_METACLASS_RO_$_";
6528   else
6529     Result += "&_OBJC_CLASS_RO_$_";
6530   Result += CDecl->getNameAsString();
6531   Result += ",\n};\n";
6532 
6533   // Add static function to initialize some of the meta-data fields.
6534   // avoid doing it twice.
6535   if (metaclass)
6536     return;
6537 
6538   const ObjCInterfaceDecl *SuperClass =
6539     rootClass ? CDecl : CDecl->getSuperClass();
6540 
6541   Result += "static void OBJC_CLASS_SETUP_$_";
6542   Result += CDecl->getNameAsString();
6543   Result += "(void ) {\n";
6544   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6545   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6546   Result += RootClass->getNameAsString(); Result += ";\n";
6547 
6548   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6549   Result += ".superclass = ";
6550   if (rootClass)
6551     Result += "&OBJC_CLASS_$_";
6552   else
6553      Result += "&OBJC_METACLASS_$_";
6554 
6555   Result += SuperClass->getNameAsString(); Result += ";\n";
6556 
6557   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6558   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6559 
6560   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6561   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6562   Result += CDecl->getNameAsString(); Result += ";\n";
6563 
6564   if (!rootClass) {
6565     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6566     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6567     Result += SuperClass->getNameAsString(); Result += ";\n";
6568   }
6569 
6570   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6571   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6572   Result += "}\n";
6573 }
6574 
6575 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6576                              std::string &Result,
6577                              ObjCCategoryDecl *CatDecl,
6578                              ObjCInterfaceDecl *ClassDecl,
6579                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
6580                              ArrayRef<ObjCMethodDecl *> ClassMethods,
6581                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6582                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6583   StringRef CatName = CatDecl->getName();
6584   StringRef ClassName = ClassDecl->getName();
6585   // must declare an extern class object in case this class is not implemented
6586   // in this TU.
6587   Result += "\n";
6588   Result += "extern \"C\" ";
6589   if (ClassDecl->getImplementation())
6590     Result += "__declspec(dllexport) ";
6591   else
6592     Result += "__declspec(dllimport) ";
6593 
6594   Result += "struct _class_t ";
6595   Result += "OBJC_CLASS_$_"; Result += ClassName;
6596   Result += ";\n";
6597 
6598   Result += "\nstatic struct _category_t ";
6599   Result += "_OBJC_$_CATEGORY_";
6600   Result += ClassName; Result += "_$_"; Result += CatName;
6601   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6602   Result += "{\n";
6603   Result += "\t\""; Result += ClassName; Result += "\",\n";
6604   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6605   Result += ",\n";
6606   if (InstanceMethods.size() > 0) {
6607     Result += "\t(const struct _method_list_t *)&";
6608     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6609     Result += ClassName; Result += "_$_"; Result += CatName;
6610     Result += ",\n";
6611   }
6612   else
6613     Result += "\t0,\n";
6614 
6615   if (ClassMethods.size() > 0) {
6616     Result += "\t(const struct _method_list_t *)&";
6617     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6618     Result += ClassName; Result += "_$_"; Result += CatName;
6619     Result += ",\n";
6620   }
6621   else
6622     Result += "\t0,\n";
6623 
6624   if (RefedProtocols.size() > 0) {
6625     Result += "\t(const struct _protocol_list_t *)&";
6626     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6627     Result += ClassName; Result += "_$_"; Result += CatName;
6628     Result += ",\n";
6629   }
6630   else
6631     Result += "\t0,\n";
6632 
6633   if (ClassProperties.size() > 0) {
6634     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6635     Result += ClassName; Result += "_$_"; Result += CatName;
6636     Result += ",\n";
6637   }
6638   else
6639     Result += "\t0,\n";
6640 
6641   Result += "};\n";
6642 
6643   // Add static function to initialize the class pointer in the category structure.
6644   Result += "static void OBJC_CATEGORY_SETUP_$_";
6645   Result += ClassDecl->getNameAsString();
6646   Result += "_$_";
6647   Result += CatName;
6648   Result += "(void ) {\n";
6649   Result += "\t_OBJC_$_CATEGORY_";
6650   Result += ClassDecl->getNameAsString();
6651   Result += "_$_";
6652   Result += CatName;
6653   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6654   Result += ";\n}\n";
6655 }
6656 
6657 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6658                                            ASTContext *Context, std::string &Result,
6659                                            ArrayRef<ObjCMethodDecl *> Methods,
6660                                            StringRef VarName,
6661                                            StringRef ProtocolName) {
6662   if (Methods.size() == 0)
6663     return;
6664 
6665   Result += "\nstatic const char *";
6666   Result += VarName; Result += ProtocolName;
6667   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6668   Result += "{\n";
6669   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6670     ObjCMethodDecl *MD = Methods[i];
6671     std::string MethodTypeString =
6672       Context->getObjCEncodingForMethodDecl(MD, true);
6673     std::string QuoteMethodTypeString;
6674     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6675     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6676     if (i == e-1)
6677       Result += "\n};\n";
6678     else {
6679       Result += ",\n";
6680     }
6681   }
6682 }
6683 
6684 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6685                                 ASTContext *Context,
6686                                 std::string &Result,
6687                                 ArrayRef<ObjCIvarDecl *> Ivars,
6688                                 ObjCInterfaceDecl *CDecl) {
6689   // FIXME. visibility of offset symbols may have to be set; for Darwin
6690   // this is what happens:
6691   /**
6692    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6693        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6694        Class->getVisibility() == HiddenVisibility)
6695      Visibility should be: HiddenVisibility;
6696    else
6697      Visibility should be: DefaultVisibility;
6698   */
6699 
6700   Result += "\n";
6701   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6702     ObjCIvarDecl *IvarDecl = Ivars[i];
6703     if (Context->getLangOpts().MicrosoftExt)
6704       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6705 
6706     if (!Context->getLangOpts().MicrosoftExt ||
6707         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6708         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6709       Result += "extern \"C\" unsigned long int ";
6710     else
6711       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6712     if (Ivars[i]->isBitField())
6713       RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6714     else
6715       WriteInternalIvarName(CDecl, IvarDecl, Result);
6716     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6717     Result += " = ";
6718     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6719     Result += ";\n";
6720     if (Ivars[i]->isBitField()) {
6721       // skip over rest of the ivar bitfields.
6722       SKIP_BITFIELDS(i , e, Ivars);
6723     }
6724   }
6725 }
6726 
6727 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6728                                            ASTContext *Context, std::string &Result,
6729                                            ArrayRef<ObjCIvarDecl *> OriginalIvars,
6730                                            StringRef VarName,
6731                                            ObjCInterfaceDecl *CDecl) {
6732   if (OriginalIvars.size() > 0) {
6733     Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6734     SmallVector<ObjCIvarDecl *, 8> Ivars;
6735     // strip off all but the first ivar bitfield from each group of ivars.
6736     // Such ivars in the ivar list table will be replaced by their grouping struct
6737     // 'ivar'.
6738     for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6739       if (OriginalIvars[i]->isBitField()) {
6740         Ivars.push_back(OriginalIvars[i]);
6741         // skip over rest of the ivar bitfields.
6742         SKIP_BITFIELDS(i , e, OriginalIvars);
6743       }
6744       else
6745         Ivars.push_back(OriginalIvars[i]);
6746     }
6747 
6748     Result += "\nstatic ";
6749     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6750     Result += " "; Result += VarName;
6751     Result += CDecl->getNameAsString();
6752     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6753     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6754     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6755     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6756       ObjCIvarDecl *IvarDecl = Ivars[i];
6757       if (i == 0)
6758         Result += "\t{{";
6759       else
6760         Result += "\t {";
6761       Result += "(unsigned long int *)&";
6762       if (Ivars[i]->isBitField())
6763         RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6764       else
6765         WriteInternalIvarName(CDecl, IvarDecl, Result);
6766       Result += ", ";
6767 
6768       Result += "\"";
6769       if (Ivars[i]->isBitField())
6770         RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6771       else
6772         Result += IvarDecl->getName();
6773       Result += "\", ";
6774 
6775       QualType IVQT = IvarDecl->getType();
6776       if (IvarDecl->isBitField())
6777         IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6778 
6779       std::string IvarTypeString, QuoteIvarTypeString;
6780       Context->getObjCEncodingForType(IVQT, IvarTypeString,
6781                                       IvarDecl);
6782       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6783       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6784 
6785       // FIXME. this alignment represents the host alignment and need be changed to
6786       // represent the target alignment.
6787       unsigned Align = Context->getTypeAlign(IVQT)/8;
6788       Align = llvm::Log2_32(Align);
6789       Result += llvm::utostr(Align); Result += ", ";
6790       CharUnits Size = Context->getTypeSizeInChars(IVQT);
6791       Result += llvm::utostr(Size.getQuantity());
6792       if (i  == e-1)
6793         Result += "}}\n";
6794       else
6795         Result += "},\n";
6796     }
6797     Result += "};\n";
6798   }
6799 }
6800 
6801 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6802 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6803                                                     std::string &Result) {
6804 
6805   // Do not synthesize the protocol more than once.
6806   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6807     return;
6808   WriteModernMetadataDeclarations(Context, Result);
6809 
6810   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6811     PDecl = Def;
6812   // Must write out all protocol definitions in current qualifier list,
6813   // and in their nested qualifiers before writing out current definition.
6814   for (auto *I : PDecl->protocols())
6815     RewriteObjCProtocolMetaData(I, Result);
6816 
6817   // Construct method lists.
6818   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6819   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6820   for (auto *MD : PDecl->instance_methods()) {
6821     if (MD->getImplementationControl() == ObjCImplementationControl::Optional) {
6822       OptInstanceMethods.push_back(MD);
6823     } else {
6824       InstanceMethods.push_back(MD);
6825     }
6826   }
6827 
6828   for (auto *MD : PDecl->class_methods()) {
6829     if (MD->getImplementationControl() == ObjCImplementationControl::Optional) {
6830       OptClassMethods.push_back(MD);
6831     } else {
6832       ClassMethods.push_back(MD);
6833     }
6834   }
6835   std::vector<ObjCMethodDecl *> AllMethods;
6836   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6837     AllMethods.push_back(InstanceMethods[i]);
6838   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6839     AllMethods.push_back(ClassMethods[i]);
6840   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6841     AllMethods.push_back(OptInstanceMethods[i]);
6842   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6843     AllMethods.push_back(OptClassMethods[i]);
6844 
6845   Write__extendedMethodTypes_initializer(*this, Context, Result,
6846                                          AllMethods,
6847                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
6848                                          PDecl->getNameAsString());
6849   // Protocol's super protocol list
6850   SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6851   Write_protocol_list_initializer(Context, Result, SuperProtocols,
6852                                   "_OBJC_PROTOCOL_REFS_",
6853                                   PDecl->getNameAsString());
6854 
6855   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6856                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6857                                   PDecl->getNameAsString(), false);
6858 
6859   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6860                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
6861                                   PDecl->getNameAsString(), false);
6862 
6863   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6864                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6865                                   PDecl->getNameAsString(), false);
6866 
6867   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6868                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6869                                   PDecl->getNameAsString(), false);
6870 
6871   // Protocol's property metadata.
6872   SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6873       PDecl->instance_properties());
6874   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6875                                  /* Container */nullptr,
6876                                  "_OBJC_PROTOCOL_PROPERTIES_",
6877                                  PDecl->getNameAsString());
6878 
6879   // Writer out root metadata for current protocol: struct _protocol_t
6880   Result += "\n";
6881   if (LangOpts.MicrosoftExt)
6882     Result += "static ";
6883   Result += "struct _protocol_t _OBJC_PROTOCOL_";
6884   Result += PDecl->getNameAsString();
6885   Result += " __attribute__ ((used)) = {\n";
6886   Result += "\t0,\n"; // id is; is null
6887   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6888   if (SuperProtocols.size() > 0) {
6889     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6890     Result += PDecl->getNameAsString(); Result += ",\n";
6891   }
6892   else
6893     Result += "\t0,\n";
6894   if (InstanceMethods.size() > 0) {
6895     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6896     Result += PDecl->getNameAsString(); Result += ",\n";
6897   }
6898   else
6899     Result += "\t0,\n";
6900 
6901   if (ClassMethods.size() > 0) {
6902     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6903     Result += PDecl->getNameAsString(); Result += ",\n";
6904   }
6905   else
6906     Result += "\t0,\n";
6907 
6908   if (OptInstanceMethods.size() > 0) {
6909     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6910     Result += PDecl->getNameAsString(); Result += ",\n";
6911   }
6912   else
6913     Result += "\t0,\n";
6914 
6915   if (OptClassMethods.size() > 0) {
6916     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6917     Result += PDecl->getNameAsString(); Result += ",\n";
6918   }
6919   else
6920     Result += "\t0,\n";
6921 
6922   if (ProtocolProperties.size() > 0) {
6923     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6924     Result += PDecl->getNameAsString(); Result += ",\n";
6925   }
6926   else
6927     Result += "\t0,\n";
6928 
6929   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6930   Result += "\t0,\n";
6931 
6932   if (AllMethods.size() > 0) {
6933     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6934     Result += PDecl->getNameAsString();
6935     Result += "\n};\n";
6936   }
6937   else
6938     Result += "\t0\n};\n";
6939 
6940   if (LangOpts.MicrosoftExt)
6941     Result += "static ";
6942   Result += "struct _protocol_t *";
6943   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6944   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6945   Result += ";\n";
6946 
6947   // Mark this protocol as having been generated.
6948   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6949     llvm_unreachable("protocol already synthesized");
6950 }
6951 
6952 /// hasObjCExceptionAttribute - Return true if this class or any super
6953 /// class has the __objc_exception__ attribute.
6954 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6955 static bool hasObjCExceptionAttribute(ASTContext &Context,
6956                                       const ObjCInterfaceDecl *OID) {
6957   if (OID->hasAttr<ObjCExceptionAttr>())
6958     return true;
6959   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6960     return hasObjCExceptionAttribute(Context, Super);
6961   return false;
6962 }
6963 
6964 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6965                                            std::string &Result) {
6966   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6967 
6968   // Explicitly declared @interface's are already synthesized.
6969   if (CDecl->isImplicitInterfaceDecl())
6970     assert(false &&
6971            "Legacy implicit interface rewriting not supported in moder abi");
6972 
6973   WriteModernMetadataDeclarations(Context, Result);
6974   SmallVector<ObjCIvarDecl *, 8> IVars;
6975 
6976   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6977       IVD; IVD = IVD->getNextIvar()) {
6978     // Ignore unnamed bit-fields.
6979     if (!IVD->getDeclName())
6980       continue;
6981     IVars.push_back(IVD);
6982   }
6983 
6984   Write__ivar_list_t_initializer(*this, Context, Result, IVars,
6985                                  "_OBJC_$_INSTANCE_VARIABLES_",
6986                                  CDecl);
6987 
6988   // Build _objc_method_list for class's instance methods if needed
6989   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
6990 
6991   // If any of our property implementations have associated getters or
6992   // setters, produce metadata for them as well.
6993   for (const auto *Prop : IDecl->property_impls()) {
6994     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6995       continue;
6996     if (!Prop->getPropertyIvarDecl())
6997       continue;
6998     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
6999     if (!PD)
7000       continue;
7001     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7002       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7003         InstanceMethods.push_back(Getter);
7004     if (PD->isReadOnly())
7005       continue;
7006     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7007       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7008         InstanceMethods.push_back(Setter);
7009   }
7010 
7011   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7012                                   "_OBJC_$_INSTANCE_METHODS_",
7013                                   IDecl->getNameAsString(), true);
7014 
7015   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7016 
7017   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7018                                   "_OBJC_$_CLASS_METHODS_",
7019                                   IDecl->getNameAsString(), true);
7020 
7021   // Protocols referenced in class declaration?
7022   // Protocol's super protocol list
7023   std::vector<ObjCProtocolDecl *> RefedProtocols;
7024   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7025   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7026        E = Protocols.end();
7027        I != E; ++I) {
7028     RefedProtocols.push_back(*I);
7029     // Must write out all protocol definitions in current qualifier list,
7030     // and in their nested qualifiers before writing out current definition.
7031     RewriteObjCProtocolMetaData(*I, Result);
7032   }
7033 
7034   Write_protocol_list_initializer(Context, Result,
7035                                   RefedProtocols,
7036                                   "_OBJC_CLASS_PROTOCOLS_$_",
7037                                   IDecl->getNameAsString());
7038 
7039   // Protocol's property metadata.
7040   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7041       CDecl->instance_properties());
7042   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7043                                  /* Container */IDecl,
7044                                  "_OBJC_$_PROP_LIST_",
7045                                  CDecl->getNameAsString());
7046 
7047   // Data for initializing _class_ro_t  metaclass meta-data
7048   uint32_t flags = CLS_META;
7049   std::string InstanceSize;
7050   std::string InstanceStart;
7051 
7052   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7053   if (classIsHidden)
7054     flags |= OBJC2_CLS_HIDDEN;
7055 
7056   if (!CDecl->getSuperClass())
7057     // class is root
7058     flags |= CLS_ROOT;
7059   InstanceSize = "sizeof(struct _class_t)";
7060   InstanceStart = InstanceSize;
7061   Write__class_ro_t_initializer(Context, Result, flags,
7062                                 InstanceStart, InstanceSize,
7063                                 ClassMethods,
7064                                 nullptr,
7065                                 nullptr,
7066                                 nullptr,
7067                                 "_OBJC_METACLASS_RO_$_",
7068                                 CDecl->getNameAsString());
7069 
7070   // Data for initializing _class_ro_t meta-data
7071   flags = CLS;
7072   if (classIsHidden)
7073     flags |= OBJC2_CLS_HIDDEN;
7074 
7075   if (hasObjCExceptionAttribute(*Context, CDecl))
7076     flags |= CLS_EXCEPTION;
7077 
7078   if (!CDecl->getSuperClass())
7079     // class is root
7080     flags |= CLS_ROOT;
7081 
7082   InstanceSize.clear();
7083   InstanceStart.clear();
7084   if (!ObjCSynthesizedStructs.count(CDecl)) {
7085     InstanceSize = "0";
7086     InstanceStart = "0";
7087   }
7088   else {
7089     InstanceSize = "sizeof(struct ";
7090     InstanceSize += CDecl->getNameAsString();
7091     InstanceSize += "_IMPL)";
7092 
7093     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7094     if (IVD) {
7095       RewriteIvarOffsetComputation(IVD, InstanceStart);
7096     }
7097     else
7098       InstanceStart = InstanceSize;
7099   }
7100   Write__class_ro_t_initializer(Context, Result, flags,
7101                                 InstanceStart, InstanceSize,
7102                                 InstanceMethods,
7103                                 RefedProtocols,
7104                                 IVars,
7105                                 ClassProperties,
7106                                 "_OBJC_CLASS_RO_$_",
7107                                 CDecl->getNameAsString());
7108 
7109   Write_class_t(Context, Result,
7110                 "OBJC_METACLASS_$_",
7111                 CDecl, /*metaclass*/true);
7112 
7113   Write_class_t(Context, Result,
7114                 "OBJC_CLASS_$_",
7115                 CDecl, /*metaclass*/false);
7116 
7117   if (ImplementationIsNonLazy(IDecl))
7118     DefinedNonLazyClasses.push_back(CDecl);
7119 }
7120 
7121 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7122   int ClsDefCount = ClassImplementation.size();
7123   if (!ClsDefCount)
7124     return;
7125   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7126   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7127   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7128   for (int i = 0; i < ClsDefCount; i++) {
7129     ObjCImplementationDecl *IDecl = ClassImplementation[i];
7130     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7131     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7132     Result  += CDecl->getName(); Result += ",\n";
7133   }
7134   Result += "};\n";
7135 }
7136 
7137 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7138   int ClsDefCount = ClassImplementation.size();
7139   int CatDefCount = CategoryImplementation.size();
7140 
7141   // For each implemented class, write out all its meta data.
7142   for (int i = 0; i < ClsDefCount; i++)
7143     RewriteObjCClassMetaData(ClassImplementation[i], Result);
7144 
7145   RewriteClassSetupInitHook(Result);
7146 
7147   // For each implemented category, write out all its meta data.
7148   for (int i = 0; i < CatDefCount; i++)
7149     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7150 
7151   RewriteCategorySetupInitHook(Result);
7152 
7153   if (ClsDefCount > 0) {
7154     if (LangOpts.MicrosoftExt)
7155       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7156     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7157     Result += llvm::utostr(ClsDefCount); Result += "]";
7158     Result +=
7159       " __attribute__((used, section (\"__DATA, __objc_classlist,"
7160       "regular,no_dead_strip\")))= {\n";
7161     for (int i = 0; i < ClsDefCount; i++) {
7162       Result += "\t&OBJC_CLASS_$_";
7163       Result += ClassImplementation[i]->getNameAsString();
7164       Result += ",\n";
7165     }
7166     Result += "};\n";
7167 
7168     if (!DefinedNonLazyClasses.empty()) {
7169       if (LangOpts.MicrosoftExt)
7170         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7171       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7172       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7173         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7174         Result += ",\n";
7175       }
7176       Result += "};\n";
7177     }
7178   }
7179 
7180   if (CatDefCount > 0) {
7181     if (LangOpts.MicrosoftExt)
7182       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7183     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7184     Result += llvm::utostr(CatDefCount); Result += "]";
7185     Result +=
7186     " __attribute__((used, section (\"__DATA, __objc_catlist,"
7187     "regular,no_dead_strip\")))= {\n";
7188     for (int i = 0; i < CatDefCount; i++) {
7189       Result += "\t&_OBJC_$_CATEGORY_";
7190       Result +=
7191         CategoryImplementation[i]->getClassInterface()->getNameAsString();
7192       Result += "_$_";
7193       Result += CategoryImplementation[i]->getNameAsString();
7194       Result += ",\n";
7195     }
7196     Result += "};\n";
7197   }
7198 
7199   if (!DefinedNonLazyCategories.empty()) {
7200     if (LangOpts.MicrosoftExt)
7201       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7202     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7203     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7204       Result += "\t&_OBJC_$_CATEGORY_";
7205       Result +=
7206         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7207       Result += "_$_";
7208       Result += DefinedNonLazyCategories[i]->getNameAsString();
7209       Result += ",\n";
7210     }
7211     Result += "};\n";
7212   }
7213 }
7214 
7215 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7216   if (LangOpts.MicrosoftExt)
7217     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7218 
7219   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7220   // version 0, ObjCABI is 2
7221   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7222 }
7223 
7224 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7225 /// implementation.
7226 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7227                                               std::string &Result) {
7228   WriteModernMetadataDeclarations(Context, Result);
7229   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7230   // Find category declaration for this implementation.
7231   ObjCCategoryDecl *CDecl
7232     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7233 
7234   std::string FullCategoryName = ClassDecl->getNameAsString();
7235   FullCategoryName += "_$_";
7236   FullCategoryName += CDecl->getNameAsString();
7237 
7238   // Build _objc_method_list for class's instance methods if needed
7239   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7240 
7241   // If any of our property implementations have associated getters or
7242   // setters, produce metadata for them as well.
7243   for (const auto *Prop : IDecl->property_impls()) {
7244     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7245       continue;
7246     if (!Prop->getPropertyIvarDecl())
7247       continue;
7248     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7249     if (!PD)
7250       continue;
7251     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7252       InstanceMethods.push_back(Getter);
7253     if (PD->isReadOnly())
7254       continue;
7255     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7256       InstanceMethods.push_back(Setter);
7257   }
7258 
7259   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7260                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7261                                   FullCategoryName, true);
7262 
7263   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7264 
7265   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7266                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
7267                                   FullCategoryName, true);
7268 
7269   // Protocols referenced in class declaration?
7270   // Protocol's super protocol list
7271   SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7272   for (auto *I : CDecl->protocols())
7273     // Must write out all protocol definitions in current qualifier list,
7274     // and in their nested qualifiers before writing out current definition.
7275     RewriteObjCProtocolMetaData(I, Result);
7276 
7277   Write_protocol_list_initializer(Context, Result,
7278                                   RefedProtocols,
7279                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
7280                                   FullCategoryName);
7281 
7282   // Protocol's property metadata.
7283   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7284       CDecl->instance_properties());
7285   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7286                                 /* Container */IDecl,
7287                                 "_OBJC_$_PROP_LIST_",
7288                                 FullCategoryName);
7289 
7290   Write_category_t(*this, Context, Result,
7291                    CDecl,
7292                    ClassDecl,
7293                    InstanceMethods,
7294                    ClassMethods,
7295                    RefedProtocols,
7296                    ClassProperties);
7297 
7298   // Determine if this category is also "non-lazy".
7299   if (ImplementationIsNonLazy(IDecl))
7300     DefinedNonLazyCategories.push_back(CDecl);
7301 }
7302 
7303 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7304   int CatDefCount = CategoryImplementation.size();
7305   if (!CatDefCount)
7306     return;
7307   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7308   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7309   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7310   for (int i = 0; i < CatDefCount; i++) {
7311     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7312     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7313     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7314     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7315     Result += ClassDecl->getName();
7316     Result += "_$_";
7317     Result += CatDecl->getName();
7318     Result += ",\n";
7319   }
7320   Result += "};\n";
7321 }
7322 
7323 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7324 /// class methods.
7325 template<typename MethodIterator>
7326 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7327                                              MethodIterator MethodEnd,
7328                                              bool IsInstanceMethod,
7329                                              StringRef prefix,
7330                                              StringRef ClassName,
7331                                              std::string &Result) {
7332   if (MethodBegin == MethodEnd) return;
7333 
7334   if (!objc_impl_method) {
7335     /* struct _objc_method {
7336      SEL _cmd;
7337      char *method_types;
7338      void *_imp;
7339      }
7340      */
7341     Result += "\nstruct _objc_method {\n";
7342     Result += "\tSEL _cmd;\n";
7343     Result += "\tchar *method_types;\n";
7344     Result += "\tvoid *_imp;\n";
7345     Result += "};\n";
7346 
7347     objc_impl_method = true;
7348   }
7349 
7350   // Build _objc_method_list for class's methods if needed
7351 
7352   /* struct  {
7353    struct _objc_method_list *next_method;
7354    int method_count;
7355    struct _objc_method method_list[];
7356    }
7357    */
7358   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7359   Result += "\n";
7360   if (LangOpts.MicrosoftExt) {
7361     if (IsInstanceMethod)
7362       Result += "__declspec(allocate(\".inst_meth$B\")) ";
7363     else
7364       Result += "__declspec(allocate(\".cls_meth$B\")) ";
7365   }
7366   Result += "static struct {\n";
7367   Result += "\tstruct _objc_method_list *next_method;\n";
7368   Result += "\tint method_count;\n";
7369   Result += "\tstruct _objc_method method_list[";
7370   Result += utostr(NumMethods);
7371   Result += "];\n} _OBJC_";
7372   Result += prefix;
7373   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7374   Result += "_METHODS_";
7375   Result += ClassName;
7376   Result += " __attribute__ ((used, section (\"__OBJC, __";
7377   Result += IsInstanceMethod ? "inst" : "cls";
7378   Result += "_meth\")))= ";
7379   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7380 
7381   Result += "\t,{{(SEL)\"";
7382   Result += (*MethodBegin)->getSelector().getAsString().c_str();
7383   std::string MethodTypeString;
7384   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7385   Result += "\", \"";
7386   Result += MethodTypeString;
7387   Result += "\", (void *)";
7388   Result += MethodInternalNames[*MethodBegin];
7389   Result += "}\n";
7390   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7391     Result += "\t  ,{(SEL)\"";
7392     Result += (*MethodBegin)->getSelector().getAsString().c_str();
7393     std::string MethodTypeString;
7394     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7395     Result += "\", \"";
7396     Result += MethodTypeString;
7397     Result += "\", (void *)";
7398     Result += MethodInternalNames[*MethodBegin];
7399     Result += "}\n";
7400   }
7401   Result += "\t }\n};\n";
7402 }
7403 
7404 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7405   SourceRange OldRange = IV->getSourceRange();
7406   Expr *BaseExpr = IV->getBase();
7407 
7408   // Rewrite the base, but without actually doing replaces.
7409   {
7410     DisableReplaceStmtScope S(*this);
7411     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7412     IV->setBase(BaseExpr);
7413   }
7414 
7415   ObjCIvarDecl *D = IV->getDecl();
7416 
7417   Expr *Replacement = IV;
7418 
7419     if (BaseExpr->getType()->isObjCObjectPointerType()) {
7420       const ObjCInterfaceType *iFaceDecl =
7421         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7422       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7423       // lookup which class implements the instance variable.
7424       ObjCInterfaceDecl *clsDeclared = nullptr;
7425       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7426                                                    clsDeclared);
7427       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7428 
7429       // Build name of symbol holding ivar offset.
7430       std::string IvarOffsetName;
7431       if (D->isBitField())
7432         ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7433       else
7434         WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7435 
7436       ReferencedIvars[clsDeclared].insert(D);
7437 
7438       // cast offset to "char *".
7439       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7440                                                     Context->getPointerType(Context->CharTy),
7441                                                     CK_BitCast,
7442                                                     BaseExpr);
7443       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7444                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
7445                                        Context->UnsignedLongTy, nullptr,
7446                                        SC_Extern);
7447       DeclRefExpr *DRE = new (Context)
7448           DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7449                       VK_LValue, SourceLocation());
7450       BinaryOperator *addExpr = BinaryOperator::Create(
7451           *Context, castExpr, DRE, BO_Add,
7452           Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary,
7453           SourceLocation(), FPOptionsOverride());
7454       // Don't forget the parens to enforce the proper binding.
7455       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7456                                               SourceLocation(),
7457                                               addExpr);
7458       QualType IvarT = D->getType();
7459       if (D->isBitField())
7460         IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7461 
7462       if (!IvarT->getAs<TypedefType>() && IvarT->isRecordType()) {
7463         RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
7464         RD = RD->getDefinition();
7465         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7466           // decltype(((Foo_IMPL*)0)->bar) *
7467           auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
7468           // ivar in class extensions requires special treatment.
7469           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7470             CDecl = CatDecl->getClassInterface();
7471           std::string RecName = std::string(CDecl->getName());
7472           RecName += "_IMPL";
7473           RecordDecl *RD = RecordDecl::Create(
7474               *Context, TagTypeKind::Struct, TUDecl, SourceLocation(),
7475               SourceLocation(), &Context->Idents.get(RecName));
7476           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7477           unsigned UnsignedIntSize =
7478             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7479           Expr *Zero = IntegerLiteral::Create(*Context,
7480                                               llvm::APInt(UnsignedIntSize, 0),
7481                                               Context->UnsignedIntTy, SourceLocation());
7482           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7483           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7484                                                   Zero);
7485           FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7486                                             SourceLocation(),
7487                                             &Context->Idents.get(D->getNameAsString()),
7488                                             IvarT, nullptr,
7489                                             /*BitWidth=*/nullptr,
7490                                             /*Mutable=*/true, ICIS_NoInit);
7491           MemberExpr *ME = MemberExpr::CreateImplicit(
7492               *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
7493           IvarT = Context->getDecltypeType(ME, ME->getType());
7494         }
7495       }
7496       convertObjCTypeToCStyleType(IvarT);
7497       QualType castT = Context->getPointerType(IvarT);
7498 
7499       castExpr = NoTypeInfoCStyleCastExpr(Context,
7500                                           castT,
7501                                           CK_BitCast,
7502                                           PE);
7503 
7504       Expr *Exp = UnaryOperator::Create(
7505           const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
7506           VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
7507       PE = new (Context) ParenExpr(OldRange.getBegin(),
7508                                    OldRange.getEnd(),
7509                                    Exp);
7510 
7511       if (D->isBitField()) {
7512         FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7513                                           SourceLocation(),
7514                                           &Context->Idents.get(D->getNameAsString()),
7515                                           D->getType(), nullptr,
7516                                           /*BitWidth=*/D->getBitWidth(),
7517                                           /*Mutable=*/true, ICIS_NoInit);
7518         MemberExpr *ME =
7519             MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7520                                        FD->getType(), VK_LValue, OK_Ordinary);
7521         Replacement = ME;
7522 
7523       }
7524       else
7525         Replacement = PE;
7526     }
7527 
7528     ReplaceStmtWithRange(IV, Replacement, OldRange);
7529     return Replacement;
7530 }
7531 
7532 #endif // CLANG_ENABLE_OBJC_REWRITER
7533