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