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