1 //===--- RewriteObjC.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/Config/config.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Rewrite/Core/Rewriter.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <memory>
31 
32 #if CLANG_ENABLE_OBJC_REWRITER
33 
34 using namespace clang;
35 using llvm::utostr;
36 
37 namespace {
38   class RewriteObjC : public ASTConsumer {
39   protected:
40     enum {
41       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
42                                         block, ... */
43       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
44       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
45                                         __block variable */
46       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
47                                         helpers */
48       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
49                                         support routines */
50       BLOCK_BYREF_CURRENT_MAX = 256
51     };
52 
53     enum {
54       BLOCK_NEEDS_FREE =        (1 << 24),
55       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
56       BLOCK_HAS_CXX_OBJ =       (1 << 26),
57       BLOCK_IS_GC =             (1 << 27),
58       BLOCK_IS_GLOBAL =         (1 << 28),
59       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
60     };
61     static const int OBJC_ABI_VERSION = 7;
62 
63     Rewriter Rewrite;
64     DiagnosticsEngine &Diags;
65     const LangOptions &LangOpts;
66     ASTContext *Context;
67     SourceManager *SM;
68     TranslationUnitDecl *TUDecl;
69     FileID MainFileID;
70     const char *MainFileStart, *MainFileEnd;
71     Stmt *CurrentBody;
72     ParentMap *PropParentMap; // created lazily.
73     std::string InFileName;
74     std::unique_ptr<raw_ostream> OutFile;
75     std::string Preamble;
76 
77     TypeDecl *ProtocolTypeDecl;
78     VarDecl *GlobalVarDecl;
79     unsigned RewriteFailedDiag;
80     // ObjC string constant support.
81     unsigned NumObjCStringLiterals;
82     VarDecl *ConstantStringClassReference;
83     RecordDecl *NSStringRecord;
84 
85     // ObjC foreach break/continue generation support.
86     int BcLabelCount;
87 
88     unsigned TryFinallyContainsReturnDiag;
89     // Needed for super.
90     ObjCMethodDecl *CurMethodDef;
91     RecordDecl *SuperStructDecl;
92     RecordDecl *ConstantStringDecl;
93 
94     FunctionDecl *MsgSendFunctionDecl;
95     FunctionDecl *MsgSendSuperFunctionDecl;
96     FunctionDecl *MsgSendStretFunctionDecl;
97     FunctionDecl *MsgSendSuperStretFunctionDecl;
98     FunctionDecl *MsgSendFpretFunctionDecl;
99     FunctionDecl *GetClassFunctionDecl;
100     FunctionDecl *GetMetaClassFunctionDecl;
101     FunctionDecl *GetSuperClassFunctionDecl;
102     FunctionDecl *SelGetUidFunctionDecl;
103     FunctionDecl *CFStringFunctionDecl;
104     FunctionDecl *SuperConstructorFunctionDecl;
105     FunctionDecl *CurFunctionDef;
106     FunctionDecl *CurFunctionDeclToDeclareForBlock;
107 
108     /* Misc. containers needed for meta-data rewrite. */
109     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
113     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
114     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
115     SmallVector<Stmt *, 32> Stmts;
116     SmallVector<int, 8> ObjCBcLabelNo;
117     // Remember all the @protocol(<expr>) expressions.
118     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
119 
120     llvm::DenseSet<uint64_t> CopyDestroyCache;
121 
122     // Block expressions.
123     SmallVector<BlockExpr *, 32> Blocks;
124     SmallVector<int, 32> InnerDeclRefsCount;
125     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
126 
127     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
128 
129     // Block related declarations.
130     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132     SmallVector<ValueDecl *, 8> BlockByRefDecls;
133     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
134     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
135     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
137 
138     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
139 
140     // This maps an original source AST to it's rewritten form. This allows
141     // us to avoid rewriting the same node twice (which is very uncommon).
142     // This is needed to support some of the exotic property rewriting.
143     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
144 
145     // Needed for header files being rewritten
146     bool IsHeader;
147     bool SilenceRewriteMacroWarning;
148     bool objc_impl_method;
149 
150     bool DisableReplaceStmt;
151     class DisableReplaceStmtScope {
152       RewriteObjC &R;
153       bool SavedValue;
154 
155     public:
156       DisableReplaceStmtScope(RewriteObjC &R)
157         : R(R), SavedValue(R.DisableReplaceStmt) {
158         R.DisableReplaceStmt = true;
159       }
160 
161       ~DisableReplaceStmtScope() {
162         R.DisableReplaceStmt = SavedValue;
163       }
164     };
165 
166     void InitializeCommon(ASTContext &context);
167 
168   public:
169     // Top Level Driver code.
170     bool HandleTopLevelDecl(DeclGroupRef D) override {
171       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173           if (!Class->isThisDeclarationADefinition()) {
174             RewriteForwardClassDecl(D);
175             break;
176           }
177         }
178 
179         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180           if (!Proto->isThisDeclarationADefinition()) {
181             RewriteForwardProtocolDecl(D);
182             break;
183           }
184         }
185 
186         HandleTopLevelSingleDecl(*I);
187       }
188       return true;
189     }
190 
191     void HandleTopLevelSingleDecl(Decl *D);
192     void HandleDeclInMainFile(Decl *D);
193     RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
194                 DiagnosticsEngine &D, const LangOptions &LOpts,
195                 bool silenceMacroWarn);
196 
197     ~RewriteObjC() override {}
198 
199     void HandleTranslationUnit(ASTContext &C) override;
200 
201     void ReplaceStmt(Stmt *Old, Stmt *New) {
202       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
203     }
204 
205     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
206       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
207 
208       Stmt *ReplacingStmt = ReplacedNodes[Old];
209       if (ReplacingStmt)
210         return; // We can't rewrite the same node twice.
211 
212       if (DisableReplaceStmt)
213         return;
214 
215       // Measure the old text.
216       int Size = Rewrite.getRangeSize(SrcRange);
217       if (Size == -1) {
218         Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
219             << Old->getSourceRange();
220         return;
221       }
222       // Get the new text.
223       std::string SStr;
224       llvm::raw_string_ostream S(SStr);
225       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
226       const std::string &Str = S.str();
227 
228       // If replacement succeeded or warning disabled return with no warning.
229       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
230         ReplacedNodes[Old] = New;
231         return;
232       }
233       if (SilenceRewriteMacroWarning)
234         return;
235       Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
236           << Old->getSourceRange();
237     }
238 
239     void InsertText(SourceLocation Loc, StringRef Str,
240                     bool InsertAfter = true) {
241       // If insertion succeeded or warning disabled return with no warning.
242       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
243           SilenceRewriteMacroWarning)
244         return;
245 
246       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
247     }
248 
249     void ReplaceText(SourceLocation Start, unsigned OrigLength,
250                      StringRef Str) {
251       // If removal succeeded or warning disabled return with no warning.
252       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
253           SilenceRewriteMacroWarning)
254         return;
255 
256       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
257     }
258 
259     // Syntactic Rewriting.
260     void RewriteRecordBody(RecordDecl *RD);
261     void RewriteInclude();
262     void RewriteForwardClassDecl(DeclGroupRef D);
263     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
264     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
265                                      const std::string &typedefString);
266     void RewriteImplementations();
267     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
268                                  ObjCImplementationDecl *IMD,
269                                  ObjCCategoryImplDecl *CID);
270     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
271     void RewriteImplementationDecl(Decl *Dcl);
272     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
273                                ObjCMethodDecl *MDecl, std::string &ResultStr);
274     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
275                                const FunctionType *&FPRetType);
276     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
277                             ValueDecl *VD, bool def=false);
278     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
279     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
280     void RewriteForwardProtocolDecl(DeclGroupRef D);
281     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
282     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
283     void RewriteProperty(ObjCPropertyDecl *prop);
284     void RewriteFunctionDecl(FunctionDecl *FD);
285     void RewriteBlockPointerType(std::string& Str, QualType Type);
286     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
287     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
288     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
289     void RewriteTypeOfDecl(VarDecl *VD);
290     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
291 
292     // Expression Rewriting.
293     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
294     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
295     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
296     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
297     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
298     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
299     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
300     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
301     void RewriteTryReturnStmts(Stmt *S);
302     void RewriteSyncReturnStmts(Stmt *S, std::string buf);
303     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
304     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
305     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
306     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307                                        SourceLocation OrigEnd);
308     Stmt *RewriteBreakStmt(BreakStmt *S);
309     Stmt *RewriteContinueStmt(ContinueStmt *S);
310     void RewriteCastExpr(CStyleCastExpr *CE);
311 
312     // Block rewriting.
313     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
314 
315     // Block specific rewrite rules.
316     void RewriteBlockPointerDecl(NamedDecl *VD);
317     void RewriteByRefVar(VarDecl *VD);
318     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
319     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
320     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
321 
322     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
323                                       std::string &Result);
324 
325     void Initialize(ASTContext &context) override = 0;
326 
327     // Metadata Rewriting.
328     virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
329     virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
330                                                  StringRef prefix,
331                                                  StringRef ClassName,
332                                                  std::string &Result) = 0;
333     virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
334                                              std::string &Result) = 0;
335     virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336                                      StringRef prefix,
337                                      StringRef ClassName,
338                                      std::string &Result) = 0;
339     virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
340                                           std::string &Result) = 0;
341 
342     // Rewriting ivar access
343     virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
344     virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
345                                          std::string &Result) = 0;
346 
347     // Misc. AST transformation routines. Sometimes they end up calling
348     // rewriting routines on the new ASTs.
349     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
350                                            ArrayRef<Expr *> Args,
351                                            SourceLocation StartLoc=SourceLocation(),
352                                            SourceLocation EndLoc=SourceLocation());
353     CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
354                                         QualType msgSendType,
355                                         QualType returnType,
356                                         SmallVectorImpl<QualType> &ArgTypes,
357                                         SmallVectorImpl<Expr*> &MsgExprs,
358                                         ObjCMethodDecl *Method);
359     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360                            SourceLocation StartLoc=SourceLocation(),
361                            SourceLocation EndLoc=SourceLocation());
362 
363     void SynthCountByEnumWithState(std::string &buf);
364     void SynthMsgSendFunctionDecl();
365     void SynthMsgSendSuperFunctionDecl();
366     void SynthMsgSendStretFunctionDecl();
367     void SynthMsgSendFpretFunctionDecl();
368     void SynthMsgSendSuperStretFunctionDecl();
369     void SynthGetClassFunctionDecl();
370     void SynthGetMetaClassFunctionDecl();
371     void SynthGetSuperClassFunctionDecl();
372     void SynthSelGetUidFunctionDecl();
373     void SynthSuperConstructorFunctionDecl();
374 
375     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
376     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
377                                       StringRef funcName, std::string Tag);
378     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
379                                       StringRef funcName, std::string Tag);
380     std::string SynthesizeBlockImpl(BlockExpr *CE,
381                                     std::string Tag, std::string Desc);
382     std::string SynthesizeBlockDescriptor(std::string DescTag,
383                                           std::string ImplTag,
384                                           int i, StringRef funcName,
385                                           unsigned hasCopy);
386     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
387     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
388                                  StringRef FunName);
389     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391             const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
392 
393     // Misc. helper routines.
394     QualType getProtocolType();
395     void WarnAboutReturnGotoStmts(Stmt *S);
396     void HasReturnStmts(Stmt *S, bool &hasReturns);
397     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400 
401     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
402     void CollectBlockDeclRefInfo(BlockExpr *Exp);
403     void GetBlockDeclRefExprs(Stmt *S);
404     void GetInnerBlockDeclRefExprs(Stmt *S,
405                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
406                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
407 
408     // We avoid calling Type::isBlockPointerType(), since it operates on the
409     // canonical type. We only care if the top-level type is a closure pointer.
410     bool isTopLevelBlockPointerType(QualType T) {
411       return isa<BlockPointerType>(T);
412     }
413 
414     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415     /// to a function pointer type and upon success, returns true; false
416     /// otherwise.
417     bool convertBlockPointerToFunctionPointer(QualType &T) {
418       if (isTopLevelBlockPointerType(T)) {
419         const auto *BPT = T->castAs<BlockPointerType>();
420         T = Context->getPointerType(BPT->getPointeeType());
421         return true;
422       }
423       return false;
424     }
425 
426     bool needToScanForQualifiers(QualType T);
427     QualType getSuperStructType();
428     QualType getConstantStringStructType();
429     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431 
432     void convertToUnqualifiedObjCType(QualType &T) {
433       if (T->isObjCQualifiedIdType())
434         T = Context->getObjCIdType();
435       else if (T->isObjCQualifiedClassType())
436         T = Context->getObjCClassType();
437       else if (T->isObjCObjectPointerType() &&
438                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439         if (const ObjCObjectPointerType * OBJPT =
440               T->getAsObjCInterfacePointerType()) {
441           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442           T = QualType(IFaceT, 0);
443           T = Context->getPointerType(T);
444         }
445      }
446     }
447 
448     // FIXME: This predicate seems like it would be useful to add to ASTContext.
449     bool isObjCType(QualType T) {
450       if (!LangOpts.ObjC)
451         return false;
452 
453       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
454 
455       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456           OCT == Context->getCanonicalType(Context->getObjCClassType()))
457         return true;
458 
459       if (const PointerType *PT = OCT->getAs<PointerType>()) {
460         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
461             PT->getPointeeType()->isObjCQualifiedIdType())
462           return true;
463       }
464       return false;
465     }
466     bool PointerTypeTakesAnyBlockArguments(QualType QT);
467     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
468     void GetExtentOfArgList(const char *Name, const char *&LParen,
469                             const char *&RParen);
470 
471     void QuoteDoublequotes(std::string &From, std::string &To) {
472       for (unsigned i = 0; i < From.length(); i++) {
473         if (From[i] == '"')
474           To += "\\\"";
475         else
476           To += From[i];
477       }
478     }
479 
480     QualType getSimpleFunctionType(QualType result,
481                                    ArrayRef<QualType> args,
482                                    bool variadic = false) {
483       if (result == Context->getObjCInstanceType())
484         result =  Context->getObjCIdType();
485       FunctionProtoType::ExtProtoInfo fpi;
486       fpi.Variadic = variadic;
487       return Context->getFunctionType(result, args, fpi);
488     }
489 
490     // Helper function: create a CStyleCastExpr with trivial type source info.
491     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
492                                              CastKind Kind, Expr *E) {
493       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
494       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
495                                     TInfo, SourceLocation(), SourceLocation());
496     }
497 
498     StringLiteral *getStringLiteral(StringRef Str) {
499       QualType StrType = Context->getConstantArrayType(
500           Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
501           ArrayType::Normal, 0);
502       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
503                                    /*Pascal=*/false, StrType, SourceLocation());
504     }
505   };
506 
507   class RewriteObjCFragileABI : public RewriteObjC {
508   public:
509     RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
510                           DiagnosticsEngine &D, const LangOptions &LOpts,
511                           bool silenceMacroWarn)
512         : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
513 
514     ~RewriteObjCFragileABI() override {}
515     void Initialize(ASTContext &context) override;
516 
517     // Rewriting metadata
518     template<typename MethodIterator>
519     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
520                                     MethodIterator MethodEnd,
521                                     bool IsInstanceMethod,
522                                     StringRef prefix,
523                                     StringRef ClassName,
524                                     std::string &Result);
525     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
526                                      StringRef prefix, StringRef ClassName,
527                                      std::string &Result) override;
528     void RewriteObjCProtocolListMetaData(
529           const ObjCList<ObjCProtocolDecl> &Prots,
530           StringRef prefix, StringRef ClassName, std::string &Result) override;
531     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
532                                   std::string &Result) override;
533     void RewriteMetaDataIntoBuffer(std::string &Result) override;
534     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
535                                      std::string &Result) override;
536 
537     // Rewriting ivar
538     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
539                                       std::string &Result) override;
540     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
541   };
542 } // end anonymous namespace
543 
544 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
545                                                    NamedDecl *D) {
546   if (const FunctionProtoType *fproto
547       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
548     for (const auto &I : fproto->param_types())
549       if (isTopLevelBlockPointerType(I)) {
550         // All the args are checked/rewritten. Don't call twice!
551         RewriteBlockPointerDecl(D);
552         break;
553       }
554   }
555 }
556 
557 void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
558   const PointerType *PT = funcType->getAs<PointerType>();
559   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
560     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
561 }
562 
563 static bool IsHeaderFile(const std::string &Filename) {
564   std::string::size_type DotPos = Filename.rfind('.');
565 
566   if (DotPos == std::string::npos) {
567     // no file extension
568     return false;
569   }
570 
571   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
572   // C header: .h
573   // C++ header: .hh or .H;
574   return Ext == "h" || Ext == "hh" || Ext == "H";
575 }
576 
577 RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
578                          DiagnosticsEngine &D, const LangOptions &LOpts,
579                          bool silenceMacroWarn)
580     : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
581       SilenceRewriteMacroWarning(silenceMacroWarn) {
582   IsHeader = IsHeaderFile(inFile);
583   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
584                "rewriting sub-expression within a macro (may not be correct)");
585   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
586                DiagnosticsEngine::Warning,
587                "rewriter doesn't support user-specified control flow semantics "
588                "for @try/@finally (code may not execute properly)");
589 }
590 
591 std::unique_ptr<ASTConsumer>
592 clang::CreateObjCRewriter(const std::string &InFile,
593                           std::unique_ptr<raw_ostream> OS,
594                           DiagnosticsEngine &Diags, const LangOptions &LOpts,
595                           bool SilenceRewriteMacroWarning) {
596   return std::make_unique<RewriteObjCFragileABI>(
597       InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
598 }
599 
600 void RewriteObjC::InitializeCommon(ASTContext &context) {
601   Context = &context;
602   SM = &Context->getSourceManager();
603   TUDecl = Context->getTranslationUnitDecl();
604   MsgSendFunctionDecl = nullptr;
605   MsgSendSuperFunctionDecl = nullptr;
606   MsgSendStretFunctionDecl = nullptr;
607   MsgSendSuperStretFunctionDecl = nullptr;
608   MsgSendFpretFunctionDecl = nullptr;
609   GetClassFunctionDecl = nullptr;
610   GetMetaClassFunctionDecl = nullptr;
611   GetSuperClassFunctionDecl = nullptr;
612   SelGetUidFunctionDecl = nullptr;
613   CFStringFunctionDecl = nullptr;
614   ConstantStringClassReference = nullptr;
615   NSStringRecord = nullptr;
616   CurMethodDef = nullptr;
617   CurFunctionDef = nullptr;
618   CurFunctionDeclToDeclareForBlock = nullptr;
619   GlobalVarDecl = nullptr;
620   SuperStructDecl = nullptr;
621   ProtocolTypeDecl = nullptr;
622   ConstantStringDecl = nullptr;
623   BcLabelCount = 0;
624   SuperConstructorFunctionDecl = nullptr;
625   NumObjCStringLiterals = 0;
626   PropParentMap = nullptr;
627   CurrentBody = nullptr;
628   DisableReplaceStmt = false;
629   objc_impl_method = false;
630 
631   // Get the ID and start/end of the main file.
632   MainFileID = SM->getMainFileID();
633   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634   MainFileStart = MainBuf->getBufferStart();
635   MainFileEnd = MainBuf->getBufferEnd();
636 
637   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
638 }
639 
640 //===----------------------------------------------------------------------===//
641 // Top Level Driver Code
642 //===----------------------------------------------------------------------===//
643 
644 void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
645   if (Diags.hasErrorOccurred())
646     return;
647 
648   // Two cases: either the decl could be in the main file, or it could be in a
649   // #included file.  If the former, rewrite it now.  If the later, check to see
650   // if we rewrote the #include/#import.
651   SourceLocation Loc = D->getLocation();
652   Loc = SM->getExpansionLoc(Loc);
653 
654   // If this is for a builtin, ignore it.
655   if (Loc.isInvalid()) return;
656 
657   // Look for built-in declarations that we need to refer during the rewrite.
658   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
659     RewriteFunctionDecl(FD);
660   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
661     // declared in <Foundation/NSString.h>
662     if (FVD->getName() == "_NSConstantStringClassReference") {
663       ConstantStringClassReference = FVD;
664       return;
665     }
666   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667     if (ID->isThisDeclarationADefinition())
668       RewriteInterfaceDecl(ID);
669   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670     RewriteCategoryDecl(CD);
671   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672     if (PD->isThisDeclarationADefinition())
673       RewriteProtocolDecl(PD);
674   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675     // Recurse into linkage specifications
676     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677                                  DIEnd = LSD->decls_end();
678          DI != DIEnd; ) {
679       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680         if (!IFace->isThisDeclarationADefinition()) {
681           SmallVector<Decl *, 8> DG;
682           SourceLocation StartLoc = IFace->getBeginLoc();
683           do {
684             if (isa<ObjCInterfaceDecl>(*DI) &&
685                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686                 StartLoc == (*DI)->getBeginLoc())
687               DG.push_back(*DI);
688             else
689               break;
690 
691             ++DI;
692           } while (DI != DIEnd);
693           RewriteForwardClassDecl(DG);
694           continue;
695         }
696       }
697 
698       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699         if (!Proto->isThisDeclarationADefinition()) {
700           SmallVector<Decl *, 8> DG;
701           SourceLocation StartLoc = Proto->getBeginLoc();
702           do {
703             if (isa<ObjCProtocolDecl>(*DI) &&
704                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705                 StartLoc == (*DI)->getBeginLoc())
706               DG.push_back(*DI);
707             else
708               break;
709 
710             ++DI;
711           } while (DI != DIEnd);
712           RewriteForwardProtocolDecl(DG);
713           continue;
714         }
715       }
716 
717       HandleTopLevelSingleDecl(*DI);
718       ++DI;
719     }
720   }
721   // If we have a decl in the main file, see if we should rewrite it.
722   if (SM->isWrittenInMainFile(Loc))
723     return HandleDeclInMainFile(D);
724 }
725 
726 //===----------------------------------------------------------------------===//
727 // Syntactic (non-AST) Rewriting Code
728 //===----------------------------------------------------------------------===//
729 
730 void RewriteObjC::RewriteInclude() {
731   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732   StringRef MainBuf = SM->getBufferData(MainFileID);
733   const char *MainBufStart = MainBuf.begin();
734   const char *MainBufEnd = MainBuf.end();
735   size_t ImportLen = strlen("import");
736 
737   // Loop over the whole file, looking for includes.
738   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739     if (*BufPtr == '#') {
740       if (++BufPtr == MainBufEnd)
741         return;
742       while (*BufPtr == ' ' || *BufPtr == '\t')
743         if (++BufPtr == MainBufEnd)
744           return;
745       if (!strncmp(BufPtr, "import", ImportLen)) {
746         // replace import with include
747         SourceLocation ImportLoc =
748           LocStart.getLocWithOffset(BufPtr-MainBufStart);
749         ReplaceText(ImportLoc, ImportLen, "include");
750         BufPtr += ImportLen;
751       }
752     }
753   }
754 }
755 
756 static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757   const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
758   std::string S;
759   S = "((struct ";
760   S += ClassDecl->getIdentifier()->getName();
761   S += "_IMPL *)self)->";
762   S += OID->getName();
763   return S;
764 }
765 
766 void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767                                           ObjCImplementationDecl *IMD,
768                                           ObjCCategoryImplDecl *CID) {
769   static bool objcGetPropertyDefined = false;
770   static bool objcSetPropertyDefined = false;
771   SourceLocation startLoc = PID->getBeginLoc();
772   InsertText(startLoc, "// ");
773   const char *startBuf = SM->getCharacterData(startLoc);
774   assert((*startBuf == '@') && "bogus @synthesize location");
775   const char *semiBuf = strchr(startBuf, ';');
776   assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777   SourceLocation onePastSemiLoc =
778     startLoc.getLocWithOffset(semiBuf-startBuf+1);
779 
780   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781     return; // FIXME: is this correct?
782 
783   // Generate the 'getter' function.
784   ObjCPropertyDecl *PD = PID->getPropertyDecl();
785   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
786 
787   if (!OID)
788     return;
789 
790   unsigned Attributes = PD->getPropertyAttributes();
791   if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) {
792     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794                                          ObjCPropertyDecl::OBJC_PR_copy));
795     std::string Getr;
796     if (GenGetProperty && !objcGetPropertyDefined) {
797       objcGetPropertyDefined = true;
798       // FIXME. Is this attribute correct in all cases?
799       Getr = "\nextern \"C\" __declspec(dllimport) "
800             "id objc_getProperty(id, SEL, long, bool);\n";
801     }
802     RewriteObjCMethodDecl(OID->getContainingInterface(),
803                           PID->getGetterMethodDecl(), Getr);
804     Getr += "{ ";
805     // Synthesize an explicit cast to gain access to the ivar.
806     // See objc-act.c:objc_synthesize_new_getter() for details.
807     if (GenGetProperty) {
808       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809       Getr += "typedef ";
810       const FunctionType *FPRetType = nullptr;
811       RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
812                             FPRetType);
813       Getr += " _TYPE";
814       if (FPRetType) {
815         Getr += ")"; // close the precedence "scope" for "*".
816 
817         // Now, emit the argument types (if any).
818         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819           Getr += "(";
820           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
821             if (i) Getr += ", ";
822             std::string ParamStr =
823                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
824             Getr += ParamStr;
825           }
826           if (FT->isVariadic()) {
827             if (FT->getNumParams())
828               Getr += ", ";
829             Getr += "...";
830           }
831           Getr += ")";
832         } else
833           Getr += "()";
834       }
835       Getr += ";\n";
836       Getr += "return (_TYPE)";
837       Getr += "objc_getProperty(self, _cmd, ";
838       RewriteIvarOffsetComputation(OID, Getr);
839       Getr += ", 1)";
840     }
841     else
842       Getr += "return " + getIvarAccessString(OID);
843     Getr += "; }";
844     InsertText(onePastSemiLoc, Getr);
845   }
846 
847   if (PD->isReadOnly() || !PID->getSetterMethodDecl() ||
848       PID->getSetterMethodDecl()->isDefined())
849     return;
850 
851   // Generate the 'setter' function.
852   std::string Setr;
853   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
854                                       ObjCPropertyDecl::OBJC_PR_copy);
855   if (GenSetProperty && !objcSetPropertyDefined) {
856     objcSetPropertyDefined = true;
857     // FIXME. Is this attribute correct in all cases?
858     Setr = "\nextern \"C\" __declspec(dllimport) "
859     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
860   }
861 
862   RewriteObjCMethodDecl(OID->getContainingInterface(),
863                         PID->getSetterMethodDecl(), Setr);
864   Setr += "{ ";
865   // Synthesize an explicit cast to initialize the ivar.
866   // See objc-act.c:objc_synthesize_new_setter() for details.
867   if (GenSetProperty) {
868     Setr += "objc_setProperty (self, _cmd, ";
869     RewriteIvarOffsetComputation(OID, Setr);
870     Setr += ", (id)";
871     Setr += PD->getName();
872     Setr += ", ";
873     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
874       Setr += "0, ";
875     else
876       Setr += "1, ";
877     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
878       Setr += "1)";
879     else
880       Setr += "0)";
881   }
882   else {
883     Setr += getIvarAccessString(OID) + " = ";
884     Setr += PD->getName();
885   }
886   Setr += "; }";
887   InsertText(onePastSemiLoc, Setr);
888 }
889 
890 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
891                                        std::string &typedefString) {
892   typedefString += "#ifndef _REWRITER_typedef_";
893   typedefString += ForwardDecl->getNameAsString();
894   typedefString += "\n";
895   typedefString += "#define _REWRITER_typedef_";
896   typedefString += ForwardDecl->getNameAsString();
897   typedefString += "\n";
898   typedefString += "typedef struct objc_object ";
899   typedefString += ForwardDecl->getNameAsString();
900   typedefString += ";\n#endif\n";
901 }
902 
903 void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
904                                               const std::string &typedefString) {
905   SourceLocation startLoc = ClassDecl->getBeginLoc();
906   const char *startBuf = SM->getCharacterData(startLoc);
907   const char *semiPtr = strchr(startBuf, ';');
908   // Replace the @class with typedefs corresponding to the classes.
909   ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
910 }
911 
912 void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
913   std::string typedefString;
914   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
915     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
916     if (I == D.begin()) {
917       // Translate to typedef's that forward reference structs with the same name
918       // as the class. As a convenience, we include the original declaration
919       // as a comment.
920       typedefString += "// @class ";
921       typedefString += ForwardDecl->getNameAsString();
922       typedefString += ";\n";
923     }
924     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
925   }
926   DeclGroupRef::iterator I = D.begin();
927   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
928 }
929 
930 void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
931   std::string typedefString;
932   for (unsigned i = 0; i < D.size(); i++) {
933     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
934     if (i == 0) {
935       typedefString += "// @class ";
936       typedefString += ForwardDecl->getNameAsString();
937       typedefString += ";\n";
938     }
939     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940   }
941   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
942 }
943 
944 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
945   // When method is a synthesized one, such as a getter/setter there is
946   // nothing to rewrite.
947   if (Method->isImplicit())
948     return;
949   SourceLocation LocStart = Method->getBeginLoc();
950   SourceLocation LocEnd = Method->getEndLoc();
951 
952   if (SM->getExpansionLineNumber(LocEnd) >
953       SM->getExpansionLineNumber(LocStart)) {
954     InsertText(LocStart, "#if 0\n");
955     ReplaceText(LocEnd, 1, ";\n#endif\n");
956   } else {
957     InsertText(LocStart, "// ");
958   }
959 }
960 
961 void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
962   SourceLocation Loc = prop->getAtLoc();
963 
964   ReplaceText(Loc, 0, "// ");
965   // FIXME: handle properties that are declared across multiple lines.
966 }
967 
968 void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
969   SourceLocation LocStart = CatDecl->getBeginLoc();
970 
971   // FIXME: handle category headers that are declared across multiple lines.
972   ReplaceText(LocStart, 0, "// ");
973 
974   for (auto *I : CatDecl->instance_properties())
975     RewriteProperty(I);
976   for (auto *I : CatDecl->instance_methods())
977     RewriteMethodDeclaration(I);
978   for (auto *I : CatDecl->class_methods())
979     RewriteMethodDeclaration(I);
980 
981   // Lastly, comment out the @end.
982   ReplaceText(CatDecl->getAtEndRange().getBegin(),
983               strlen("@end"), "/* @end */");
984 }
985 
986 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
987   SourceLocation LocStart = PDecl->getBeginLoc();
988   assert(PDecl->isThisDeclarationADefinition());
989 
990   // FIXME: handle protocol headers that are declared across multiple lines.
991   ReplaceText(LocStart, 0, "// ");
992 
993   for (auto *I : PDecl->instance_methods())
994     RewriteMethodDeclaration(I);
995   for (auto *I : PDecl->class_methods())
996     RewriteMethodDeclaration(I);
997   for (auto *I : PDecl->instance_properties())
998     RewriteProperty(I);
999 
1000   // Lastly, comment out the @end.
1001   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1002   ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1003 
1004   // Must comment out @optional/@required
1005   const char *startBuf = SM->getCharacterData(LocStart);
1006   const char *endBuf = SM->getCharacterData(LocEnd);
1007   for (const char *p = startBuf; p < endBuf; p++) {
1008     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1009       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1010       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1011 
1012     }
1013     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1014       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1015       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1016 
1017     }
1018   }
1019 }
1020 
1021 void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1022   SourceLocation LocStart = (*D.begin())->getBeginLoc();
1023   if (LocStart.isInvalid())
1024     llvm_unreachable("Invalid SourceLocation");
1025   // FIXME: handle forward protocol that are declared across multiple lines.
1026   ReplaceText(LocStart, 0, "// ");
1027 }
1028 
1029 void
1030 RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1031   SourceLocation LocStart = DG[0]->getBeginLoc();
1032   if (LocStart.isInvalid())
1033     llvm_unreachable("Invalid SourceLocation");
1034   // FIXME: handle forward protocol that are declared across multiple lines.
1035   ReplaceText(LocStart, 0, "// ");
1036 }
1037 
1038 void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1039                                         const FunctionType *&FPRetType) {
1040   if (T->isObjCQualifiedIdType())
1041     ResultStr += "id";
1042   else if (T->isFunctionPointerType() ||
1043            T->isBlockPointerType()) {
1044     // needs special handling, since pointer-to-functions have special
1045     // syntax (where a decaration models use).
1046     QualType retType = T;
1047     QualType PointeeTy;
1048     if (const PointerType* PT = retType->getAs<PointerType>())
1049       PointeeTy = PT->getPointeeType();
1050     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1051       PointeeTy = BPT->getPointeeType();
1052     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1053       ResultStr +=
1054           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1055       ResultStr += "(*";
1056     }
1057   } else
1058     ResultStr += T.getAsString(Context->getPrintingPolicy());
1059 }
1060 
1061 void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1062                                         ObjCMethodDecl *OMD,
1063                                         std::string &ResultStr) {
1064   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1065   const FunctionType *FPRetType = nullptr;
1066   ResultStr += "\nstatic ";
1067   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1068   ResultStr += " ";
1069 
1070   // Unique method name
1071   std::string NameStr;
1072 
1073   if (OMD->isInstanceMethod())
1074     NameStr += "_I_";
1075   else
1076     NameStr += "_C_";
1077 
1078   NameStr += IDecl->getNameAsString();
1079   NameStr += "_";
1080 
1081   if (ObjCCategoryImplDecl *CID =
1082       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1083     NameStr += CID->getNameAsString();
1084     NameStr += "_";
1085   }
1086   // Append selector names, replacing ':' with '_'
1087   {
1088     std::string selString = OMD->getSelector().getAsString();
1089     int len = selString.size();
1090     for (int i = 0; i < len; i++)
1091       if (selString[i] == ':')
1092         selString[i] = '_';
1093     NameStr += selString;
1094   }
1095   // Remember this name for metadata emission
1096   MethodInternalNames[OMD] = NameStr;
1097   ResultStr += NameStr;
1098 
1099   // Rewrite arguments
1100   ResultStr += "(";
1101 
1102   // invisible arguments
1103   if (OMD->isInstanceMethod()) {
1104     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1105     selfTy = Context->getPointerType(selfTy);
1106     if (!LangOpts.MicrosoftExt) {
1107       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1108         ResultStr += "struct ";
1109     }
1110     // When rewriting for Microsoft, explicitly omit the structure name.
1111     ResultStr += IDecl->getNameAsString();
1112     ResultStr += " *";
1113   }
1114   else
1115     ResultStr += Context->getObjCClassType().getAsString(
1116       Context->getPrintingPolicy());
1117 
1118   ResultStr += " self, ";
1119   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1120   ResultStr += " _cmd";
1121 
1122   // Method arguments.
1123   for (const auto *PDecl : OMD->parameters()) {
1124     ResultStr += ", ";
1125     if (PDecl->getType()->isObjCQualifiedIdType()) {
1126       ResultStr += "id ";
1127       ResultStr += PDecl->getNameAsString();
1128     } else {
1129       std::string Name = PDecl->getNameAsString();
1130       QualType QT = PDecl->getType();
1131       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1132       (void)convertBlockPointerToFunctionPointer(QT);
1133       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1134       ResultStr += Name;
1135     }
1136   }
1137   if (OMD->isVariadic())
1138     ResultStr += ", ...";
1139   ResultStr += ") ";
1140 
1141   if (FPRetType) {
1142     ResultStr += ")"; // close the precedence "scope" for "*".
1143 
1144     // Now, emit the argument types (if any).
1145     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1146       ResultStr += "(";
1147       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1148         if (i) ResultStr += ", ";
1149         std::string ParamStr =
1150             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1151         ResultStr += ParamStr;
1152       }
1153       if (FT->isVariadic()) {
1154         if (FT->getNumParams())
1155           ResultStr += ", ";
1156         ResultStr += "...";
1157       }
1158       ResultStr += ")";
1159     } else {
1160       ResultStr += "()";
1161     }
1162   }
1163 }
1164 
1165 void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1166   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1167   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1168   assert((IMD || CID) && "Unknown ImplementationDecl");
1169 
1170   InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// ");
1171 
1172   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1173     if (!OMD->getBody())
1174       continue;
1175     std::string ResultStr;
1176     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1177     SourceLocation LocStart = OMD->getBeginLoc();
1178     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1179 
1180     const char *startBuf = SM->getCharacterData(LocStart);
1181     const char *endBuf = SM->getCharacterData(LocEnd);
1182     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1183   }
1184 
1185   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1186     if (!OMD->getBody())
1187       continue;
1188     std::string ResultStr;
1189     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1190     SourceLocation LocStart = OMD->getBeginLoc();
1191     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1192 
1193     const char *startBuf = SM->getCharacterData(LocStart);
1194     const char *endBuf = SM->getCharacterData(LocEnd);
1195     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1196   }
1197   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1198     RewritePropertyImplDecl(I, IMD, CID);
1199 
1200   InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1201 }
1202 
1203 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1204   std::string ResultStr;
1205   if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1206     // we haven't seen a forward decl - generate a typedef.
1207     ResultStr = "#ifndef _REWRITER_typedef_";
1208     ResultStr += ClassDecl->getNameAsString();
1209     ResultStr += "\n";
1210     ResultStr += "#define _REWRITER_typedef_";
1211     ResultStr += ClassDecl->getNameAsString();
1212     ResultStr += "\n";
1213     ResultStr += "typedef struct objc_object ";
1214     ResultStr += ClassDecl->getNameAsString();
1215     ResultStr += ";\n#endif\n";
1216     // Mark this typedef as having been generated.
1217     ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1218   }
1219   RewriteObjCInternalStruct(ClassDecl, ResultStr);
1220 
1221   for (auto *I : ClassDecl->instance_properties())
1222     RewriteProperty(I);
1223   for (auto *I : ClassDecl->instance_methods())
1224     RewriteMethodDeclaration(I);
1225   for (auto *I : ClassDecl->class_methods())
1226     RewriteMethodDeclaration(I);
1227 
1228   // Lastly, comment out the @end.
1229   ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230               "/* @end */");
1231 }
1232 
1233 Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1234   SourceRange OldRange = PseudoOp->getSourceRange();
1235 
1236   // We just magically know some things about the structure of this
1237   // expression.
1238   ObjCMessageExpr *OldMsg =
1239     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1240                             PseudoOp->getNumSemanticExprs() - 1));
1241 
1242   // Because the rewriter doesn't allow us to rewrite rewritten code,
1243   // we need to suppress rewriting the sub-statements.
1244   Expr *Base, *RHS;
1245   {
1246     DisableReplaceStmtScope S(*this);
1247 
1248     // Rebuild the base expression if we have one.
1249     Base = nullptr;
1250     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1251       Base = OldMsg->getInstanceReceiver();
1252       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1253       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1254     }
1255 
1256     // Rebuild the RHS.
1257     RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1258     RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1259     RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1260   }
1261 
1262   // TODO: avoid this copy.
1263   SmallVector<SourceLocation, 1> SelLocs;
1264   OldMsg->getSelectorLocs(SelLocs);
1265 
1266   ObjCMessageExpr *NewMsg = nullptr;
1267   switch (OldMsg->getReceiverKind()) {
1268   case ObjCMessageExpr::Class:
1269     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1270                                      OldMsg->getValueKind(),
1271                                      OldMsg->getLeftLoc(),
1272                                      OldMsg->getClassReceiverTypeInfo(),
1273                                      OldMsg->getSelector(),
1274                                      SelLocs,
1275                                      OldMsg->getMethodDecl(),
1276                                      RHS,
1277                                      OldMsg->getRightLoc(),
1278                                      OldMsg->isImplicit());
1279     break;
1280 
1281   case ObjCMessageExpr::Instance:
1282     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1283                                      OldMsg->getValueKind(),
1284                                      OldMsg->getLeftLoc(),
1285                                      Base,
1286                                      OldMsg->getSelector(),
1287                                      SelLocs,
1288                                      OldMsg->getMethodDecl(),
1289                                      RHS,
1290                                      OldMsg->getRightLoc(),
1291                                      OldMsg->isImplicit());
1292     break;
1293 
1294   case ObjCMessageExpr::SuperClass:
1295   case ObjCMessageExpr::SuperInstance:
1296     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1297                                      OldMsg->getValueKind(),
1298                                      OldMsg->getLeftLoc(),
1299                                      OldMsg->getSuperLoc(),
1300                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1301                                      OldMsg->getSuperType(),
1302                                      OldMsg->getSelector(),
1303                                      SelLocs,
1304                                      OldMsg->getMethodDecl(),
1305                                      RHS,
1306                                      OldMsg->getRightLoc(),
1307                                      OldMsg->isImplicit());
1308     break;
1309   }
1310 
1311   Stmt *Replacement = SynthMessageExpr(NewMsg);
1312   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1313   return Replacement;
1314 }
1315 
1316 Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1317   SourceRange OldRange = PseudoOp->getSourceRange();
1318 
1319   // We just magically know some things about the structure of this
1320   // expression.
1321   ObjCMessageExpr *OldMsg =
1322     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1323 
1324   // Because the rewriter doesn't allow us to rewrite rewritten code,
1325   // we need to suppress rewriting the sub-statements.
1326   Expr *Base = nullptr;
1327   {
1328     DisableReplaceStmtScope S(*this);
1329 
1330     // Rebuild the base expression if we have one.
1331     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1332       Base = OldMsg->getInstanceReceiver();
1333       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1334       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1335     }
1336   }
1337 
1338   // Intentionally empty.
1339   SmallVector<SourceLocation, 1> SelLocs;
1340   SmallVector<Expr*, 1> Args;
1341 
1342   ObjCMessageExpr *NewMsg = nullptr;
1343   switch (OldMsg->getReceiverKind()) {
1344   case ObjCMessageExpr::Class:
1345     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1346                                      OldMsg->getValueKind(),
1347                                      OldMsg->getLeftLoc(),
1348                                      OldMsg->getClassReceiverTypeInfo(),
1349                                      OldMsg->getSelector(),
1350                                      SelLocs,
1351                                      OldMsg->getMethodDecl(),
1352                                      Args,
1353                                      OldMsg->getRightLoc(),
1354                                      OldMsg->isImplicit());
1355     break;
1356 
1357   case ObjCMessageExpr::Instance:
1358     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1359                                      OldMsg->getValueKind(),
1360                                      OldMsg->getLeftLoc(),
1361                                      Base,
1362                                      OldMsg->getSelector(),
1363                                      SelLocs,
1364                                      OldMsg->getMethodDecl(),
1365                                      Args,
1366                                      OldMsg->getRightLoc(),
1367                                      OldMsg->isImplicit());
1368     break;
1369 
1370   case ObjCMessageExpr::SuperClass:
1371   case ObjCMessageExpr::SuperInstance:
1372     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1373                                      OldMsg->getValueKind(),
1374                                      OldMsg->getLeftLoc(),
1375                                      OldMsg->getSuperLoc(),
1376                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1377                                      OldMsg->getSuperType(),
1378                                      OldMsg->getSelector(),
1379                                      SelLocs,
1380                                      OldMsg->getMethodDecl(),
1381                                      Args,
1382                                      OldMsg->getRightLoc(),
1383                                      OldMsg->isImplicit());
1384     break;
1385   }
1386 
1387   Stmt *Replacement = SynthMessageExpr(NewMsg);
1388   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1389   return Replacement;
1390 }
1391 
1392 /// SynthCountByEnumWithState - To print:
1393 /// ((unsigned int (*)
1394 ///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1395 ///  (void *)objc_msgSend)((id)l_collection,
1396 ///                        sel_registerName(
1397 ///                          "countByEnumeratingWithState:objects:count:"),
1398 ///                        &enumState,
1399 ///                        (id *)__rw_items, (unsigned int)16)
1400 ///
1401 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1402   buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1403   "id *, unsigned int))(void *)objc_msgSend)";
1404   buf += "\n\t\t";
1405   buf += "((id)l_collection,\n\t\t";
1406   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1407   buf += "\n\t\t";
1408   buf += "&enumState, "
1409          "(id *)__rw_items, (unsigned int)16)";
1410 }
1411 
1412 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1413 /// statement to exit to its outer synthesized loop.
1414 ///
1415 Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1416   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1417     return S;
1418   // replace break with goto __break_label
1419   std::string buf;
1420 
1421   SourceLocation startLoc = S->getBeginLoc();
1422   buf = "goto __break_label_";
1423   buf += utostr(ObjCBcLabelNo.back());
1424   ReplaceText(startLoc, strlen("break"), buf);
1425 
1426   return nullptr;
1427 }
1428 
1429 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1430 /// statement to continue with its inner synthesized loop.
1431 ///
1432 Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1433   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1434     return S;
1435   // replace continue with goto __continue_label
1436   std::string buf;
1437 
1438   SourceLocation startLoc = S->getBeginLoc();
1439   buf = "goto __continue_label_";
1440   buf += utostr(ObjCBcLabelNo.back());
1441   ReplaceText(startLoc, strlen("continue"), buf);
1442 
1443   return nullptr;
1444 }
1445 
1446 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1447 ///  It rewrites:
1448 /// for ( type elem in collection) { stmts; }
1449 
1450 /// Into:
1451 /// {
1452 ///   type elem;
1453 ///   struct __objcFastEnumerationState enumState = { 0 };
1454 ///   id __rw_items[16];
1455 ///   id l_collection = (id)collection;
1456 ///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1457 ///                                       objects:__rw_items count:16];
1458 /// if (limit) {
1459 ///   unsigned long startMutations = *enumState.mutationsPtr;
1460 ///   do {
1461 ///        unsigned long counter = 0;
1462 ///        do {
1463 ///             if (startMutations != *enumState.mutationsPtr)
1464 ///               objc_enumerationMutation(l_collection);
1465 ///             elem = (type)enumState.itemsPtr[counter++];
1466 ///             stmts;
1467 ///             __continue_label: ;
1468 ///        } while (counter < limit);
1469 ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1470 ///                                  objects:__rw_items count:16]);
1471 ///   elem = nil;
1472 ///   __break_label: ;
1473 ///  }
1474 ///  else
1475 ///       elem = nil;
1476 ///  }
1477 ///
1478 Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1479                                                 SourceLocation OrigEnd) {
1480   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1481   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1482          "ObjCForCollectionStmt Statement stack mismatch");
1483   assert(!ObjCBcLabelNo.empty() &&
1484          "ObjCForCollectionStmt - Label No stack empty");
1485 
1486   SourceLocation startLoc = S->getBeginLoc();
1487   const char *startBuf = SM->getCharacterData(startLoc);
1488   StringRef elementName;
1489   std::string elementTypeAsString;
1490   std::string buf;
1491   buf = "\n{\n\t";
1492   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1493     // type elem;
1494     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1495     QualType ElementType = cast<ValueDecl>(D)->getType();
1496     if (ElementType->isObjCQualifiedIdType() ||
1497         ElementType->isObjCQualifiedInterfaceType())
1498       // Simply use 'id' for all qualified types.
1499       elementTypeAsString = "id";
1500     else
1501       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1502     buf += elementTypeAsString;
1503     buf += " ";
1504     elementName = D->getName();
1505     buf += elementName;
1506     buf += ";\n\t";
1507   }
1508   else {
1509     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1510     elementName = DR->getDecl()->getName();
1511     ValueDecl *VD = DR->getDecl();
1512     if (VD->getType()->isObjCQualifiedIdType() ||
1513         VD->getType()->isObjCQualifiedInterfaceType())
1514       // Simply use 'id' for all qualified types.
1515       elementTypeAsString = "id";
1516     else
1517       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1518   }
1519 
1520   // struct __objcFastEnumerationState enumState = { 0 };
1521   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1522   // id __rw_items[16];
1523   buf += "id __rw_items[16];\n\t";
1524   // id l_collection = (id)
1525   buf += "id l_collection = (id)";
1526   // Find start location of 'collection' the hard way!
1527   const char *startCollectionBuf = startBuf;
1528   startCollectionBuf += 3;  // skip 'for'
1529   startCollectionBuf = strchr(startCollectionBuf, '(');
1530   startCollectionBuf++; // skip '('
1531   // find 'in' and skip it.
1532   while (*startCollectionBuf != ' ' ||
1533          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1534          (*(startCollectionBuf+3) != ' ' &&
1535           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1536     startCollectionBuf++;
1537   startCollectionBuf += 3;
1538 
1539   // Replace: "for (type element in" with string constructed thus far.
1540   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1541   // Replace ')' in for '(' type elem in collection ')' with ';'
1542   SourceLocation rightParenLoc = S->getRParenLoc();
1543   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1544   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1545   buf = ";\n\t";
1546 
1547   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1548   //                                   objects:__rw_items count:16];
1549   // which is synthesized into:
1550   // unsigned int limit =
1551   // ((unsigned int (*)
1552   //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1553   //  (void *)objc_msgSend)((id)l_collection,
1554   //                        sel_registerName(
1555   //                          "countByEnumeratingWithState:objects:count:"),
1556   //                        (struct __objcFastEnumerationState *)&state,
1557   //                        (id *)__rw_items, (unsigned int)16);
1558   buf += "unsigned long limit =\n\t\t";
1559   SynthCountByEnumWithState(buf);
1560   buf += ";\n\t";
1561   /// if (limit) {
1562   ///   unsigned long startMutations = *enumState.mutationsPtr;
1563   ///   do {
1564   ///        unsigned long counter = 0;
1565   ///        do {
1566   ///             if (startMutations != *enumState.mutationsPtr)
1567   ///               objc_enumerationMutation(l_collection);
1568   ///             elem = (type)enumState.itemsPtr[counter++];
1569   buf += "if (limit) {\n\t";
1570   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1571   buf += "do {\n\t\t";
1572   buf += "unsigned long counter = 0;\n\t\t";
1573   buf += "do {\n\t\t\t";
1574   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1575   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1576   buf += elementName;
1577   buf += " = (";
1578   buf += elementTypeAsString;
1579   buf += ")enumState.itemsPtr[counter++];";
1580   // Replace ')' in for '(' type elem in collection ')' with all of these.
1581   ReplaceText(lparenLoc, 1, buf);
1582 
1583   ///            __continue_label: ;
1584   ///        } while (counter < limit);
1585   ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1586   ///                                  objects:__rw_items count:16]);
1587   ///   elem = nil;
1588   ///   __break_label: ;
1589   ///  }
1590   ///  else
1591   ///       elem = nil;
1592   ///  }
1593   ///
1594   buf = ";\n\t";
1595   buf += "__continue_label_";
1596   buf += utostr(ObjCBcLabelNo.back());
1597   buf += ": ;";
1598   buf += "\n\t\t";
1599   buf += "} while (counter < limit);\n\t";
1600   buf += "} while (limit = ";
1601   SynthCountByEnumWithState(buf);
1602   buf += ");\n\t";
1603   buf += elementName;
1604   buf += " = ((";
1605   buf += elementTypeAsString;
1606   buf += ")0);\n\t";
1607   buf += "__break_label_";
1608   buf += utostr(ObjCBcLabelNo.back());
1609   buf += ": ;\n\t";
1610   buf += "}\n\t";
1611   buf += "else\n\t\t";
1612   buf += elementName;
1613   buf += " = ((";
1614   buf += elementTypeAsString;
1615   buf += ")0);\n\t";
1616   buf += "}\n";
1617 
1618   // Insert all these *after* the statement body.
1619   // FIXME: If this should support Obj-C++, support CXXTryStmt
1620   if (isa<CompoundStmt>(S->getBody())) {
1621     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1622     InsertText(endBodyLoc, buf);
1623   } else {
1624     /* Need to treat single statements specially. For example:
1625      *
1626      *     for (A *a in b) if (stuff()) break;
1627      *     for (A *a in b) xxxyy;
1628      *
1629      * The following code simply scans ahead to the semi to find the actual end.
1630      */
1631     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1632     const char *semiBuf = strchr(stmtBuf, ';');
1633     assert(semiBuf && "Can't find ';'");
1634     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1635     InsertText(endBodyLoc, buf);
1636   }
1637   Stmts.pop_back();
1638   ObjCBcLabelNo.pop_back();
1639   return nullptr;
1640 }
1641 
1642 /// RewriteObjCSynchronizedStmt -
1643 /// This routine rewrites @synchronized(expr) stmt;
1644 /// into:
1645 /// objc_sync_enter(expr);
1646 /// @try stmt @finally { objc_sync_exit(expr); }
1647 ///
1648 Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1649   // Get the start location and compute the semi location.
1650   SourceLocation startLoc = S->getBeginLoc();
1651   const char *startBuf = SM->getCharacterData(startLoc);
1652 
1653   assert((*startBuf == '@') && "bogus @synchronized location");
1654 
1655   std::string buf;
1656   buf = "objc_sync_enter((id)";
1657   const char *lparenBuf = startBuf;
1658   while (*lparenBuf != '(') lparenBuf++;
1659   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1660   // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1661   // the sync expression is typically a message expression that's already
1662   // been rewritten! (which implies the SourceLocation's are invalid).
1663   SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
1664   const char *endBuf = SM->getCharacterData(endLoc);
1665   while (*endBuf != ')') endBuf--;
1666   SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1667   buf = ");\n";
1668   // declare a new scope with two variables, _stack and _rethrow.
1669   buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1670   buf += "int buf[18/*32-bit i386*/];\n";
1671   buf += "char *pointers[4];} _stack;\n";
1672   buf += "id volatile _rethrow = 0;\n";
1673   buf += "objc_exception_try_enter(&_stack);\n";
1674   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1675   ReplaceText(rparenLoc, 1, buf);
1676   startLoc = S->getSynchBody()->getEndLoc();
1677   startBuf = SM->getCharacterData(startLoc);
1678 
1679   assert((*startBuf == '}') && "bogus @synchronized block");
1680   SourceLocation lastCurlyLoc = startLoc;
1681   buf = "}\nelse {\n";
1682   buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1683   buf += "}\n";
1684   buf += "{ /* implicit finally clause */\n";
1685   buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1686 
1687   std::string syncBuf;
1688   syncBuf += " objc_sync_exit(";
1689 
1690   Expr *syncExpr = S->getSynchExpr();
1691   CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1692                   ? CK_BitCast :
1693                 syncExpr->getType()->isBlockPointerType()
1694                   ? CK_BlockPointerToObjCPointerCast
1695                   : CK_CPointerToObjCPointerCast;
1696   syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1697                                       CK, syncExpr);
1698   std::string syncExprBufS;
1699   llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1700   assert(syncExpr != nullptr && "Expected non-null Expr");
1701   syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1702   syncBuf += syncExprBuf.str();
1703   syncBuf += ");";
1704 
1705   buf += syncBuf;
1706   buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1707   buf += "}\n";
1708   buf += "}";
1709 
1710   ReplaceText(lastCurlyLoc, 1, buf);
1711 
1712   bool hasReturns = false;
1713   HasReturnStmts(S->getSynchBody(), hasReturns);
1714   if (hasReturns)
1715     RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1716 
1717   return nullptr;
1718 }
1719 
1720 void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1721 {
1722   // Perform a bottom up traversal of all children.
1723   for (Stmt *SubStmt : S->children())
1724     if (SubStmt)
1725       WarnAboutReturnGotoStmts(SubStmt);
1726 
1727   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1728     Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1729                  TryFinallyContainsReturnDiag);
1730   }
1731 }
1732 
1733 void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1734 {
1735   // Perform a bottom up traversal of all children.
1736   for (Stmt *SubStmt : S->children())
1737     if (SubStmt)
1738       HasReturnStmts(SubStmt, hasReturns);
1739 
1740   if (isa<ReturnStmt>(S))
1741     hasReturns = true;
1742 }
1743 
1744 void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1745   // Perform a bottom up traversal of all children.
1746   for (Stmt *SubStmt : S->children())
1747     if (SubStmt) {
1748       RewriteTryReturnStmts(SubStmt);
1749     }
1750   if (isa<ReturnStmt>(S)) {
1751     SourceLocation startLoc = S->getBeginLoc();
1752     const char *startBuf = SM->getCharacterData(startLoc);
1753     const char *semiBuf = strchr(startBuf, ';');
1754     assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1755     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1756 
1757     std::string buf;
1758     buf = "{ objc_exception_try_exit(&_stack); return";
1759 
1760     ReplaceText(startLoc, 6, buf);
1761     InsertText(onePastSemiLoc, "}");
1762   }
1763 }
1764 
1765 void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1766   // Perform a bottom up traversal of all children.
1767   for (Stmt *SubStmt : S->children())
1768     if (SubStmt) {
1769       RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1770     }
1771   if (isa<ReturnStmt>(S)) {
1772     SourceLocation startLoc = S->getBeginLoc();
1773     const char *startBuf = SM->getCharacterData(startLoc);
1774 
1775     const char *semiBuf = strchr(startBuf, ';');
1776     assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1777     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1778 
1779     std::string buf;
1780     buf = "{ objc_exception_try_exit(&_stack);";
1781     buf += syncExitBuf;
1782     buf += " return";
1783 
1784     ReplaceText(startLoc, 6, buf);
1785     InsertText(onePastSemiLoc, "}");
1786   }
1787 }
1788 
1789 Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1790   // Get the start location and compute the semi location.
1791   SourceLocation startLoc = S->getBeginLoc();
1792   const char *startBuf = SM->getCharacterData(startLoc);
1793 
1794   assert((*startBuf == '@') && "bogus @try location");
1795 
1796   std::string buf;
1797   // declare a new scope with two variables, _stack and _rethrow.
1798   buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1799   buf += "int buf[18/*32-bit i386*/];\n";
1800   buf += "char *pointers[4];} _stack;\n";
1801   buf += "id volatile _rethrow = 0;\n";
1802   buf += "objc_exception_try_enter(&_stack);\n";
1803   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1804 
1805   ReplaceText(startLoc, 4, buf);
1806 
1807   startLoc = S->getTryBody()->getEndLoc();
1808   startBuf = SM->getCharacterData(startLoc);
1809 
1810   assert((*startBuf == '}') && "bogus @try block");
1811 
1812   SourceLocation lastCurlyLoc = startLoc;
1813   if (S->getNumCatchStmts()) {
1814     startLoc = startLoc.getLocWithOffset(1);
1815     buf = " /* @catch begin */ else {\n";
1816     buf += " id _caught = objc_exception_extract(&_stack);\n";
1817     buf += " objc_exception_try_enter (&_stack);\n";
1818     buf += " if (_setjmp(_stack.buf))\n";
1819     buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1820     buf += " else { /* @catch continue */";
1821 
1822     InsertText(startLoc, buf);
1823   } else { /* no catch list */
1824     buf = "}\nelse {\n";
1825     buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1826     buf += "}";
1827     ReplaceText(lastCurlyLoc, 1, buf);
1828   }
1829   Stmt *lastCatchBody = nullptr;
1830   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1831     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1832     VarDecl *catchDecl = Catch->getCatchParamDecl();
1833 
1834     if (I == 0)
1835       buf = "if ("; // we are generating code for the first catch clause
1836     else
1837       buf = "else if (";
1838     startLoc = Catch->getBeginLoc();
1839     startBuf = SM->getCharacterData(startLoc);
1840 
1841     assert((*startBuf == '@') && "bogus @catch location");
1842 
1843     const char *lParenLoc = strchr(startBuf, '(');
1844 
1845     if (Catch->hasEllipsis()) {
1846       // Now rewrite the body...
1847       lastCatchBody = Catch->getCatchBody();
1848       SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1849       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1850       assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1851              "bogus @catch paren location");
1852       assert((*bodyBuf == '{') && "bogus @catch body location");
1853 
1854       buf += "1) { id _tmp = _caught;";
1855       Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1856     } else if (catchDecl) {
1857       QualType t = catchDecl->getType();
1858       if (t == Context->getObjCIdType()) {
1859         buf += "1) { ";
1860         ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1861       } else if (const ObjCObjectPointerType *Ptr =
1862                    t->getAs<ObjCObjectPointerType>()) {
1863         // Should be a pointer to a class.
1864         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1865         if (IDecl) {
1866           buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1867           buf += IDecl->getNameAsString();
1868           buf += "\"), (struct objc_object *)_caught)) { ";
1869           ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1870         }
1871       }
1872       // Now rewrite the body...
1873       lastCatchBody = Catch->getCatchBody();
1874       SourceLocation rParenLoc = Catch->getRParenLoc();
1875       SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1876       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1877       const char *rParenBuf = SM->getCharacterData(rParenLoc);
1878       assert((*rParenBuf == ')') && "bogus @catch paren location");
1879       assert((*bodyBuf == '{') && "bogus @catch body location");
1880 
1881       // Here we replace ") {" with "= _caught;" (which initializes and
1882       // declares the @catch parameter).
1883       ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1884     } else {
1885       llvm_unreachable("@catch rewrite bug");
1886     }
1887   }
1888   // Complete the catch list...
1889   if (lastCatchBody) {
1890     SourceLocation bodyLoc = lastCatchBody->getEndLoc();
1891     assert(*SM->getCharacterData(bodyLoc) == '}' &&
1892            "bogus @catch body location");
1893 
1894     // Insert the last (implicit) else clause *before* the right curly brace.
1895     bodyLoc = bodyLoc.getLocWithOffset(-1);
1896     buf = "} /* last catch end */\n";
1897     buf += "else {\n";
1898     buf += " _rethrow = _caught;\n";
1899     buf += " objc_exception_try_exit(&_stack);\n";
1900     buf += "} } /* @catch end */\n";
1901     if (!S->getFinallyStmt())
1902       buf += "}\n";
1903     InsertText(bodyLoc, buf);
1904 
1905     // Set lastCurlyLoc
1906     lastCurlyLoc = lastCatchBody->getEndLoc();
1907   }
1908   if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1909     startLoc = finalStmt->getBeginLoc();
1910     startBuf = SM->getCharacterData(startLoc);
1911     assert((*startBuf == '@') && "bogus @finally start");
1912 
1913     ReplaceText(startLoc, 8, "/* @finally */");
1914 
1915     Stmt *body = finalStmt->getFinallyBody();
1916     SourceLocation startLoc = body->getBeginLoc();
1917     SourceLocation endLoc = body->getEndLoc();
1918     assert(*SM->getCharacterData(startLoc) == '{' &&
1919            "bogus @finally body location");
1920     assert(*SM->getCharacterData(endLoc) == '}' &&
1921            "bogus @finally body location");
1922 
1923     startLoc = startLoc.getLocWithOffset(1);
1924     InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1925     endLoc = endLoc.getLocWithOffset(-1);
1926     InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1927 
1928     // Set lastCurlyLoc
1929     lastCurlyLoc = body->getEndLoc();
1930 
1931     // Now check for any return/continue/go statements within the @try.
1932     WarnAboutReturnGotoStmts(S->getTryBody());
1933   } else { /* no finally clause - make sure we synthesize an implicit one */
1934     buf = "{ /* implicit finally clause */\n";
1935     buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1936     buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1937     buf += "}";
1938     ReplaceText(lastCurlyLoc, 1, buf);
1939 
1940     // Now check for any return/continue/go statements within the @try.
1941     // The implicit finally clause won't called if the @try contains any
1942     // jump statements.
1943     bool hasReturns = false;
1944     HasReturnStmts(S->getTryBody(), hasReturns);
1945     if (hasReturns)
1946       RewriteTryReturnStmts(S->getTryBody());
1947   }
1948   // Now emit the final closing curly brace...
1949   lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1950   InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1951   return nullptr;
1952 }
1953 
1954 // This can't be done with ReplaceStmt(S, ThrowExpr), since
1955 // the throw expression is typically a message expression that's already
1956 // been rewritten! (which implies the SourceLocation's are invalid).
1957 Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1958   // Get the start location and compute the semi location.
1959   SourceLocation startLoc = S->getBeginLoc();
1960   const char *startBuf = SM->getCharacterData(startLoc);
1961 
1962   assert((*startBuf == '@') && "bogus @throw location");
1963 
1964   std::string buf;
1965   /* void objc_exception_throw(id) __attribute__((noreturn)); */
1966   if (S->getThrowExpr())
1967     buf = "objc_exception_throw(";
1968   else // add an implicit argument
1969     buf = "objc_exception_throw(_caught";
1970 
1971   // handle "@  throw" correctly.
1972   const char *wBuf = strchr(startBuf, 'w');
1973   assert((*wBuf == 'w') && "@throw: can't find 'w'");
1974   ReplaceText(startLoc, wBuf-startBuf+1, buf);
1975 
1976   const char *semiBuf = strchr(startBuf, ';');
1977   assert((*semiBuf == ';') && "@throw: can't find ';'");
1978   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1979   ReplaceText(semiLoc, 1, ");");
1980   return nullptr;
1981 }
1982 
1983 Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1984   // Create a new string expression.
1985   std::string StrEncoding;
1986   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1987   Expr *Replacement = getStringLiteral(StrEncoding);
1988   ReplaceStmt(Exp, Replacement);
1989 
1990   // Replace this subexpr in the parent.
1991   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1992   return Replacement;
1993 }
1994 
1995 Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1996   if (!SelGetUidFunctionDecl)
1997     SynthSelGetUidFunctionDecl();
1998   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1999   // Create a call to sel_registerName("selName").
2000   SmallVector<Expr*, 8> SelExprs;
2001   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2002   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2003                                                   SelExprs);
2004   ReplaceStmt(Exp, SelExp);
2005   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2006   return SelExp;
2007 }
2008 
2009 CallExpr *
2010 RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2011                                           ArrayRef<Expr *> Args,
2012                                           SourceLocation StartLoc,
2013                                           SourceLocation EndLoc) {
2014   // Get the type, we will need to reference it in a couple spots.
2015   QualType msgSendType = FD->getType();
2016 
2017   // Create a reference to the objc_msgSend() declaration.
2018   DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2019                                                VK_LValue, SourceLocation());
2020 
2021   // Now, we cast the reference to a pointer to the objc_msgSend type.
2022   QualType pToFunc = Context->getPointerType(msgSendType);
2023   ImplicitCastExpr *ICE =
2024     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2025                              DRE, nullptr, VK_RValue);
2026 
2027   const auto *FT = msgSendType->castAs<FunctionType>();
2028 
2029   CallExpr *Exp = CallExpr::Create(
2030       *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2031   return Exp;
2032 }
2033 
2034 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2035                                 const char *&startRef, const char *&endRef) {
2036   while (startBuf < endBuf) {
2037     if (*startBuf == '<')
2038       startRef = startBuf; // mark the start.
2039     if (*startBuf == '>') {
2040       if (startRef && *startRef == '<') {
2041         endRef = startBuf; // mark the end.
2042         return true;
2043       }
2044       return false;
2045     }
2046     startBuf++;
2047   }
2048   return false;
2049 }
2050 
2051 static void scanToNextArgument(const char *&argRef) {
2052   int angle = 0;
2053   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2054     if (*argRef == '<')
2055       angle++;
2056     else if (*argRef == '>')
2057       angle--;
2058     argRef++;
2059   }
2060   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2061 }
2062 
2063 bool RewriteObjC::needToScanForQualifiers(QualType T) {
2064   if (T->isObjCQualifiedIdType())
2065     return true;
2066   if (const PointerType *PT = T->getAs<PointerType>()) {
2067     if (PT->getPointeeType()->isObjCQualifiedIdType())
2068       return true;
2069   }
2070   if (T->isObjCObjectPointerType()) {
2071     T = T->getPointeeType();
2072     return T->isObjCQualifiedInterfaceType();
2073   }
2074   if (T->isArrayType()) {
2075     QualType ElemTy = Context->getBaseElementType(T);
2076     return needToScanForQualifiers(ElemTy);
2077   }
2078   return false;
2079 }
2080 
2081 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2082   QualType Type = E->getType();
2083   if (needToScanForQualifiers(Type)) {
2084     SourceLocation Loc, EndLoc;
2085 
2086     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2087       Loc = ECE->getLParenLoc();
2088       EndLoc = ECE->getRParenLoc();
2089     } else {
2090       Loc = E->getBeginLoc();
2091       EndLoc = E->getEndLoc();
2092     }
2093     // This will defend against trying to rewrite synthesized expressions.
2094     if (Loc.isInvalid() || EndLoc.isInvalid())
2095       return;
2096 
2097     const char *startBuf = SM->getCharacterData(Loc);
2098     const char *endBuf = SM->getCharacterData(EndLoc);
2099     const char *startRef = nullptr, *endRef = nullptr;
2100     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2101       // Get the locations of the startRef, endRef.
2102       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2103       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2104       // Comment out the protocol references.
2105       InsertText(LessLoc, "/*");
2106       InsertText(GreaterLoc, "*/");
2107     }
2108   }
2109 }
2110 
2111 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2112   SourceLocation Loc;
2113   QualType Type;
2114   const FunctionProtoType *proto = nullptr;
2115   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2116     Loc = VD->getLocation();
2117     Type = VD->getType();
2118   }
2119   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2120     Loc = FD->getLocation();
2121     // Check for ObjC 'id' and class types that have been adorned with protocol
2122     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2123     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2124     assert(funcType && "missing function type");
2125     proto = dyn_cast<FunctionProtoType>(funcType);
2126     if (!proto)
2127       return;
2128     Type = proto->getReturnType();
2129   }
2130   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2131     Loc = FD->getLocation();
2132     Type = FD->getType();
2133   }
2134   else
2135     return;
2136 
2137   if (needToScanForQualifiers(Type)) {
2138     // Since types are unique, we need to scan the buffer.
2139 
2140     const char *endBuf = SM->getCharacterData(Loc);
2141     const char *startBuf = endBuf;
2142     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2143       startBuf--; // scan backward (from the decl location) for return type.
2144     const char *startRef = nullptr, *endRef = nullptr;
2145     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2146       // Get the locations of the startRef, endRef.
2147       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2148       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2149       // Comment out the protocol references.
2150       InsertText(LessLoc, "/*");
2151       InsertText(GreaterLoc, "*/");
2152     }
2153   }
2154   if (!proto)
2155       return; // most likely, was a variable
2156   // Now check arguments.
2157   const char *startBuf = SM->getCharacterData(Loc);
2158   const char *startFuncBuf = startBuf;
2159   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2160     if (needToScanForQualifiers(proto->getParamType(i))) {
2161       // Since types are unique, we need to scan the buffer.
2162 
2163       const char *endBuf = startBuf;
2164       // scan forward (from the decl location) for argument types.
2165       scanToNextArgument(endBuf);
2166       const char *startRef = nullptr, *endRef = nullptr;
2167       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2168         // Get the locations of the startRef, endRef.
2169         SourceLocation LessLoc =
2170           Loc.getLocWithOffset(startRef-startFuncBuf);
2171         SourceLocation GreaterLoc =
2172           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2173         // Comment out the protocol references.
2174         InsertText(LessLoc, "/*");
2175         InsertText(GreaterLoc, "*/");
2176       }
2177       startBuf = ++endBuf;
2178     }
2179     else {
2180       // If the function name is derived from a macro expansion, then the
2181       // argument buffer will not follow the name. Need to speak with Chris.
2182       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2183         startBuf++; // scan forward (from the decl location) for argument types.
2184       startBuf++;
2185     }
2186   }
2187 }
2188 
2189 void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2190   QualType QT = ND->getType();
2191   const Type* TypePtr = QT->getAs<Type>();
2192   if (!isa<TypeOfExprType>(TypePtr))
2193     return;
2194   while (isa<TypeOfExprType>(TypePtr)) {
2195     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2196     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2197     TypePtr = QT->getAs<Type>();
2198   }
2199   // FIXME. This will not work for multiple declarators; as in:
2200   // __typeof__(a) b,c,d;
2201   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2202   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2203   const char *startBuf = SM->getCharacterData(DeclLoc);
2204   if (ND->getInit()) {
2205     std::string Name(ND->getNameAsString());
2206     TypeAsString += " " + Name + " = ";
2207     Expr *E = ND->getInit();
2208     SourceLocation startLoc;
2209     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2210       startLoc = ECE->getLParenLoc();
2211     else
2212       startLoc = E->getBeginLoc();
2213     startLoc = SM->getExpansionLoc(startLoc);
2214     const char *endBuf = SM->getCharacterData(startLoc);
2215     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2216   }
2217   else {
2218     SourceLocation X = ND->getEndLoc();
2219     X = SM->getExpansionLoc(X);
2220     const char *endBuf = SM->getCharacterData(X);
2221     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2222   }
2223 }
2224 
2225 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2226 void RewriteObjC::SynthSelGetUidFunctionDecl() {
2227   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2228   SmallVector<QualType, 16> ArgTys;
2229   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2230   QualType getFuncType =
2231     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2232   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2233                                                SourceLocation(),
2234                                                SourceLocation(),
2235                                                SelGetUidIdent, getFuncType,
2236                                                nullptr, SC_Extern);
2237 }
2238 
2239 void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2240   // declared in <objc/objc.h>
2241   if (FD->getIdentifier() &&
2242       FD->getName() == "sel_registerName") {
2243     SelGetUidFunctionDecl = FD;
2244     return;
2245   }
2246   RewriteObjCQualifiedInterfaceTypes(FD);
2247 }
2248 
2249 void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2250   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2251   const char *argPtr = TypeString.c_str();
2252   if (!strchr(argPtr, '^')) {
2253     Str += TypeString;
2254     return;
2255   }
2256   while (*argPtr) {
2257     Str += (*argPtr == '^' ? '*' : *argPtr);
2258     argPtr++;
2259   }
2260 }
2261 
2262 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2263 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2264                                                   ValueDecl *VD) {
2265   QualType Type = VD->getType();
2266   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2267   const char *argPtr = TypeString.c_str();
2268   int paren = 0;
2269   while (*argPtr) {
2270     switch (*argPtr) {
2271       case '(':
2272         Str += *argPtr;
2273         paren++;
2274         break;
2275       case ')':
2276         Str += *argPtr;
2277         paren--;
2278         break;
2279       case '^':
2280         Str += '*';
2281         if (paren == 1)
2282           Str += VD->getNameAsString();
2283         break;
2284       default:
2285         Str += *argPtr;
2286         break;
2287     }
2288     argPtr++;
2289   }
2290 }
2291 
2292 void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2293   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2294   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2295   const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType);
2296   if (!proto)
2297     return;
2298   QualType Type = proto->getReturnType();
2299   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2300   FdStr += " ";
2301   FdStr += FD->getName();
2302   FdStr +=  "(";
2303   unsigned numArgs = proto->getNumParams();
2304   for (unsigned i = 0; i < numArgs; i++) {
2305     QualType ArgType = proto->getParamType(i);
2306     RewriteBlockPointerType(FdStr, ArgType);
2307     if (i+1 < numArgs)
2308       FdStr += ", ";
2309   }
2310   FdStr +=  ");\n";
2311   InsertText(FunLocStart, FdStr);
2312   CurFunctionDeclToDeclareForBlock = nullptr;
2313 }
2314 
2315 // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2316 void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2317   if (SuperConstructorFunctionDecl)
2318     return;
2319   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2320   SmallVector<QualType, 16> ArgTys;
2321   QualType argT = Context->getObjCIdType();
2322   assert(!argT.isNull() && "Can't find 'id' type");
2323   ArgTys.push_back(argT);
2324   ArgTys.push_back(argT);
2325   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2326                                                ArgTys);
2327   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2328                                                      SourceLocation(),
2329                                                      SourceLocation(),
2330                                                      msgSendIdent, msgSendType,
2331                                                      nullptr, SC_Extern);
2332 }
2333 
2334 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2335 void RewriteObjC::SynthMsgSendFunctionDecl() {
2336   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2337   SmallVector<QualType, 16> ArgTys;
2338   QualType argT = Context->getObjCIdType();
2339   assert(!argT.isNull() && "Can't find 'id' type");
2340   ArgTys.push_back(argT);
2341   argT = Context->getObjCSelType();
2342   assert(!argT.isNull() && "Can't find 'SEL' type");
2343   ArgTys.push_back(argT);
2344   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2345                                                ArgTys, /*variadic=*/true);
2346   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2347                                              SourceLocation(),
2348                                              SourceLocation(),
2349                                              msgSendIdent, msgSendType,
2350                                              nullptr, SC_Extern);
2351 }
2352 
2353 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2354 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2355   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2356   SmallVector<QualType, 16> ArgTys;
2357   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2358                                       SourceLocation(), SourceLocation(),
2359                                       &Context->Idents.get("objc_super"));
2360   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2361   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2362   ArgTys.push_back(argT);
2363   argT = Context->getObjCSelType();
2364   assert(!argT.isNull() && "Can't find 'SEL' type");
2365   ArgTys.push_back(argT);
2366   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2367                                                ArgTys, /*variadic=*/true);
2368   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2369                                                   SourceLocation(),
2370                                                   SourceLocation(),
2371                                                   msgSendIdent, msgSendType,
2372                                                   nullptr, SC_Extern);
2373 }
2374 
2375 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2376 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2377   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2378   SmallVector<QualType, 16> ArgTys;
2379   QualType argT = Context->getObjCIdType();
2380   assert(!argT.isNull() && "Can't find 'id' type");
2381   ArgTys.push_back(argT);
2382   argT = Context->getObjCSelType();
2383   assert(!argT.isNull() && "Can't find 'SEL' type");
2384   ArgTys.push_back(argT);
2385   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2386                                                ArgTys, /*variadic=*/true);
2387   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2388                                                   SourceLocation(),
2389                                                   SourceLocation(),
2390                                                   msgSendIdent, msgSendType,
2391                                                   nullptr, SC_Extern);
2392 }
2393 
2394 // SynthMsgSendSuperStretFunctionDecl -
2395 // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2396 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2397   IdentifierInfo *msgSendIdent =
2398     &Context->Idents.get("objc_msgSendSuper_stret");
2399   SmallVector<QualType, 16> ArgTys;
2400   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2401                                       SourceLocation(), SourceLocation(),
2402                                       &Context->Idents.get("objc_super"));
2403   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2404   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2405   ArgTys.push_back(argT);
2406   argT = Context->getObjCSelType();
2407   assert(!argT.isNull() && "Can't find 'SEL' type");
2408   ArgTys.push_back(argT);
2409   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2410                                                ArgTys, /*variadic=*/true);
2411   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2412                                                        SourceLocation(),
2413                                                        SourceLocation(),
2414                                                        msgSendIdent,
2415                                                        msgSendType, nullptr,
2416                                                        SC_Extern);
2417 }
2418 
2419 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2420 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2421   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2422   SmallVector<QualType, 16> ArgTys;
2423   QualType argT = Context->getObjCIdType();
2424   assert(!argT.isNull() && "Can't find 'id' type");
2425   ArgTys.push_back(argT);
2426   argT = Context->getObjCSelType();
2427   assert(!argT.isNull() && "Can't find 'SEL' type");
2428   ArgTys.push_back(argT);
2429   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2430                                                ArgTys, /*variadic=*/true);
2431   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432                                                   SourceLocation(),
2433                                                   SourceLocation(),
2434                                                   msgSendIdent, msgSendType,
2435                                                   nullptr, SC_Extern);
2436 }
2437 
2438 // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2439 void RewriteObjC::SynthGetClassFunctionDecl() {
2440   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2441   SmallVector<QualType, 16> ArgTys;
2442   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2443   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2444                                                 ArgTys);
2445   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446                                               SourceLocation(),
2447                                               SourceLocation(),
2448                                               getClassIdent, getClassType,
2449                                               nullptr, SC_Extern);
2450 }
2451 
2452 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2453 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2454   IdentifierInfo *getSuperClassIdent =
2455     &Context->Idents.get("class_getSuperclass");
2456   SmallVector<QualType, 16> ArgTys;
2457   ArgTys.push_back(Context->getObjCClassType());
2458   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2459                                                 ArgTys);
2460   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2461                                                    SourceLocation(),
2462                                                    SourceLocation(),
2463                                                    getSuperClassIdent,
2464                                                    getClassType, nullptr,
2465                                                    SC_Extern);
2466 }
2467 
2468 // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2469 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2470   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2471   SmallVector<QualType, 16> ArgTys;
2472   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2473   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2474                                                 ArgTys);
2475   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2476                                                   SourceLocation(),
2477                                                   SourceLocation(),
2478                                                   getClassIdent, getClassType,
2479                                                   nullptr, SC_Extern);
2480 }
2481 
2482 Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2483   assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2484   QualType strType = getConstantStringStructType();
2485 
2486   std::string S = "__NSConstantStringImpl_";
2487 
2488   std::string tmpName = InFileName;
2489   unsigned i;
2490   for (i=0; i < tmpName.length(); i++) {
2491     char c = tmpName.at(i);
2492     // replace any non-alphanumeric characters with '_'.
2493     if (!isAlphanumeric(c))
2494       tmpName[i] = '_';
2495   }
2496   S += tmpName;
2497   S += "_";
2498   S += utostr(NumObjCStringLiterals++);
2499 
2500   Preamble += "static __NSConstantStringImpl " + S;
2501   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2502   Preamble += "0x000007c8,"; // utf8_str
2503   // The pretty printer for StringLiteral handles escape characters properly.
2504   std::string prettyBufS;
2505   llvm::raw_string_ostream prettyBuf(prettyBufS);
2506   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2507   Preamble += prettyBuf.str();
2508   Preamble += ",";
2509   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2510 
2511   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2512                                    SourceLocation(), &Context->Idents.get(S),
2513                                    strType, nullptr, SC_Static);
2514   DeclRefExpr *DRE = new (Context)
2515       DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2516   Expr *Unop = new (Context)
2517       UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2518                     VK_RValue, OK_Ordinary, SourceLocation(), false);
2519   // cast to NSConstantString *
2520   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2521                                             CK_CPointerToObjCPointerCast, Unop);
2522   ReplaceStmt(Exp, cast);
2523   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2524   return cast;
2525 }
2526 
2527 // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2528 QualType RewriteObjC::getSuperStructType() {
2529   if (!SuperStructDecl) {
2530     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2531                                          SourceLocation(), SourceLocation(),
2532                                          &Context->Idents.get("objc_super"));
2533     QualType FieldTypes[2];
2534 
2535     // struct objc_object *receiver;
2536     FieldTypes[0] = Context->getObjCIdType();
2537     // struct objc_class *super;
2538     FieldTypes[1] = Context->getObjCClassType();
2539 
2540     // Create fields
2541     for (unsigned i = 0; i < 2; ++i) {
2542       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2543                                                  SourceLocation(),
2544                                                  SourceLocation(), nullptr,
2545                                                  FieldTypes[i], nullptr,
2546                                                  /*BitWidth=*/nullptr,
2547                                                  /*Mutable=*/false,
2548                                                  ICIS_NoInit));
2549     }
2550 
2551     SuperStructDecl->completeDefinition();
2552   }
2553   return Context->getTagDeclType(SuperStructDecl);
2554 }
2555 
2556 QualType RewriteObjC::getConstantStringStructType() {
2557   if (!ConstantStringDecl) {
2558     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2559                                             SourceLocation(), SourceLocation(),
2560                          &Context->Idents.get("__NSConstantStringImpl"));
2561     QualType FieldTypes[4];
2562 
2563     // struct objc_object *receiver;
2564     FieldTypes[0] = Context->getObjCIdType();
2565     // int flags;
2566     FieldTypes[1] = Context->IntTy;
2567     // char *str;
2568     FieldTypes[2] = Context->getPointerType(Context->CharTy);
2569     // long length;
2570     FieldTypes[3] = Context->LongTy;
2571 
2572     // Create fields
2573     for (unsigned i = 0; i < 4; ++i) {
2574       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2575                                                     ConstantStringDecl,
2576                                                     SourceLocation(),
2577                                                     SourceLocation(), nullptr,
2578                                                     FieldTypes[i], nullptr,
2579                                                     /*BitWidth=*/nullptr,
2580                                                     /*Mutable=*/true,
2581                                                     ICIS_NoInit));
2582     }
2583 
2584     ConstantStringDecl->completeDefinition();
2585   }
2586   return Context->getTagDeclType(ConstantStringDecl);
2587 }
2588 
2589 CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2590                                                 QualType msgSendType,
2591                                                 QualType returnType,
2592                                                 SmallVectorImpl<QualType> &ArgTypes,
2593                                                 SmallVectorImpl<Expr*> &MsgExprs,
2594                                                 ObjCMethodDecl *Method) {
2595   // Create a reference to the objc_msgSend_stret() declaration.
2596   DeclRefExpr *STDRE =
2597       new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
2598                                 msgSendType, VK_LValue, SourceLocation());
2599   // Need to cast objc_msgSend_stret to "void *" (see above comment).
2600   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2601                                   Context->getPointerType(Context->VoidTy),
2602                                   CK_BitCast, STDRE);
2603   // Now do the "normal" pointer to function cast.
2604   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2605                                             Method ? Method->isVariadic()
2606                                                    : false);
2607   castType = Context->getPointerType(castType);
2608   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2609                                             cast);
2610 
2611   // Don't forget the parens to enforce the proper binding.
2612   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2613 
2614   const auto *FT = msgSendType->castAs<FunctionType>();
2615   CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2616                                     VK_RValue, SourceLocation());
2617   return STCE;
2618 }
2619 
2620 Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2621                                     SourceLocation StartLoc,
2622                                     SourceLocation EndLoc) {
2623   if (!SelGetUidFunctionDecl)
2624     SynthSelGetUidFunctionDecl();
2625   if (!MsgSendFunctionDecl)
2626     SynthMsgSendFunctionDecl();
2627   if (!MsgSendSuperFunctionDecl)
2628     SynthMsgSendSuperFunctionDecl();
2629   if (!MsgSendStretFunctionDecl)
2630     SynthMsgSendStretFunctionDecl();
2631   if (!MsgSendSuperStretFunctionDecl)
2632     SynthMsgSendSuperStretFunctionDecl();
2633   if (!MsgSendFpretFunctionDecl)
2634     SynthMsgSendFpretFunctionDecl();
2635   if (!GetClassFunctionDecl)
2636     SynthGetClassFunctionDecl();
2637   if (!GetSuperClassFunctionDecl)
2638     SynthGetSuperClassFunctionDecl();
2639   if (!GetMetaClassFunctionDecl)
2640     SynthGetMetaClassFunctionDecl();
2641 
2642   // default to objc_msgSend().
2643   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2644   // May need to use objc_msgSend_stret() as well.
2645   FunctionDecl *MsgSendStretFlavor = nullptr;
2646   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2647     QualType resultType = mDecl->getReturnType();
2648     if (resultType->isRecordType())
2649       MsgSendStretFlavor = MsgSendStretFunctionDecl;
2650     else if (resultType->isRealFloatingType())
2651       MsgSendFlavor = MsgSendFpretFunctionDecl;
2652   }
2653 
2654   // Synthesize a call to objc_msgSend().
2655   SmallVector<Expr*, 8> MsgExprs;
2656   switch (Exp->getReceiverKind()) {
2657   case ObjCMessageExpr::SuperClass: {
2658     MsgSendFlavor = MsgSendSuperFunctionDecl;
2659     if (MsgSendStretFlavor)
2660       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2661     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2662 
2663     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2664 
2665     SmallVector<Expr*, 4> InitExprs;
2666 
2667     // set the receiver to self, the first argument to all methods.
2668     InitExprs.push_back(
2669       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2670                                CK_BitCast,
2671                    new (Context) DeclRefExpr(*Context,
2672                                              CurMethodDef->getSelfDecl(),
2673                                              false,
2674                                              Context->getObjCIdType(),
2675                                              VK_RValue,
2676                                              SourceLocation()))
2677                         ); // set the 'receiver'.
2678 
2679     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2680     SmallVector<Expr*, 8> ClsExprs;
2681     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2682     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683                                                  ClsExprs, StartLoc, EndLoc);
2684     // (Class)objc_getClass("CurrentClass")
2685     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2686                                              Context->getObjCClassType(),
2687                                              CK_BitCast, Cls);
2688     ClsExprs.clear();
2689     ClsExprs.push_back(ArgExpr);
2690     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2691                                        StartLoc, EndLoc);
2692     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2693     // To turn off a warning, type-cast to 'id'
2694     InitExprs.push_back( // set 'super class', using class_getSuperclass().
2695                         NoTypeInfoCStyleCastExpr(Context,
2696                                                  Context->getObjCIdType(),
2697                                                  CK_BitCast, Cls));
2698     // struct objc_super
2699     QualType superType = getSuperStructType();
2700     Expr *SuperRep;
2701 
2702     if (LangOpts.MicrosoftExt) {
2703       SynthSuperConstructorFunctionDecl();
2704       // Simulate a constructor call...
2705       DeclRefExpr *DRE = new (Context)
2706           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2707                       VK_LValue, SourceLocation());
2708       SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2709                                   VK_LValue, SourceLocation());
2710       // The code for super is a little tricky to prevent collision with
2711       // the structure definition in the header. The rewriter has it's own
2712       // internal definition (__rw_objc_super) that is uses. This is why
2713       // we need the cast below. For example:
2714       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2715       //
2716       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2717                                Context->getPointerType(SuperRep->getType()),
2718                                              VK_RValue, OK_Ordinary,
2719                                              SourceLocation(), false);
2720       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2721                                           Context->getPointerType(superType),
2722                                           CK_BitCast, SuperRep);
2723     } else {
2724       // (struct objc_super) { <exprs from above> }
2725       InitListExpr *ILE =
2726         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2727                                    SourceLocation());
2728       TypeSourceInfo *superTInfo
2729         = Context->getTrivialTypeSourceInfo(superType);
2730       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2731                                                    superType, VK_LValue,
2732                                                    ILE, false);
2733       // struct objc_super *
2734       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2735                                Context->getPointerType(SuperRep->getType()),
2736                                              VK_RValue, OK_Ordinary,
2737                                              SourceLocation(), false);
2738     }
2739     MsgExprs.push_back(SuperRep);
2740     break;
2741   }
2742 
2743   case ObjCMessageExpr::Class: {
2744     SmallVector<Expr*, 8> ClsExprs;
2745     auto *Class =
2746         Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
2747     IdentifierInfo *clsName = Class->getIdentifier();
2748     ClsExprs.push_back(getStringLiteral(clsName->getName()));
2749     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2750                                                  StartLoc, EndLoc);
2751     MsgExprs.push_back(Cls);
2752     break;
2753   }
2754 
2755   case ObjCMessageExpr::SuperInstance:{
2756     MsgSendFlavor = MsgSendSuperFunctionDecl;
2757     if (MsgSendStretFlavor)
2758       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2759     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2760     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2761     SmallVector<Expr*, 4> InitExprs;
2762 
2763     InitExprs.push_back(
2764       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2765                                CK_BitCast,
2766                    new (Context) DeclRefExpr(*Context,
2767                                              CurMethodDef->getSelfDecl(),
2768                                              false,
2769                                              Context->getObjCIdType(),
2770                                              VK_RValue, SourceLocation()))
2771                         ); // set the 'receiver'.
2772 
2773     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2774     SmallVector<Expr*, 8> ClsExprs;
2775     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2776     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2777                                                  StartLoc, EndLoc);
2778     // (Class)objc_getClass("CurrentClass")
2779     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2780                                                  Context->getObjCClassType(),
2781                                                  CK_BitCast, Cls);
2782     ClsExprs.clear();
2783     ClsExprs.push_back(ArgExpr);
2784     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2785                                        StartLoc, EndLoc);
2786 
2787     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2788     // To turn off a warning, type-cast to 'id'
2789     InitExprs.push_back(
2790       // set 'super class', using class_getSuperclass().
2791       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2792                                CK_BitCast, Cls));
2793     // struct objc_super
2794     QualType superType = getSuperStructType();
2795     Expr *SuperRep;
2796 
2797     if (LangOpts.MicrosoftExt) {
2798       SynthSuperConstructorFunctionDecl();
2799       // Simulate a constructor call...
2800       DeclRefExpr *DRE = new (Context)
2801           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2802                       VK_LValue, SourceLocation());
2803       SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2804                                   VK_LValue, SourceLocation());
2805       // The code for super is a little tricky to prevent collision with
2806       // the structure definition in the header. The rewriter has it's own
2807       // internal definition (__rw_objc_super) that is uses. This is why
2808       // we need the cast below. For example:
2809       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2810       //
2811       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2812                                Context->getPointerType(SuperRep->getType()),
2813                                VK_RValue, OK_Ordinary,
2814                                SourceLocation(), false);
2815       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2816                                Context->getPointerType(superType),
2817                                CK_BitCast, SuperRep);
2818     } else {
2819       // (struct objc_super) { <exprs from above> }
2820       InitListExpr *ILE =
2821         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2822                                    SourceLocation());
2823       TypeSourceInfo *superTInfo
2824         = Context->getTrivialTypeSourceInfo(superType);
2825       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2826                                                    superType, VK_RValue, ILE,
2827                                                    false);
2828     }
2829     MsgExprs.push_back(SuperRep);
2830     break;
2831   }
2832 
2833   case ObjCMessageExpr::Instance: {
2834     // Remove all type-casts because it may contain objc-style types; e.g.
2835     // Foo<Proto> *.
2836     Expr *recExpr = Exp->getInstanceReceiver();
2837     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2838       recExpr = CE->getSubExpr();
2839     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2840                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2841                                      ? CK_BlockPointerToObjCPointerCast
2842                                      : CK_CPointerToObjCPointerCast;
2843 
2844     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2845                                        CK, recExpr);
2846     MsgExprs.push_back(recExpr);
2847     break;
2848   }
2849   }
2850 
2851   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2852   SmallVector<Expr*, 8> SelExprs;
2853   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2854   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2855                                                   SelExprs, StartLoc, EndLoc);
2856   MsgExprs.push_back(SelExp);
2857 
2858   // Now push any user supplied arguments.
2859   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2860     Expr *userExpr = Exp->getArg(i);
2861     // Make all implicit casts explicit...ICE comes in handy:-)
2862     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2863       // Reuse the ICE type, it is exactly what the doctor ordered.
2864       QualType type = ICE->getType();
2865       if (needToScanForQualifiers(type))
2866         type = Context->getObjCIdType();
2867       // Make sure we convert "type (^)(...)" to "type (*)(...)".
2868       (void)convertBlockPointerToFunctionPointer(type);
2869       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2870       CastKind CK;
2871       if (SubExpr->getType()->isIntegralType(*Context) &&
2872           type->isBooleanType()) {
2873         CK = CK_IntegralToBoolean;
2874       } else if (type->isObjCObjectPointerType()) {
2875         if (SubExpr->getType()->isBlockPointerType()) {
2876           CK = CK_BlockPointerToObjCPointerCast;
2877         } else if (SubExpr->getType()->isPointerType()) {
2878           CK = CK_CPointerToObjCPointerCast;
2879         } else {
2880           CK = CK_BitCast;
2881         }
2882       } else {
2883         CK = CK_BitCast;
2884       }
2885 
2886       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2887     }
2888     // Make id<P...> cast into an 'id' cast.
2889     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2890       if (CE->getType()->isObjCQualifiedIdType()) {
2891         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2892           userExpr = CE->getSubExpr();
2893         CastKind CK;
2894         if (userExpr->getType()->isIntegralType(*Context)) {
2895           CK = CK_IntegralToPointer;
2896         } else if (userExpr->getType()->isBlockPointerType()) {
2897           CK = CK_BlockPointerToObjCPointerCast;
2898         } else if (userExpr->getType()->isPointerType()) {
2899           CK = CK_CPointerToObjCPointerCast;
2900         } else {
2901           CK = CK_BitCast;
2902         }
2903         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2904                                             CK, userExpr);
2905       }
2906     }
2907     MsgExprs.push_back(userExpr);
2908     // We've transferred the ownership to MsgExprs. For now, we *don't* null
2909     // out the argument in the original expression (since we aren't deleting
2910     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2911     //Exp->setArg(i, 0);
2912   }
2913   // Generate the funky cast.
2914   CastExpr *cast;
2915   SmallVector<QualType, 8> ArgTypes;
2916   QualType returnType;
2917 
2918   // Push 'id' and 'SEL', the 2 implicit arguments.
2919   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2920     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2921   else
2922     ArgTypes.push_back(Context->getObjCIdType());
2923   ArgTypes.push_back(Context->getObjCSelType());
2924   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2925     // Push any user argument types.
2926     for (const auto *PI : OMD->parameters()) {
2927       QualType t = PI->getType()->isObjCQualifiedIdType()
2928                      ? Context->getObjCIdType()
2929                      : PI->getType();
2930       // Make sure we convert "t (^)(...)" to "t (*)(...)".
2931       (void)convertBlockPointerToFunctionPointer(t);
2932       ArgTypes.push_back(t);
2933     }
2934     returnType = Exp->getType();
2935     convertToUnqualifiedObjCType(returnType);
2936     (void)convertBlockPointerToFunctionPointer(returnType);
2937   } else {
2938     returnType = Context->getObjCIdType();
2939   }
2940   // Get the type, we will need to reference it in a couple spots.
2941   QualType msgSendType = MsgSendFlavor->getType();
2942 
2943   // Create a reference to the objc_msgSend() declaration.
2944   DeclRefExpr *DRE = new (Context) DeclRefExpr(
2945       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2946 
2947   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2948   // If we don't do this cast, we get the following bizarre warning/note:
2949   // xx.m:13: warning: function called through a non-compatible type
2950   // xx.m:13: note: if this code is reached, the program will abort
2951   cast = NoTypeInfoCStyleCastExpr(Context,
2952                                   Context->getPointerType(Context->VoidTy),
2953                                   CK_BitCast, DRE);
2954 
2955   // Now do the "normal" pointer to function cast.
2956   // If we don't have a method decl, force a variadic cast.
2957   const ObjCMethodDecl *MD = Exp->getMethodDecl();
2958   QualType castType =
2959     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
2960   castType = Context->getPointerType(castType);
2961   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2962                                   cast);
2963 
2964   // Don't forget the parens to enforce the proper binding.
2965   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2966 
2967   const auto *FT = msgSendType->castAs<FunctionType>();
2968   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2969                                   VK_RValue, EndLoc);
2970   Stmt *ReplacingStmt = CE;
2971   if (MsgSendStretFlavor) {
2972     // We have the method which returns a struct/union. Must also generate
2973     // call to objc_msgSend_stret and hang both varieties on a conditional
2974     // expression which dictate which one to envoke depending on size of
2975     // method's return type.
2976 
2977     CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2978                                                msgSendType, returnType,
2979                                                ArgTypes, MsgExprs,
2980                                                Exp->getMethodDecl());
2981 
2982     // Build sizeof(returnType)
2983     UnaryExprOrTypeTraitExpr *sizeofExpr =
2984        new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2985                                  Context->getTrivialTypeSourceInfo(returnType),
2986                                  Context->getSizeType(), SourceLocation(),
2987                                  SourceLocation());
2988     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2989     // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2990     // For X86 it is more complicated and some kind of target specific routine
2991     // is needed to decide what to do.
2992     unsigned IntSize =
2993       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2994     IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2995                                                    llvm::APInt(IntSize, 8),
2996                                                    Context->IntTy,
2997                                                    SourceLocation());
2998     BinaryOperator *lessThanExpr = BinaryOperator::Create(
2999         *Context, sizeofExpr, limit, BO_LE, Context->IntTy, VK_RValue,
3000         OK_Ordinary, SourceLocation(), FPOptions(Context->getLangOpts()));
3001     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3002     ConditionalOperator *CondExpr =
3003       new (Context) ConditionalOperator(lessThanExpr,
3004                                         SourceLocation(), CE,
3005                                         SourceLocation(), STCE,
3006                                         returnType, VK_RValue, OK_Ordinary);
3007     ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3008                                             CondExpr);
3009   }
3010   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3011   return ReplacingStmt;
3012 }
3013 
3014 Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3015   Stmt *ReplacingStmt =
3016       SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3017 
3018   // Now do the actual rewrite.
3019   ReplaceStmt(Exp, ReplacingStmt);
3020 
3021   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3022   return ReplacingStmt;
3023 }
3024 
3025 // typedef struct objc_object Protocol;
3026 QualType RewriteObjC::getProtocolType() {
3027   if (!ProtocolTypeDecl) {
3028     TypeSourceInfo *TInfo
3029       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3030     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3031                                            SourceLocation(), SourceLocation(),
3032                                            &Context->Idents.get("Protocol"),
3033                                            TInfo);
3034   }
3035   return Context->getTypeDeclType(ProtocolTypeDecl);
3036 }
3037 
3038 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3039 /// a synthesized/forward data reference (to the protocol's metadata).
3040 /// The forward references (and metadata) are generated in
3041 /// RewriteObjC::HandleTranslationUnit().
3042 Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3043   std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3044   IdentifierInfo *ID = &Context->Idents.get(Name);
3045   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3046                                 SourceLocation(), ID, getProtocolType(),
3047                                 nullptr, SC_Extern);
3048   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3049       *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3050   Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3051                              Context->getPointerType(DRE->getType()),
3052                              VK_RValue, OK_Ordinary, SourceLocation(), false);
3053   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3054                                                 CK_BitCast,
3055                                                 DerefExpr);
3056   ReplaceStmt(Exp, castExpr);
3057   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3058   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3059   return castExpr;
3060 }
3061 
3062 bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3063                                              const char *endBuf) {
3064   while (startBuf < endBuf) {
3065     if (*startBuf == '#') {
3066       // Skip whitespace.
3067       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3068         ;
3069       if (!strncmp(startBuf, "if", strlen("if")) ||
3070           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3071           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3072           !strncmp(startBuf, "define", strlen("define")) ||
3073           !strncmp(startBuf, "undef", strlen("undef")) ||
3074           !strncmp(startBuf, "else", strlen("else")) ||
3075           !strncmp(startBuf, "elif", strlen("elif")) ||
3076           !strncmp(startBuf, "endif", strlen("endif")) ||
3077           !strncmp(startBuf, "pragma", strlen("pragma")) ||
3078           !strncmp(startBuf, "include", strlen("include")) ||
3079           !strncmp(startBuf, "import", strlen("import")) ||
3080           !strncmp(startBuf, "include_next", strlen("include_next")))
3081         return true;
3082     }
3083     startBuf++;
3084   }
3085   return false;
3086 }
3087 
3088 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3089 /// an objective-c class with ivars.
3090 void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3091                                                std::string &Result) {
3092   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3093   assert(CDecl->getName() != "" &&
3094          "Name missing in SynthesizeObjCInternalStruct");
3095   // Do not synthesize more than once.
3096   if (ObjCSynthesizedStructs.count(CDecl))
3097     return;
3098   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3099   int NumIvars = CDecl->ivar_size();
3100   SourceLocation LocStart = CDecl->getBeginLoc();
3101   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3102 
3103   const char *startBuf = SM->getCharacterData(LocStart);
3104   const char *endBuf = SM->getCharacterData(LocEnd);
3105 
3106   // If no ivars and no root or if its root, directly or indirectly,
3107   // have no ivars (thus not synthesized) then no need to synthesize this class.
3108   if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3109       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3110     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3111     ReplaceText(LocStart, endBuf-startBuf, Result);
3112     return;
3113   }
3114 
3115   // FIXME: This has potential of causing problem. If
3116   // SynthesizeObjCInternalStruct is ever called recursively.
3117   Result += "\nstruct ";
3118   Result += CDecl->getNameAsString();
3119   if (LangOpts.MicrosoftExt)
3120     Result += "_IMPL";
3121 
3122   if (NumIvars > 0) {
3123     const char *cursor = strchr(startBuf, '{');
3124     assert((cursor && endBuf)
3125            && "SynthesizeObjCInternalStruct - malformed @interface");
3126     // If the buffer contains preprocessor directives, we do more fine-grained
3127     // rewrites. This is intended to fix code that looks like (which occurs in
3128     // NSURL.h, for example):
3129     //
3130     // #ifdef XYZ
3131     // @interface Foo : NSObject
3132     // #else
3133     // @interface FooBar : NSObject
3134     // #endif
3135     // {
3136     //    int i;
3137     // }
3138     // @end
3139     //
3140     // This clause is segregated to avoid breaking the common case.
3141     if (BufferContainsPPDirectives(startBuf, cursor)) {
3142       SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3143                                   CDecl->getAtStartLoc();
3144       const char *endHeader = SM->getCharacterData(L);
3145       endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3146 
3147       if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3148         // advance to the end of the referenced protocols.
3149         while (endHeader < cursor && *endHeader != '>') endHeader++;
3150         endHeader++;
3151       }
3152       // rewrite the original header
3153       ReplaceText(LocStart, endHeader-startBuf, Result);
3154     } else {
3155       // rewrite the original header *without* disturbing the '{'
3156       ReplaceText(LocStart, cursor-startBuf, Result);
3157     }
3158     if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3159       Result = "\n    struct ";
3160       Result += RCDecl->getNameAsString();
3161       Result += "_IMPL ";
3162       Result += RCDecl->getNameAsString();
3163       Result += "_IVARS;\n";
3164 
3165       // insert the super class structure definition.
3166       SourceLocation OnePastCurly =
3167         LocStart.getLocWithOffset(cursor-startBuf+1);
3168       InsertText(OnePastCurly, Result);
3169     }
3170     cursor++; // past '{'
3171 
3172     // Now comment out any visibility specifiers.
3173     while (cursor < endBuf) {
3174       if (*cursor == '@') {
3175         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3176         // Skip whitespace.
3177         for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3178           /*scan*/;
3179 
3180         // FIXME: presence of @public, etc. inside comment results in
3181         // this transformation as well, which is still correct c-code.
3182         if (!strncmp(cursor, "public", strlen("public")) ||
3183             !strncmp(cursor, "private", strlen("private")) ||
3184             !strncmp(cursor, "package", strlen("package")) ||
3185             !strncmp(cursor, "protected", strlen("protected")))
3186           InsertText(atLoc, "// ");
3187       }
3188       // FIXME: If there are cases where '<' is used in ivar declaration part
3189       // of user code, then scan the ivar list and use needToScanForQualifiers
3190       // for type checking.
3191       else if (*cursor == '<') {
3192         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3193         InsertText(atLoc, "/* ");
3194         cursor = strchr(cursor, '>');
3195         cursor++;
3196         atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3197         InsertText(atLoc, " */");
3198       } else if (*cursor == '^') { // rewrite block specifier.
3199         SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3200         ReplaceText(caretLoc, 1, "*");
3201       }
3202       cursor++;
3203     }
3204     // Don't forget to add a ';'!!
3205     InsertText(LocEnd.getLocWithOffset(1), ";");
3206   } else { // we don't have any instance variables - insert super struct.
3207     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3208     Result += " {\n    struct ";
3209     Result += RCDecl->getNameAsString();
3210     Result += "_IMPL ";
3211     Result += RCDecl->getNameAsString();
3212     Result += "_IVARS;\n};\n";
3213     ReplaceText(LocStart, endBuf-startBuf, Result);
3214   }
3215   // Mark this struct as having been generated.
3216   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3217     llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3218 }
3219 
3220 //===----------------------------------------------------------------------===//
3221 // Meta Data Emission
3222 //===----------------------------------------------------------------------===//
3223 
3224 /// RewriteImplementations - This routine rewrites all method implementations
3225 /// and emits meta-data.
3226 
3227 void RewriteObjC::RewriteImplementations() {
3228   int ClsDefCount = ClassImplementation.size();
3229   int CatDefCount = CategoryImplementation.size();
3230 
3231   // Rewrite implemented methods
3232   for (int i = 0; i < ClsDefCount; i++)
3233     RewriteImplementationDecl(ClassImplementation[i]);
3234 
3235   for (int i = 0; i < CatDefCount; i++)
3236     RewriteImplementationDecl(CategoryImplementation[i]);
3237 }
3238 
3239 void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3240                                      const std::string &Name,
3241                                      ValueDecl *VD, bool def) {
3242   assert(BlockByRefDeclNo.count(VD) &&
3243          "RewriteByRefString: ByRef decl missing");
3244   if (def)
3245     ResultStr += "struct ";
3246   ResultStr += "__Block_byref_" + Name +
3247     "_" + utostr(BlockByRefDeclNo[VD]) ;
3248 }
3249 
3250 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3251   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3252     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3253   return false;
3254 }
3255 
3256 std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3257                                                    StringRef funcName,
3258                                                    std::string Tag) {
3259   const FunctionType *AFT = CE->getFunctionType();
3260   QualType RT = AFT->getReturnType();
3261   std::string StructRef = "struct " + Tag;
3262   std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3263                   funcName.str() + "_" + "block_func_" + utostr(i);
3264 
3265   BlockDecl *BD = CE->getBlockDecl();
3266 
3267   if (isa<FunctionNoProtoType>(AFT)) {
3268     // No user-supplied arguments. Still need to pass in a pointer to the
3269     // block (to reference imported block decl refs).
3270     S += "(" + StructRef + " *__cself)";
3271   } else if (BD->param_empty()) {
3272     S += "(" + StructRef + " *__cself)";
3273   } else {
3274     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3275     assert(FT && "SynthesizeBlockFunc: No function proto");
3276     S += '(';
3277     // first add the implicit argument.
3278     S += StructRef + " *__cself, ";
3279     std::string ParamStr;
3280     for (BlockDecl::param_iterator AI = BD->param_begin(),
3281          E = BD->param_end(); AI != E; ++AI) {
3282       if (AI != BD->param_begin()) S += ", ";
3283       ParamStr = (*AI)->getNameAsString();
3284       QualType QT = (*AI)->getType();
3285       (void)convertBlockPointerToFunctionPointer(QT);
3286       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3287       S += ParamStr;
3288     }
3289     if (FT->isVariadic()) {
3290       if (!BD->param_empty()) S += ", ";
3291       S += "...";
3292     }
3293     S += ')';
3294   }
3295   S += " {\n";
3296 
3297   // Create local declarations to avoid rewriting all closure decl ref exprs.
3298   // First, emit a declaration for all "by ref" decls.
3299   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3300        E = BlockByRefDecls.end(); I != E; ++I) {
3301     S += "  ";
3302     std::string Name = (*I)->getNameAsString();
3303     std::string TypeString;
3304     RewriteByRefString(TypeString, Name, (*I));
3305     TypeString += " *";
3306     Name = TypeString + Name;
3307     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3308   }
3309   // Next, emit a declaration for all "by copy" declarations.
3310   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3311        E = BlockByCopyDecls.end(); I != E; ++I) {
3312     S += "  ";
3313     // Handle nested closure invocation. For example:
3314     //
3315     //   void (^myImportedClosure)(void);
3316     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3317     //
3318     //   void (^anotherClosure)(void);
3319     //   anotherClosure = ^(void) {
3320     //     myImportedClosure(); // import and invoke the closure
3321     //   };
3322     //
3323     if (isTopLevelBlockPointerType((*I)->getType())) {
3324       RewriteBlockPointerTypeVariable(S, (*I));
3325       S += " = (";
3326       RewriteBlockPointerType(S, (*I)->getType());
3327       S += ")";
3328       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3329     }
3330     else {
3331       std::string Name = (*I)->getNameAsString();
3332       QualType QT = (*I)->getType();
3333       if (HasLocalVariableExternalStorage(*I))
3334         QT = Context->getPointerType(QT);
3335       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3336       S += Name + " = __cself->" +
3337                               (*I)->getNameAsString() + "; // bound by copy\n";
3338     }
3339   }
3340   std::string RewrittenStr = RewrittenBlockExprs[CE];
3341   const char *cstr = RewrittenStr.c_str();
3342   while (*cstr++ != '{') ;
3343   S += cstr;
3344   S += "\n";
3345   return S;
3346 }
3347 
3348 std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3349                                                    StringRef funcName,
3350                                                    std::string Tag) {
3351   std::string StructRef = "struct " + Tag;
3352   std::string S = "static void __";
3353 
3354   S += funcName;
3355   S += "_block_copy_" + utostr(i);
3356   S += "(" + StructRef;
3357   S += "*dst, " + StructRef;
3358   S += "*src) {";
3359   for (ValueDecl *VD : ImportedBlockDecls) {
3360     S += "_Block_object_assign((void*)&dst->";
3361     S += VD->getNameAsString();
3362     S += ", (void*)src->";
3363     S += VD->getNameAsString();
3364     if (BlockByRefDeclsPtrSet.count(VD))
3365       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3366     else if (VD->getType()->isBlockPointerType())
3367       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3368     else
3369       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3370   }
3371   S += "}\n";
3372 
3373   S += "\nstatic void __";
3374   S += funcName;
3375   S += "_block_dispose_" + utostr(i);
3376   S += "(" + StructRef;
3377   S += "*src) {";
3378   for (ValueDecl *VD : ImportedBlockDecls) {
3379     S += "_Block_object_dispose((void*)src->";
3380     S += VD->getNameAsString();
3381     if (BlockByRefDeclsPtrSet.count(VD))
3382       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3383     else if (VD->getType()->isBlockPointerType())
3384       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3385     else
3386       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3387   }
3388   S += "}\n";
3389   return S;
3390 }
3391 
3392 std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3393                                              std::string Desc) {
3394   std::string S = "\nstruct " + Tag;
3395   std::string Constructor = "  " + Tag;
3396 
3397   S += " {\n  struct __block_impl impl;\n";
3398   S += "  struct " + Desc;
3399   S += "* Desc;\n";
3400 
3401   Constructor += "(void *fp, "; // Invoke function pointer.
3402   Constructor += "struct " + Desc; // Descriptor pointer.
3403   Constructor += " *desc";
3404 
3405   if (BlockDeclRefs.size()) {
3406     // Output all "by copy" declarations.
3407     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3408          E = BlockByCopyDecls.end(); I != E; ++I) {
3409       S += "  ";
3410       std::string FieldName = (*I)->getNameAsString();
3411       std::string ArgName = "_" + FieldName;
3412       // Handle nested closure invocation. For example:
3413       //
3414       //   void (^myImportedBlock)(void);
3415       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3416       //
3417       //   void (^anotherBlock)(void);
3418       //   anotherBlock = ^(void) {
3419       //     myImportedBlock(); // import and invoke the closure
3420       //   };
3421       //
3422       if (isTopLevelBlockPointerType((*I)->getType())) {
3423         S += "struct __block_impl *";
3424         Constructor += ", void *" + ArgName;
3425       } else {
3426         QualType QT = (*I)->getType();
3427         if (HasLocalVariableExternalStorage(*I))
3428           QT = Context->getPointerType(QT);
3429         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3430         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3431         Constructor += ", " + ArgName;
3432       }
3433       S += FieldName + ";\n";
3434     }
3435     // Output all "by ref" declarations.
3436     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3437          E = BlockByRefDecls.end(); I != E; ++I) {
3438       S += "  ";
3439       std::string FieldName = (*I)->getNameAsString();
3440       std::string ArgName = "_" + FieldName;
3441       {
3442         std::string TypeString;
3443         RewriteByRefString(TypeString, FieldName, (*I));
3444         TypeString += " *";
3445         FieldName = TypeString + FieldName;
3446         ArgName = TypeString + ArgName;
3447         Constructor += ", " + ArgName;
3448       }
3449       S += FieldName + "; // by ref\n";
3450     }
3451     // Finish writing the constructor.
3452     Constructor += ", int flags=0)";
3453     // Initialize all "by copy" arguments.
3454     bool firsTime = true;
3455     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3456          E = BlockByCopyDecls.end(); I != E; ++I) {
3457       std::string Name = (*I)->getNameAsString();
3458         if (firsTime) {
3459           Constructor += " : ";
3460           firsTime = false;
3461         }
3462         else
3463           Constructor += ", ";
3464         if (isTopLevelBlockPointerType((*I)->getType()))
3465           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3466         else
3467           Constructor += Name + "(_" + Name + ")";
3468     }
3469     // Initialize all "by ref" arguments.
3470     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3471          E = BlockByRefDecls.end(); I != E; ++I) {
3472       std::string Name = (*I)->getNameAsString();
3473       if (firsTime) {
3474         Constructor += " : ";
3475         firsTime = false;
3476       }
3477       else
3478         Constructor += ", ";
3479       Constructor += Name + "(_" + Name + "->__forwarding)";
3480     }
3481 
3482     Constructor += " {\n";
3483     if (GlobalVarDecl)
3484       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3485     else
3486       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3487     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3488 
3489     Constructor += "    Desc = desc;\n";
3490   } else {
3491     // Finish writing the constructor.
3492     Constructor += ", int flags=0) {\n";
3493     if (GlobalVarDecl)
3494       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3495     else
3496       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3497     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3498     Constructor += "    Desc = desc;\n";
3499   }
3500   Constructor += "  ";
3501   Constructor += "}\n";
3502   S += Constructor;
3503   S += "};\n";
3504   return S;
3505 }
3506 
3507 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3508                                                    std::string ImplTag, int i,
3509                                                    StringRef FunName,
3510                                                    unsigned hasCopy) {
3511   std::string S = "\nstatic struct " + DescTag;
3512 
3513   S += " {\n  unsigned long reserved;\n";
3514   S += "  unsigned long Block_size;\n";
3515   if (hasCopy) {
3516     S += "  void (*copy)(struct ";
3517     S += ImplTag; S += "*, struct ";
3518     S += ImplTag; S += "*);\n";
3519 
3520     S += "  void (*dispose)(struct ";
3521     S += ImplTag; S += "*);\n";
3522   }
3523   S += "} ";
3524 
3525   S += DescTag + "_DATA = { 0, sizeof(struct ";
3526   S += ImplTag + ")";
3527   if (hasCopy) {
3528     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3529     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3530   }
3531   S += "};\n";
3532   return S;
3533 }
3534 
3535 void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3536                                           StringRef FunName) {
3537   // Insert declaration for the function in which block literal is used.
3538   if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3539     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3540   bool RewriteSC = (GlobalVarDecl &&
3541                     !Blocks.empty() &&
3542                     GlobalVarDecl->getStorageClass() == SC_Static &&
3543                     GlobalVarDecl->getType().getCVRQualifiers());
3544   if (RewriteSC) {
3545     std::string SC(" void __");
3546     SC += GlobalVarDecl->getNameAsString();
3547     SC += "() {}";
3548     InsertText(FunLocStart, SC);
3549   }
3550 
3551   // Insert closures that were part of the function.
3552   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3553     CollectBlockDeclRefInfo(Blocks[i]);
3554     // Need to copy-in the inner copied-in variables not actually used in this
3555     // block.
3556     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3557       DeclRefExpr *Exp = InnerDeclRefs[count++];
3558       ValueDecl *VD = Exp->getDecl();
3559       BlockDeclRefs.push_back(Exp);
3560       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3561         BlockByCopyDeclsPtrSet.insert(VD);
3562         BlockByCopyDecls.push_back(VD);
3563       }
3564       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3565         BlockByRefDeclsPtrSet.insert(VD);
3566         BlockByRefDecls.push_back(VD);
3567       }
3568       // imported objects in the inner blocks not used in the outer
3569       // blocks must be copied/disposed in the outer block as well.
3570       if (VD->hasAttr<BlocksAttr>() ||
3571           VD->getType()->isObjCObjectPointerType() ||
3572           VD->getType()->isBlockPointerType())
3573         ImportedBlockDecls.insert(VD);
3574     }
3575 
3576     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3577     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3578 
3579     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3580 
3581     InsertText(FunLocStart, CI);
3582 
3583     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3584 
3585     InsertText(FunLocStart, CF);
3586 
3587     if (ImportedBlockDecls.size()) {
3588       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3589       InsertText(FunLocStart, HF);
3590     }
3591     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3592                                                ImportedBlockDecls.size() > 0);
3593     InsertText(FunLocStart, BD);
3594 
3595     BlockDeclRefs.clear();
3596     BlockByRefDecls.clear();
3597     BlockByRefDeclsPtrSet.clear();
3598     BlockByCopyDecls.clear();
3599     BlockByCopyDeclsPtrSet.clear();
3600     ImportedBlockDecls.clear();
3601   }
3602   if (RewriteSC) {
3603     // Must insert any 'const/volatile/static here. Since it has been
3604     // removed as result of rewriting of block literals.
3605     std::string SC;
3606     if (GlobalVarDecl->getStorageClass() == SC_Static)
3607       SC = "static ";
3608     if (GlobalVarDecl->getType().isConstQualified())
3609       SC += "const ";
3610     if (GlobalVarDecl->getType().isVolatileQualified())
3611       SC += "volatile ";
3612     if (GlobalVarDecl->getType().isRestrictQualified())
3613       SC += "restrict ";
3614     InsertText(FunLocStart, SC);
3615   }
3616 
3617   Blocks.clear();
3618   InnerDeclRefsCount.clear();
3619   InnerDeclRefs.clear();
3620   RewrittenBlockExprs.clear();
3621 }
3622 
3623 void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3624   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3625   StringRef FuncName = FD->getName();
3626 
3627   SynthesizeBlockLiterals(FunLocStart, FuncName);
3628 }
3629 
3630 static void BuildUniqueMethodName(std::string &Name,
3631                                   ObjCMethodDecl *MD) {
3632   ObjCInterfaceDecl *IFace = MD->getClassInterface();
3633   Name = std::string(IFace->getName());
3634   Name += "__" + MD->getSelector().getAsString();
3635   // Convert colons to underscores.
3636   std::string::size_type loc = 0;
3637   while ((loc = Name.find(':', loc)) != std::string::npos)
3638     Name.replace(loc, 1, "_");
3639 }
3640 
3641 void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3642   // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3643   // SourceLocation FunLocStart = MD->getBeginLoc();
3644   SourceLocation FunLocStart = MD->getBeginLoc();
3645   std::string FuncName;
3646   BuildUniqueMethodName(FuncName, MD);
3647   SynthesizeBlockLiterals(FunLocStart, FuncName);
3648 }
3649 
3650 void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3651   for (Stmt *SubStmt : S->children())
3652     if (SubStmt) {
3653       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3654         GetBlockDeclRefExprs(CBE->getBody());
3655       else
3656         GetBlockDeclRefExprs(SubStmt);
3657     }
3658   // Handle specific things.
3659   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3660     if (DRE->refersToEnclosingVariableOrCapture() ||
3661         HasLocalVariableExternalStorage(DRE->getDecl()))
3662       // FIXME: Handle enums.
3663       BlockDeclRefs.push_back(DRE);
3664 }
3665 
3666 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3667                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3668                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3669   for (Stmt *SubStmt : S->children())
3670     if (SubStmt) {
3671       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3672         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3673         GetInnerBlockDeclRefExprs(CBE->getBody(),
3674                                   InnerBlockDeclRefs,
3675                                   InnerContexts);
3676       }
3677       else
3678         GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3679     }
3680   // Handle specific things.
3681   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3682     if (DRE->refersToEnclosingVariableOrCapture() ||
3683         HasLocalVariableExternalStorage(DRE->getDecl())) {
3684       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3685         InnerBlockDeclRefs.push_back(DRE);
3686       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3687         if (Var->isFunctionOrMethodVarDecl())
3688           ImportedLocalExternalDecls.insert(Var);
3689     }
3690   }
3691 }
3692 
3693 /// convertFunctionTypeOfBlocks - This routine converts a function type
3694 /// whose result type may be a block pointer or whose argument type(s)
3695 /// might be block pointers to an equivalent function type replacing
3696 /// all block pointers to function pointers.
3697 QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3698   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3699   // FTP will be null for closures that don't take arguments.
3700   // Generate a funky cast.
3701   SmallVector<QualType, 8> ArgTypes;
3702   QualType Res = FT->getReturnType();
3703   bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3704 
3705   if (FTP) {
3706     for (auto &I : FTP->param_types()) {
3707       QualType t = I;
3708       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3709       if (convertBlockPointerToFunctionPointer(t))
3710         HasBlockType = true;
3711       ArgTypes.push_back(t);
3712     }
3713   }
3714   QualType FuncType;
3715   // FIXME. Does this work if block takes no argument but has a return type
3716   // which is of block type?
3717   if (HasBlockType)
3718     FuncType = getSimpleFunctionType(Res, ArgTypes);
3719   else FuncType = QualType(FT, 0);
3720   return FuncType;
3721 }
3722 
3723 Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3724   // Navigate to relevant type information.
3725   const BlockPointerType *CPT = nullptr;
3726 
3727   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3728     CPT = DRE->getType()->getAs<BlockPointerType>();
3729   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3730     CPT = MExpr->getType()->getAs<BlockPointerType>();
3731   }
3732   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3733     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3734   }
3735   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3736     CPT = IEXPR->getType()->getAs<BlockPointerType>();
3737   else if (const ConditionalOperator *CEXPR =
3738             dyn_cast<ConditionalOperator>(BlockExp)) {
3739     Expr *LHSExp = CEXPR->getLHS();
3740     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3741     Expr *RHSExp = CEXPR->getRHS();
3742     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3743     Expr *CONDExp = CEXPR->getCond();
3744     ConditionalOperator *CondExpr =
3745       new (Context) ConditionalOperator(CONDExp,
3746                                       SourceLocation(), cast<Expr>(LHSStmt),
3747                                       SourceLocation(), cast<Expr>(RHSStmt),
3748                                       Exp->getType(), VK_RValue, OK_Ordinary);
3749     return CondExpr;
3750   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3751     CPT = IRE->getType()->getAs<BlockPointerType>();
3752   } else if (const PseudoObjectExpr *POE
3753                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3754     CPT = POE->getType()->castAs<BlockPointerType>();
3755   } else {
3756     assert(false && "RewriteBlockClass: Bad type");
3757   }
3758   assert(CPT && "RewriteBlockClass: Bad type");
3759   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3760   assert(FT && "RewriteBlockClass: Bad type");
3761   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3762   // FTP will be null for closures that don't take arguments.
3763 
3764   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3765                                       SourceLocation(), SourceLocation(),
3766                                       &Context->Idents.get("__block_impl"));
3767   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3768 
3769   // Generate a funky cast.
3770   SmallVector<QualType, 8> ArgTypes;
3771 
3772   // Push the block argument type.
3773   ArgTypes.push_back(PtrBlock);
3774   if (FTP) {
3775     for (auto &I : FTP->param_types()) {
3776       QualType t = I;
3777       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3778       if (!convertBlockPointerToFunctionPointer(t))
3779         convertToUnqualifiedObjCType(t);
3780       ArgTypes.push_back(t);
3781     }
3782   }
3783   // Now do the pointer to function cast.
3784   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3785 
3786   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3787 
3788   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3789                                                CK_BitCast,
3790                                                const_cast<Expr*>(BlockExp));
3791   // Don't forget the parens to enforce the proper binding.
3792   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3793                                           BlkCast);
3794   //PE->dump();
3795 
3796   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3797                                     SourceLocation(),
3798                                     &Context->Idents.get("FuncPtr"),
3799                                     Context->VoidPtrTy, nullptr,
3800                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3801                                     ICIS_NoInit);
3802   MemberExpr *ME = MemberExpr::CreateImplicit(
3803       *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
3804 
3805   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3806                                                 CK_BitCast, ME);
3807   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3808 
3809   SmallVector<Expr*, 8> BlkExprs;
3810   // Add the implicit argument.
3811   BlkExprs.push_back(BlkCast);
3812   // Add the user arguments.
3813   for (CallExpr::arg_iterator I = Exp->arg_begin(),
3814        E = Exp->arg_end(); I != E; ++I) {
3815     BlkExprs.push_back(*I);
3816   }
3817   CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
3818                                   VK_RValue, SourceLocation());
3819   return CE;
3820 }
3821 
3822 // We need to return the rewritten expression to handle cases where the
3823 // BlockDeclRefExpr is embedded in another expression being rewritten.
3824 // For example:
3825 //
3826 // int main() {
3827 //    __block Foo *f;
3828 //    __block int i;
3829 //
3830 //    void (^myblock)() = ^() {
3831 //        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3832 //        i = 77;
3833 //    };
3834 //}
3835 Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3836   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3837   // for each DeclRefExp where BYREFVAR is name of the variable.
3838   ValueDecl *VD = DeclRefExp->getDecl();
3839   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3840                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3841 
3842   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3843                                     SourceLocation(),
3844                                     &Context->Idents.get("__forwarding"),
3845                                     Context->VoidPtrTy, nullptr,
3846                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3847                                     ICIS_NoInit);
3848   MemberExpr *ME =
3849       MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
3850                                  FD->getType(), VK_LValue, OK_Ordinary);
3851 
3852   StringRef Name = VD->getName();
3853   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3854                          &Context->Idents.get(Name),
3855                          Context->VoidPtrTy, nullptr,
3856                          /*BitWidth=*/nullptr, /*Mutable=*/true,
3857                          ICIS_NoInit);
3858   ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
3859                                   VK_LValue, OK_Ordinary);
3860 
3861   // Need parens to enforce precedence.
3862   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3863                                           DeclRefExp->getExprLoc(),
3864                                           ME);
3865   ReplaceStmt(DeclRefExp, PE);
3866   return PE;
3867 }
3868 
3869 // Rewrites the imported local variable V with external storage
3870 // (static, extern, etc.) as *V
3871 //
3872 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3873   ValueDecl *VD = DRE->getDecl();
3874   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3875     if (!ImportedLocalExternalDecls.count(Var))
3876       return DRE;
3877   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3878                                           VK_LValue, OK_Ordinary,
3879                                           DRE->getLocation(), false);
3880   // Need parens to enforce precedence.
3881   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3882                                           Exp);
3883   ReplaceStmt(DRE, PE);
3884   return PE;
3885 }
3886 
3887 void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3888   SourceLocation LocStart = CE->getLParenLoc();
3889   SourceLocation LocEnd = CE->getRParenLoc();
3890 
3891   // Need to avoid trying to rewrite synthesized casts.
3892   if (LocStart.isInvalid())
3893     return;
3894   // Need to avoid trying to rewrite casts contained in macros.
3895   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3896     return;
3897 
3898   const char *startBuf = SM->getCharacterData(LocStart);
3899   const char *endBuf = SM->getCharacterData(LocEnd);
3900   QualType QT = CE->getType();
3901   const Type* TypePtr = QT->getAs<Type>();
3902   if (isa<TypeOfExprType>(TypePtr)) {
3903     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3904     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3905     std::string TypeAsString = "(";
3906     RewriteBlockPointerType(TypeAsString, QT);
3907     TypeAsString += ")";
3908     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3909     return;
3910   }
3911   // advance the location to startArgList.
3912   const char *argPtr = startBuf;
3913 
3914   while (*argPtr++ && (argPtr < endBuf)) {
3915     switch (*argPtr) {
3916     case '^':
3917       // Replace the '^' with '*'.
3918       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3919       ReplaceText(LocStart, 1, "*");
3920       break;
3921     }
3922   }
3923 }
3924 
3925 void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3926   SourceLocation DeclLoc = FD->getLocation();
3927   unsigned parenCount = 0;
3928 
3929   // We have 1 or more arguments that have closure pointers.
3930   const char *startBuf = SM->getCharacterData(DeclLoc);
3931   const char *startArgList = strchr(startBuf, '(');
3932 
3933   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3934 
3935   parenCount++;
3936   // advance the location to startArgList.
3937   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3938   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3939 
3940   const char *argPtr = startArgList;
3941 
3942   while (*argPtr++ && parenCount) {
3943     switch (*argPtr) {
3944     case '^':
3945       // Replace the '^' with '*'.
3946       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3947       ReplaceText(DeclLoc, 1, "*");
3948       break;
3949     case '(':
3950       parenCount++;
3951       break;
3952     case ')':
3953       parenCount--;
3954       break;
3955     }
3956   }
3957 }
3958 
3959 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3960   const FunctionProtoType *FTP;
3961   const PointerType *PT = QT->getAs<PointerType>();
3962   if (PT) {
3963     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3964   } else {
3965     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3966     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3967     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3968   }
3969   if (FTP) {
3970     for (const auto &I : FTP->param_types())
3971       if (isTopLevelBlockPointerType(I))
3972         return true;
3973   }
3974   return false;
3975 }
3976 
3977 bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3978   const FunctionProtoType *FTP;
3979   const PointerType *PT = QT->getAs<PointerType>();
3980   if (PT) {
3981     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3982   } else {
3983     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3984     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3985     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3986   }
3987   if (FTP) {
3988     for (const auto &I : FTP->param_types()) {
3989       if (I->isObjCQualifiedIdType())
3990         return true;
3991       if (I->isObjCObjectPointerType() &&
3992           I->getPointeeType()->isObjCQualifiedInterfaceType())
3993         return true;
3994     }
3995 
3996   }
3997   return false;
3998 }
3999 
4000 void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4001                                      const char *&RParen) {
4002   const char *argPtr = strchr(Name, '(');
4003   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4004 
4005   LParen = argPtr; // output the start.
4006   argPtr++; // skip past the left paren.
4007   unsigned parenCount = 1;
4008 
4009   while (*argPtr && parenCount) {
4010     switch (*argPtr) {
4011     case '(': parenCount++; break;
4012     case ')': parenCount--; break;
4013     default: break;
4014     }
4015     if (parenCount) argPtr++;
4016   }
4017   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4018   RParen = argPtr; // output the end
4019 }
4020 
4021 void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4022   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4023     RewriteBlockPointerFunctionArgs(FD);
4024     return;
4025   }
4026   // Handle Variables and Typedefs.
4027   SourceLocation DeclLoc = ND->getLocation();
4028   QualType DeclT;
4029   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4030     DeclT = VD->getType();
4031   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4032     DeclT = TDD->getUnderlyingType();
4033   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4034     DeclT = FD->getType();
4035   else
4036     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4037 
4038   const char *startBuf = SM->getCharacterData(DeclLoc);
4039   const char *endBuf = startBuf;
4040   // scan backward (from the decl location) for the end of the previous decl.
4041   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4042     startBuf--;
4043   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4044   std::string buf;
4045   unsigned OrigLength=0;
4046   // *startBuf != '^' if we are dealing with a pointer to function that
4047   // may take block argument types (which will be handled below).
4048   if (*startBuf == '^') {
4049     // Replace the '^' with '*', computing a negative offset.
4050     buf = '*';
4051     startBuf++;
4052     OrigLength++;
4053   }
4054   while (*startBuf != ')') {
4055     buf += *startBuf;
4056     startBuf++;
4057     OrigLength++;
4058   }
4059   buf += ')';
4060   OrigLength++;
4061 
4062   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4063       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4064     // Replace the '^' with '*' for arguments.
4065     // Replace id<P> with id/*<>*/
4066     DeclLoc = ND->getLocation();
4067     startBuf = SM->getCharacterData(DeclLoc);
4068     const char *argListBegin, *argListEnd;
4069     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4070     while (argListBegin < argListEnd) {
4071       if (*argListBegin == '^')
4072         buf += '*';
4073       else if (*argListBegin ==  '<') {
4074         buf += "/*";
4075         buf += *argListBegin++;
4076         OrigLength++;
4077         while (*argListBegin != '>') {
4078           buf += *argListBegin++;
4079           OrigLength++;
4080         }
4081         buf += *argListBegin;
4082         buf += "*/";
4083       }
4084       else
4085         buf += *argListBegin;
4086       argListBegin++;
4087       OrigLength++;
4088     }
4089     buf += ')';
4090     OrigLength++;
4091   }
4092   ReplaceText(Start, OrigLength, buf);
4093 }
4094 
4095 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4096 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4097 ///                    struct Block_byref_id_object *src) {
4098 ///  _Block_object_assign (&_dest->object, _src->object,
4099 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4100 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4101 ///  _Block_object_assign(&_dest->object, _src->object,
4102 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4103 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4104 /// }
4105 /// And:
4106 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4107 ///  _Block_object_dispose(_src->object,
4108 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4109 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4110 ///  _Block_object_dispose(_src->object,
4111 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4112 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4113 /// }
4114 
4115 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4116                                                           int flag) {
4117   std::string S;
4118   if (CopyDestroyCache.count(flag))
4119     return S;
4120   CopyDestroyCache.insert(flag);
4121   S = "static void __Block_byref_id_object_copy_";
4122   S += utostr(flag);
4123   S += "(void *dst, void *src) {\n";
4124 
4125   // offset into the object pointer is computed as:
4126   // void * + void* + int + int + void* + void *
4127   unsigned IntSize =
4128   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4129   unsigned VoidPtrSize =
4130   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4131 
4132   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4133   S += " _Block_object_assign((char*)dst + ";
4134   S += utostr(offset);
4135   S += ", *(void * *) ((char*)src + ";
4136   S += utostr(offset);
4137   S += "), ";
4138   S += utostr(flag);
4139   S += ");\n}\n";
4140 
4141   S += "static void __Block_byref_id_object_dispose_";
4142   S += utostr(flag);
4143   S += "(void *src) {\n";
4144   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4145   S += utostr(offset);
4146   S += "), ";
4147   S += utostr(flag);
4148   S += ");\n}\n";
4149   return S;
4150 }
4151 
4152 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4153 /// the declaration into:
4154 /// struct __Block_byref_ND {
4155 /// void *__isa;                  // NULL for everything except __weak pointers
4156 /// struct __Block_byref_ND *__forwarding;
4157 /// int32_t __flags;
4158 /// int32_t __size;
4159 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4160 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4161 /// typex ND;
4162 /// };
4163 ///
4164 /// It then replaces declaration of ND variable with:
4165 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4166 ///                               __size=sizeof(struct __Block_byref_ND),
4167 ///                               ND=initializer-if-any};
4168 ///
4169 ///
4170 void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4171   // Insert declaration for the function in which block literal is
4172   // used.
4173   if (CurFunctionDeclToDeclareForBlock)
4174     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4175   int flag = 0;
4176   int isa = 0;
4177   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4178   if (DeclLoc.isInvalid())
4179     // If type location is missing, it is because of missing type (a warning).
4180     // Use variable's location which is good for this case.
4181     DeclLoc = ND->getLocation();
4182   const char *startBuf = SM->getCharacterData(DeclLoc);
4183   SourceLocation X = ND->getEndLoc();
4184   X = SM->getExpansionLoc(X);
4185   const char *endBuf = SM->getCharacterData(X);
4186   std::string Name(ND->getNameAsString());
4187   std::string ByrefType;
4188   RewriteByRefString(ByrefType, Name, ND, true);
4189   ByrefType += " {\n";
4190   ByrefType += "  void *__isa;\n";
4191   RewriteByRefString(ByrefType, Name, ND);
4192   ByrefType += " *__forwarding;\n";
4193   ByrefType += " int __flags;\n";
4194   ByrefType += " int __size;\n";
4195   // Add void *__Block_byref_id_object_copy;
4196   // void *__Block_byref_id_object_dispose; if needed.
4197   QualType Ty = ND->getType();
4198   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4199   if (HasCopyAndDispose) {
4200     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4201     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4202   }
4203 
4204   QualType T = Ty;
4205   (void)convertBlockPointerToFunctionPointer(T);
4206   T.getAsStringInternal(Name, Context->getPrintingPolicy());
4207 
4208   ByrefType += " " + Name + ";\n";
4209   ByrefType += "};\n";
4210   // Insert this type in global scope. It is needed by helper function.
4211   SourceLocation FunLocStart;
4212   if (CurFunctionDef)
4213      FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4214   else {
4215     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4216     FunLocStart = CurMethodDef->getBeginLoc();
4217   }
4218   InsertText(FunLocStart, ByrefType);
4219   if (Ty.isObjCGCWeak()) {
4220     flag |= BLOCK_FIELD_IS_WEAK;
4221     isa = 1;
4222   }
4223 
4224   if (HasCopyAndDispose) {
4225     flag = BLOCK_BYREF_CALLER;
4226     QualType Ty = ND->getType();
4227     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4228     if (Ty->isBlockPointerType())
4229       flag |= BLOCK_FIELD_IS_BLOCK;
4230     else
4231       flag |= BLOCK_FIELD_IS_OBJECT;
4232     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4233     if (!HF.empty())
4234       InsertText(FunLocStart, HF);
4235   }
4236 
4237   // struct __Block_byref_ND ND =
4238   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4239   //  initializer-if-any};
4240   bool hasInit = (ND->getInit() != nullptr);
4241   unsigned flags = 0;
4242   if (HasCopyAndDispose)
4243     flags |= BLOCK_HAS_COPY_DISPOSE;
4244   Name = ND->getNameAsString();
4245   ByrefType.clear();
4246   RewriteByRefString(ByrefType, Name, ND);
4247   std::string ForwardingCastType("(");
4248   ForwardingCastType += ByrefType + " *)";
4249   if (!hasInit) {
4250     ByrefType += " " + Name + " = {(void*)";
4251     ByrefType += utostr(isa);
4252     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4253     ByrefType += utostr(flags);
4254     ByrefType += ", ";
4255     ByrefType += "sizeof(";
4256     RewriteByRefString(ByrefType, Name, ND);
4257     ByrefType += ")";
4258     if (HasCopyAndDispose) {
4259       ByrefType += ", __Block_byref_id_object_copy_";
4260       ByrefType += utostr(flag);
4261       ByrefType += ", __Block_byref_id_object_dispose_";
4262       ByrefType += utostr(flag);
4263     }
4264     ByrefType += "};\n";
4265     unsigned nameSize = Name.size();
4266     // for block or function pointer declaration. Name is already
4267     // part of the declaration.
4268     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4269       nameSize = 1;
4270     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4271   }
4272   else {
4273     SourceLocation startLoc;
4274     Expr *E = ND->getInit();
4275     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4276       startLoc = ECE->getLParenLoc();
4277     else
4278       startLoc = E->getBeginLoc();
4279     startLoc = SM->getExpansionLoc(startLoc);
4280     endBuf = SM->getCharacterData(startLoc);
4281     ByrefType += " " + Name;
4282     ByrefType += " = {(void*)";
4283     ByrefType += utostr(isa);
4284     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4285     ByrefType += utostr(flags);
4286     ByrefType += ", ";
4287     ByrefType += "sizeof(";
4288     RewriteByRefString(ByrefType, Name, ND);
4289     ByrefType += "), ";
4290     if (HasCopyAndDispose) {
4291       ByrefType += "__Block_byref_id_object_copy_";
4292       ByrefType += utostr(flag);
4293       ByrefType += ", __Block_byref_id_object_dispose_";
4294       ByrefType += utostr(flag);
4295       ByrefType += ", ";
4296     }
4297     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4298 
4299     // Complete the newly synthesized compound expression by inserting a right
4300     // curly brace before the end of the declaration.
4301     // FIXME: This approach avoids rewriting the initializer expression. It
4302     // also assumes there is only one declarator. For example, the following
4303     // isn't currently supported by this routine (in general):
4304     //
4305     // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4306     //
4307     const char *startInitializerBuf = SM->getCharacterData(startLoc);
4308     const char *semiBuf = strchr(startInitializerBuf, ';');
4309     assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4310     SourceLocation semiLoc =
4311       startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4312 
4313     InsertText(semiLoc, "}");
4314   }
4315 }
4316 
4317 void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4318   // Add initializers for any closure decl refs.
4319   GetBlockDeclRefExprs(Exp->getBody());
4320   if (BlockDeclRefs.size()) {
4321     // Unique all "by copy" declarations.
4322     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4323       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4324         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4325           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4326           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4327         }
4328       }
4329     // Unique all "by ref" declarations.
4330     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4331       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4332         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4333           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4334           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4335         }
4336       }
4337     // Find any imported blocks...they will need special attention.
4338     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4339       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4340           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4341           BlockDeclRefs[i]->getType()->isBlockPointerType())
4342         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4343   }
4344 }
4345 
4346 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4347   IdentifierInfo *ID = &Context->Idents.get(name);
4348   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4349   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4350                               SourceLocation(), ID, FType, nullptr, SC_Extern,
4351                               false, false);
4352 }
4353 
4354 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4355                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4356   const BlockDecl *block = Exp->getBlockDecl();
4357   Blocks.push_back(Exp);
4358 
4359   CollectBlockDeclRefInfo(Exp);
4360 
4361   // Add inner imported variables now used in current block.
4362  int countOfInnerDecls = 0;
4363   if (!InnerBlockDeclRefs.empty()) {
4364     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4365       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4366       ValueDecl *VD = Exp->getDecl();
4367       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4368       // We need to save the copied-in variables in nested
4369       // blocks because it is needed at the end for some of the API generations.
4370       // See SynthesizeBlockLiterals routine.
4371         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4372         BlockDeclRefs.push_back(Exp);
4373         BlockByCopyDeclsPtrSet.insert(VD);
4374         BlockByCopyDecls.push_back(VD);
4375       }
4376       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4377         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4378         BlockDeclRefs.push_back(Exp);
4379         BlockByRefDeclsPtrSet.insert(VD);
4380         BlockByRefDecls.push_back(VD);
4381       }
4382     }
4383     // Find any imported blocks...they will need special attention.
4384     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4385       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4386           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4387           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4388         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4389   }
4390   InnerDeclRefsCount.push_back(countOfInnerDecls);
4391 
4392   std::string FuncName;
4393 
4394   if (CurFunctionDef)
4395     FuncName = CurFunctionDef->getNameAsString();
4396   else if (CurMethodDef)
4397     BuildUniqueMethodName(FuncName, CurMethodDef);
4398   else if (GlobalVarDecl)
4399     FuncName = std::string(GlobalVarDecl->getNameAsString());
4400 
4401   std::string BlockNumber = utostr(Blocks.size()-1);
4402 
4403   std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4404   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4405 
4406   // Get a pointer to the function type so we can cast appropriately.
4407   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4408   QualType FType = Context->getPointerType(BFT);
4409 
4410   FunctionDecl *FD;
4411   Expr *NewRep;
4412 
4413   // Simulate a constructor call...
4414   FD = SynthBlockInitFunctionDecl(Tag);
4415   DeclRefExpr *DRE = new (Context)
4416       DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
4417 
4418   SmallVector<Expr*, 4> InitExprs;
4419 
4420   // Initialize the block function.
4421   FD = SynthBlockInitFunctionDecl(Func);
4422   DeclRefExpr *Arg = new (Context) DeclRefExpr(
4423       *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
4424   CastExpr *castExpr =
4425       NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
4426   InitExprs.push_back(castExpr);
4427 
4428   // Initialize the block descriptor.
4429   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4430 
4431   VarDecl *NewVD = VarDecl::Create(
4432       *Context, TUDecl, SourceLocation(), SourceLocation(),
4433       &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4434   UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4435       new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
4436                                 VK_LValue, SourceLocation()),
4437       UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
4438       OK_Ordinary, SourceLocation(), false);
4439   InitExprs.push_back(DescRefExpr);
4440 
4441   // Add initializers for any closure decl refs.
4442   if (BlockDeclRefs.size()) {
4443     Expr *Exp;
4444     // Output all "by copy" declarations.
4445     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4446          E = BlockByCopyDecls.end(); I != E; ++I) {
4447       if (isObjCType((*I)->getType())) {
4448         // FIXME: Conform to ABI ([[obj retain] autorelease]).
4449         FD = SynthBlockInitFunctionDecl((*I)->getName());
4450         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4451                                         VK_LValue, SourceLocation());
4452         if (HasLocalVariableExternalStorage(*I)) {
4453           QualType QT = (*I)->getType();
4454           QT = Context->getPointerType(QT);
4455           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4456                                             OK_Ordinary, SourceLocation(),
4457                                             false);
4458         }
4459       } else if (isTopLevelBlockPointerType((*I)->getType())) {
4460         FD = SynthBlockInitFunctionDecl((*I)->getName());
4461         Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4462                                         VK_LValue, SourceLocation());
4463         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
4464                                        Arg);
4465       } else {
4466         FD = SynthBlockInitFunctionDecl((*I)->getName());
4467         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4468                                         VK_LValue, SourceLocation());
4469         if (HasLocalVariableExternalStorage(*I)) {
4470           QualType QT = (*I)->getType();
4471           QT = Context->getPointerType(QT);
4472           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4473                                             OK_Ordinary, SourceLocation(),
4474                                             false);
4475         }
4476       }
4477       InitExprs.push_back(Exp);
4478     }
4479     // Output all "by ref" declarations.
4480     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4481          E = BlockByRefDecls.end(); I != E; ++I) {
4482       ValueDecl *ND = (*I);
4483       std::string Name(ND->getNameAsString());
4484       std::string RecName;
4485       RewriteByRefString(RecName, Name, ND, true);
4486       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4487                                                 + sizeof("struct"));
4488       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4489                                           SourceLocation(), SourceLocation(),
4490                                           II);
4491       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4492       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4493 
4494       FD = SynthBlockInitFunctionDecl((*I)->getName());
4495       Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4496                                       VK_LValue, SourceLocation());
4497       bool isNestedCapturedVar = false;
4498       if (block)
4499         for (const auto &CI : block->captures()) {
4500           const VarDecl *variable = CI.getVariable();
4501           if (variable == ND && CI.isNested()) {
4502             assert (CI.isByRef() &&
4503                     "SynthBlockInitExpr - captured block variable is not byref");
4504             isNestedCapturedVar = true;
4505             break;
4506           }
4507         }
4508       // captured nested byref variable has its address passed. Do not take
4509       // its address again.
4510       if (!isNestedCapturedVar)
4511         Exp = new (Context) UnaryOperator(
4512             Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_RValue,
4513             OK_Ordinary, SourceLocation(), false);
4514       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4515       InitExprs.push_back(Exp);
4516     }
4517   }
4518   if (ImportedBlockDecls.size()) {
4519     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4520     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4521     unsigned IntSize =
4522       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4523     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4524                                            Context->IntTy, SourceLocation());
4525     InitExprs.push_back(FlagExp);
4526   }
4527   NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4528                             SourceLocation());
4529   NewRep = new (Context) UnaryOperator(
4530       NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue,
4531       OK_Ordinary, SourceLocation(), false);
4532   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4533                                     NewRep);
4534   BlockDeclRefs.clear();
4535   BlockByRefDecls.clear();
4536   BlockByRefDeclsPtrSet.clear();
4537   BlockByCopyDecls.clear();
4538   BlockByCopyDeclsPtrSet.clear();
4539   ImportedBlockDecls.clear();
4540   return NewRep;
4541 }
4542 
4543 bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4544   if (const ObjCForCollectionStmt * CS =
4545       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4546         return CS->getElement() == DS;
4547   return false;
4548 }
4549 
4550 //===----------------------------------------------------------------------===//
4551 // Function Body / Expression rewriting
4552 //===----------------------------------------------------------------------===//
4553 
4554 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4555   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4556       isa<DoStmt>(S) || isa<ForStmt>(S))
4557     Stmts.push_back(S);
4558   else if (isa<ObjCForCollectionStmt>(S)) {
4559     Stmts.push_back(S);
4560     ObjCBcLabelNo.push_back(++BcLabelCount);
4561   }
4562 
4563   // Pseudo-object operations and ivar references need special
4564   // treatment because we're going to recursively rewrite them.
4565   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4566     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4567       return RewritePropertyOrImplicitSetter(PseudoOp);
4568     } else {
4569       return RewritePropertyOrImplicitGetter(PseudoOp);
4570     }
4571   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4572     return RewriteObjCIvarRefExpr(IvarRefExpr);
4573   }
4574 
4575   SourceRange OrigStmtRange = S->getSourceRange();
4576 
4577   // Perform a bottom up rewrite of all children.
4578   for (Stmt *&childStmt : S->children())
4579     if (childStmt) {
4580       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4581       if (newStmt) {
4582         childStmt = newStmt;
4583       }
4584     }
4585 
4586   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4587     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4588     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4589     InnerContexts.insert(BE->getBlockDecl());
4590     ImportedLocalExternalDecls.clear();
4591     GetInnerBlockDeclRefExprs(BE->getBody(),
4592                               InnerBlockDeclRefs, InnerContexts);
4593     // Rewrite the block body in place.
4594     Stmt *SaveCurrentBody = CurrentBody;
4595     CurrentBody = BE->getBody();
4596     PropParentMap = nullptr;
4597     // block literal on rhs of a property-dot-sytax assignment
4598     // must be replaced by its synthesize ast so getRewrittenText
4599     // works as expected. In this case, what actually ends up on RHS
4600     // is the blockTranscribed which is the helper function for the
4601     // block literal; as in: self.c = ^() {[ace ARR];};
4602     bool saveDisableReplaceStmt = DisableReplaceStmt;
4603     DisableReplaceStmt = false;
4604     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4605     DisableReplaceStmt = saveDisableReplaceStmt;
4606     CurrentBody = SaveCurrentBody;
4607     PropParentMap = nullptr;
4608     ImportedLocalExternalDecls.clear();
4609     // Now we snarf the rewritten text and stash it away for later use.
4610     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4611     RewrittenBlockExprs[BE] = Str;
4612 
4613     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4614 
4615     //blockTranscribed->dump();
4616     ReplaceStmt(S, blockTranscribed);
4617     return blockTranscribed;
4618   }
4619   // Handle specific things.
4620   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4621     return RewriteAtEncode(AtEncode);
4622 
4623   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4624     return RewriteAtSelector(AtSelector);
4625 
4626   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4627     return RewriteObjCStringLiteral(AtString);
4628 
4629   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4630 #if 0
4631     // Before we rewrite it, put the original message expression in a comment.
4632     SourceLocation startLoc = MessExpr->getBeginLoc();
4633     SourceLocation endLoc = MessExpr->getEndLoc();
4634 
4635     const char *startBuf = SM->getCharacterData(startLoc);
4636     const char *endBuf = SM->getCharacterData(endLoc);
4637 
4638     std::string messString;
4639     messString += "// ";
4640     messString.append(startBuf, endBuf-startBuf+1);
4641     messString += "\n";
4642 
4643     // FIXME: Missing definition of
4644     // InsertText(clang::SourceLocation, char const*, unsigned int).
4645     // InsertText(startLoc, messString);
4646     // Tried this, but it didn't work either...
4647     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4648 #endif
4649     return RewriteMessageExpr(MessExpr);
4650   }
4651 
4652   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4653     return RewriteObjCTryStmt(StmtTry);
4654 
4655   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4656     return RewriteObjCSynchronizedStmt(StmtTry);
4657 
4658   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4659     return RewriteObjCThrowStmt(StmtThrow);
4660 
4661   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4662     return RewriteObjCProtocolExpr(ProtocolExp);
4663 
4664   if (ObjCForCollectionStmt *StmtForCollection =
4665         dyn_cast<ObjCForCollectionStmt>(S))
4666     return RewriteObjCForCollectionStmt(StmtForCollection,
4667                                         OrigStmtRange.getEnd());
4668   if (BreakStmt *StmtBreakStmt =
4669       dyn_cast<BreakStmt>(S))
4670     return RewriteBreakStmt(StmtBreakStmt);
4671   if (ContinueStmt *StmtContinueStmt =
4672       dyn_cast<ContinueStmt>(S))
4673     return RewriteContinueStmt(StmtContinueStmt);
4674 
4675   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4676   // and cast exprs.
4677   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4678     // FIXME: What we're doing here is modifying the type-specifier that
4679     // precedes the first Decl.  In the future the DeclGroup should have
4680     // a separate type-specifier that we can rewrite.
4681     // NOTE: We need to avoid rewriting the DeclStmt if it is within
4682     // the context of an ObjCForCollectionStmt. For example:
4683     //   NSArray *someArray;
4684     //   for (id <FooProtocol> index in someArray) ;
4685     // This is because RewriteObjCForCollectionStmt() does textual rewriting
4686     // and it depends on the original text locations/positions.
4687     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4688       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4689 
4690     // Blocks rewrite rules.
4691     for (auto *SD : DS->decls()) {
4692       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4693         if (isTopLevelBlockPointerType(ND->getType()))
4694           RewriteBlockPointerDecl(ND);
4695         else if (ND->getType()->isFunctionPointerType())
4696           CheckFunctionPointerDecl(ND->getType(), ND);
4697         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4698           if (VD->hasAttr<BlocksAttr>()) {
4699             static unsigned uniqueByrefDeclCount = 0;
4700             assert(!BlockByRefDeclNo.count(ND) &&
4701               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4702             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4703             RewriteByRefVar(VD);
4704           }
4705           else
4706             RewriteTypeOfDecl(VD);
4707         }
4708       }
4709       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4710         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4711           RewriteBlockPointerDecl(TD);
4712         else if (TD->getUnderlyingType()->isFunctionPointerType())
4713           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4714       }
4715     }
4716   }
4717 
4718   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4719     RewriteObjCQualifiedInterfaceTypes(CE);
4720 
4721   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4722       isa<DoStmt>(S) || isa<ForStmt>(S)) {
4723     assert(!Stmts.empty() && "Statement stack is empty");
4724     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4725              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4726             && "Statement stack mismatch");
4727     Stmts.pop_back();
4728   }
4729   // Handle blocks rewriting.
4730   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4731     ValueDecl *VD = DRE->getDecl();
4732     if (VD->hasAttr<BlocksAttr>())
4733       return RewriteBlockDeclRefExpr(DRE);
4734     if (HasLocalVariableExternalStorage(VD))
4735       return RewriteLocalVariableExternalStorage(DRE);
4736   }
4737 
4738   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4739     if (CE->getCallee()->getType()->isBlockPointerType()) {
4740       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4741       ReplaceStmt(S, BlockCall);
4742       return BlockCall;
4743     }
4744   }
4745   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4746     RewriteCastExpr(CE);
4747   }
4748 #if 0
4749   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4750     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4751                                                    ICE->getSubExpr(),
4752                                                    SourceLocation());
4753     // Get the new text.
4754     std::string SStr;
4755     llvm::raw_string_ostream Buf(SStr);
4756     Replacement->printPretty(Buf);
4757     const std::string &Str = Buf.str();
4758 
4759     printf("CAST = %s\n", &Str[0]);
4760     InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
4761     delete S;
4762     return Replacement;
4763   }
4764 #endif
4765   // Return this stmt unmodified.
4766   return S;
4767 }
4768 
4769 void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4770   for (auto *FD : RD->fields()) {
4771     if (isTopLevelBlockPointerType(FD->getType()))
4772       RewriteBlockPointerDecl(FD);
4773     if (FD->getType()->isObjCQualifiedIdType() ||
4774         FD->getType()->isObjCQualifiedInterfaceType())
4775       RewriteObjCQualifiedInterfaceTypes(FD);
4776   }
4777 }
4778 
4779 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
4780 /// main file of the input.
4781 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4782   switch (D->getKind()) {
4783     case Decl::Function: {
4784       FunctionDecl *FD = cast<FunctionDecl>(D);
4785       if (FD->isOverloadedOperator())
4786         return;
4787 
4788       // Since function prototypes don't have ParmDecl's, we check the function
4789       // prototype. This enables us to rewrite function declarations and
4790       // definitions using the same code.
4791       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4792 
4793       if (!FD->isThisDeclarationADefinition())
4794         break;
4795 
4796       // FIXME: If this should support Obj-C++, support CXXTryStmt
4797       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4798         CurFunctionDef = FD;
4799         CurFunctionDeclToDeclareForBlock = FD;
4800         CurrentBody = Body;
4801         Body =
4802         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4803         FD->setBody(Body);
4804         CurrentBody = nullptr;
4805         if (PropParentMap) {
4806           delete PropParentMap;
4807           PropParentMap = nullptr;
4808         }
4809         // This synthesizes and inserts the block "impl" struct, invoke function,
4810         // and any copy/dispose helper functions.
4811         InsertBlockLiteralsWithinFunction(FD);
4812         CurFunctionDef = nullptr;
4813         CurFunctionDeclToDeclareForBlock = nullptr;
4814       }
4815       break;
4816     }
4817     case Decl::ObjCMethod: {
4818       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4819       if (CompoundStmt *Body = MD->getCompoundBody()) {
4820         CurMethodDef = MD;
4821         CurrentBody = Body;
4822         Body =
4823           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4824         MD->setBody(Body);
4825         CurrentBody = nullptr;
4826         if (PropParentMap) {
4827           delete PropParentMap;
4828           PropParentMap = nullptr;
4829         }
4830         InsertBlockLiteralsWithinMethod(MD);
4831         CurMethodDef = nullptr;
4832       }
4833       break;
4834     }
4835     case Decl::ObjCImplementation: {
4836       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4837       ClassImplementation.push_back(CI);
4838       break;
4839     }
4840     case Decl::ObjCCategoryImpl: {
4841       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4842       CategoryImplementation.push_back(CI);
4843       break;
4844     }
4845     case Decl::Var: {
4846       VarDecl *VD = cast<VarDecl>(D);
4847       RewriteObjCQualifiedInterfaceTypes(VD);
4848       if (isTopLevelBlockPointerType(VD->getType()))
4849         RewriteBlockPointerDecl(VD);
4850       else if (VD->getType()->isFunctionPointerType()) {
4851         CheckFunctionPointerDecl(VD->getType(), VD);
4852         if (VD->getInit()) {
4853           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4854             RewriteCastExpr(CE);
4855           }
4856         }
4857       } else if (VD->getType()->isRecordType()) {
4858         RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
4859         if (RD->isCompleteDefinition())
4860           RewriteRecordBody(RD);
4861       }
4862       if (VD->getInit()) {
4863         GlobalVarDecl = VD;
4864         CurrentBody = VD->getInit();
4865         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4866         CurrentBody = nullptr;
4867         if (PropParentMap) {
4868           delete PropParentMap;
4869           PropParentMap = nullptr;
4870         }
4871         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4872         GlobalVarDecl = nullptr;
4873 
4874         // This is needed for blocks.
4875         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4876             RewriteCastExpr(CE);
4877         }
4878       }
4879       break;
4880     }
4881     case Decl::TypeAlias:
4882     case Decl::Typedef: {
4883       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4884         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4885           RewriteBlockPointerDecl(TD);
4886         else if (TD->getUnderlyingType()->isFunctionPointerType())
4887           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4888       }
4889       break;
4890     }
4891     case Decl::CXXRecord:
4892     case Decl::Record: {
4893       RecordDecl *RD = cast<RecordDecl>(D);
4894       if (RD->isCompleteDefinition())
4895         RewriteRecordBody(RD);
4896       break;
4897     }
4898     default:
4899       break;
4900   }
4901   // Nothing yet.
4902 }
4903 
4904 void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4905   if (Diags.hasErrorOccurred())
4906     return;
4907 
4908   RewriteInclude();
4909 
4910   // Here's a great place to add any extra declarations that may be needed.
4911   // Write out meta data for each @protocol(<expr>).
4912   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4913     RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4914 
4915   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4916   if (ClassImplementation.size() || CategoryImplementation.size())
4917     RewriteImplementations();
4918 
4919   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4920   // we are done.
4921   if (const RewriteBuffer *RewriteBuf =
4922       Rewrite.getRewriteBufferFor(MainFileID)) {
4923     //printf("Changed:\n");
4924     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4925   } else {
4926     llvm::errs() << "No changes\n";
4927   }
4928 
4929   if (ClassImplementation.size() || CategoryImplementation.size() ||
4930       ProtocolExprDecls.size()) {
4931     // Rewrite Objective-c meta data*
4932     std::string ResultStr;
4933     RewriteMetaDataIntoBuffer(ResultStr);
4934     // Emit metadata.
4935     *OutFile << ResultStr;
4936   }
4937   OutFile->flush();
4938 }
4939 
4940 void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4941   InitializeCommon(context);
4942 
4943   // declaring objc_selector outside the parameter list removes a silly
4944   // scope related warning...
4945   if (IsHeader)
4946     Preamble = "#pragma once\n";
4947   Preamble += "struct objc_selector; struct objc_class;\n";
4948   Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4949   Preamble += "struct objc_object *superClass; ";
4950   if (LangOpts.MicrosoftExt) {
4951     // Add a constructor for creating temporary objects.
4952     Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4953     ": ";
4954     Preamble += "object(o), superClass(s) {} ";
4955   }
4956   Preamble += "};\n";
4957   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4958   Preamble += "typedef struct objc_object Protocol;\n";
4959   Preamble += "#define _REWRITER_typedef_Protocol\n";
4960   Preamble += "#endif\n";
4961   if (LangOpts.MicrosoftExt) {
4962     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4963     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4964   } else
4965     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4966   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4967   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4968   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4969   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4970   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4971   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4972   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4973   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4974   Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4975   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4976   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4977   Preamble += "(const char *);\n";
4978   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4979   Preamble += "(struct objc_class *);\n";
4980   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4981   Preamble += "(const char *);\n";
4982   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4983   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4984   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4985   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4986   Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4987   Preamble += "(struct objc_class *, struct objc_object *);\n";
4988   // @synchronized hooks.
4989   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4990   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4991   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4992   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4993   Preamble += "struct __objcFastEnumerationState {\n\t";
4994   Preamble += "unsigned long state;\n\t";
4995   Preamble += "void **itemsPtr;\n\t";
4996   Preamble += "unsigned long *mutationsPtr;\n\t";
4997   Preamble += "unsigned long extra[5];\n};\n";
4998   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
4999   Preamble += "#define __FASTENUMERATIONSTATE\n";
5000   Preamble += "#endif\n";
5001   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5002   Preamble += "struct __NSConstantStringImpl {\n";
5003   Preamble += "  int *isa;\n";
5004   Preamble += "  int flags;\n";
5005   Preamble += "  char *str;\n";
5006   Preamble += "  long length;\n";
5007   Preamble += "};\n";
5008   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5009   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5010   Preamble += "#else\n";
5011   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5012   Preamble += "#endif\n";
5013   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5014   Preamble += "#endif\n";
5015   // Blocks preamble.
5016   Preamble += "#ifndef BLOCK_IMPL\n";
5017   Preamble += "#define BLOCK_IMPL\n";
5018   Preamble += "struct __block_impl {\n";
5019   Preamble += "  void *isa;\n";
5020   Preamble += "  int Flags;\n";
5021   Preamble += "  int Reserved;\n";
5022   Preamble += "  void *FuncPtr;\n";
5023   Preamble += "};\n";
5024   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5025   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5026   Preamble += "extern \"C\" __declspec(dllexport) "
5027   "void _Block_object_assign(void *, const void *, const int);\n";
5028   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5029   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5030   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5031   Preamble += "#else\n";
5032   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5033   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5034   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5035   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5036   Preamble += "#endif\n";
5037   Preamble += "#endif\n";
5038   if (LangOpts.MicrosoftExt) {
5039     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5040     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5041     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5042     Preamble += "#define __attribute__(X)\n";
5043     Preamble += "#endif\n";
5044     Preamble += "#define __weak\n";
5045   }
5046   else {
5047     Preamble += "#define __block\n";
5048     Preamble += "#define __weak\n";
5049   }
5050   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5051   // as this avoids warning in any 64bit/32bit compilation model.
5052   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5053 }
5054 
5055 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
5056 /// ivar offset.
5057 void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5058                                                          std::string &Result) {
5059   if (ivar->isBitField()) {
5060     // FIXME: The hack below doesn't work for bitfields. For now, we simply
5061     // place all bitfields at offset 0.
5062     Result += "0";
5063   } else {
5064     Result += "__OFFSETOFIVAR__(struct ";
5065     Result += ivar->getContainingInterface()->getNameAsString();
5066     if (LangOpts.MicrosoftExt)
5067       Result += "_IMPL";
5068     Result += ", ";
5069     Result += ivar->getNameAsString();
5070     Result += ")";
5071   }
5072 }
5073 
5074 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5075 void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5076                             ObjCProtocolDecl *PDecl, StringRef prefix,
5077                             StringRef ClassName, std::string &Result) {
5078   static bool objc_protocol_methods = false;
5079 
5080   // Output struct protocol_methods holder of method selector and type.
5081   if (!objc_protocol_methods && PDecl->hasDefinition()) {
5082     /* struct protocol_methods {
5083      SEL _cmd;
5084      char *method_types;
5085      }
5086      */
5087     Result += "\nstruct _protocol_methods {\n";
5088     Result += "\tstruct objc_selector *_cmd;\n";
5089     Result += "\tchar *method_types;\n";
5090     Result += "};\n";
5091 
5092     objc_protocol_methods = true;
5093   }
5094   // Do not synthesize the protocol more than once.
5095   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5096     return;
5097 
5098   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5099     PDecl = Def;
5100 
5101   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5102     unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5103                                         PDecl->instmeth_end());
5104     /* struct _objc_protocol_method_list {
5105      int protocol_method_count;
5106      struct protocol_methods protocols[];
5107      }
5108      */
5109     Result += "\nstatic struct {\n";
5110     Result += "\tint protocol_method_count;\n";
5111     Result += "\tstruct _protocol_methods protocol_methods[";
5112     Result += utostr(NumMethods);
5113     Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5114     Result += PDecl->getNameAsString();
5115     Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5116     "{\n\t" + utostr(NumMethods) + "\n";
5117 
5118     // Output instance methods declared in this protocol.
5119     for (ObjCProtocolDecl::instmeth_iterator
5120          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5121          I != E; ++I) {
5122       if (I == PDecl->instmeth_begin())
5123         Result += "\t  ,{{(struct objc_selector *)\"";
5124       else
5125         Result += "\t  ,{(struct objc_selector *)\"";
5126       Result += (*I)->getSelector().getAsString();
5127       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5128       Result += "\", \"";
5129       Result += MethodTypeString;
5130       Result += "\"}\n";
5131     }
5132     Result += "\t }\n};\n";
5133   }
5134 
5135   // Output class methods declared in this protocol.
5136   unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5137                                       PDecl->classmeth_end());
5138   if (NumMethods > 0) {
5139     /* struct _objc_protocol_method_list {
5140      int protocol_method_count;
5141      struct protocol_methods protocols[];
5142      }
5143      */
5144     Result += "\nstatic struct {\n";
5145     Result += "\tint protocol_method_count;\n";
5146     Result += "\tstruct _protocol_methods protocol_methods[";
5147     Result += utostr(NumMethods);
5148     Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5149     Result += PDecl->getNameAsString();
5150     Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5151     "{\n\t";
5152     Result += utostr(NumMethods);
5153     Result += "\n";
5154 
5155     // Output instance methods declared in this protocol.
5156     for (ObjCProtocolDecl::classmeth_iterator
5157          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5158          I != E; ++I) {
5159       if (I == PDecl->classmeth_begin())
5160         Result += "\t  ,{{(struct objc_selector *)\"";
5161       else
5162         Result += "\t  ,{(struct objc_selector *)\"";
5163       Result += (*I)->getSelector().getAsString();
5164       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5165       Result += "\", \"";
5166       Result += MethodTypeString;
5167       Result += "\"}\n";
5168     }
5169     Result += "\t }\n};\n";
5170   }
5171 
5172   // Output:
5173   /* struct _objc_protocol {
5174    // Objective-C 1.0 extensions
5175    struct _objc_protocol_extension *isa;
5176    char *protocol_name;
5177    struct _objc_protocol **protocol_list;
5178    struct _objc_protocol_method_list *instance_methods;
5179    struct _objc_protocol_method_list *class_methods;
5180    };
5181    */
5182   static bool objc_protocol = false;
5183   if (!objc_protocol) {
5184     Result += "\nstruct _objc_protocol {\n";
5185     Result += "\tstruct _objc_protocol_extension *isa;\n";
5186     Result += "\tchar *protocol_name;\n";
5187     Result += "\tstruct _objc_protocol **protocol_list;\n";
5188     Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5189     Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5190     Result += "};\n";
5191 
5192     objc_protocol = true;
5193   }
5194 
5195   Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5196   Result += PDecl->getNameAsString();
5197   Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5198   "{\n\t0, \"";
5199   Result += PDecl->getNameAsString();
5200   Result += "\", 0, ";
5201   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5202     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5203     Result += PDecl->getNameAsString();
5204     Result += ", ";
5205   }
5206   else
5207     Result += "0, ";
5208   if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5209     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5210     Result += PDecl->getNameAsString();
5211     Result += "\n";
5212   }
5213   else
5214     Result += "0\n";
5215   Result += "};\n";
5216 
5217   // Mark this protocol as having been generated.
5218   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5219     llvm_unreachable("protocol already synthesized");
5220 }
5221 
5222 void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5223                                 const ObjCList<ObjCProtocolDecl> &Protocols,
5224                                 StringRef prefix, StringRef ClassName,
5225                                 std::string &Result) {
5226   if (Protocols.empty()) return;
5227 
5228   for (unsigned i = 0; i != Protocols.size(); i++)
5229     RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5230 
5231   // Output the top lovel protocol meta-data for the class.
5232   /* struct _objc_protocol_list {
5233    struct _objc_protocol_list *next;
5234    int    protocol_count;
5235    struct _objc_protocol *class_protocols[];
5236    }
5237    */
5238   Result += "\nstatic struct {\n";
5239   Result += "\tstruct _objc_protocol_list *next;\n";
5240   Result += "\tint    protocol_count;\n";
5241   Result += "\tstruct _objc_protocol *class_protocols[";
5242   Result += utostr(Protocols.size());
5243   Result += "];\n} _OBJC_";
5244   Result += prefix;
5245   Result += "_PROTOCOLS_";
5246   Result += ClassName;
5247   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5248   "{\n\t0, ";
5249   Result += utostr(Protocols.size());
5250   Result += "\n";
5251 
5252   Result += "\t,{&_OBJC_PROTOCOL_";
5253   Result += Protocols[0]->getNameAsString();
5254   Result += " \n";
5255 
5256   for (unsigned i = 1; i != Protocols.size(); i++) {
5257     Result += "\t ,&_OBJC_PROTOCOL_";
5258     Result += Protocols[i]->getNameAsString();
5259     Result += "\n";
5260   }
5261   Result += "\t }\n};\n";
5262 }
5263 
5264 void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5265                                            std::string &Result) {
5266   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5267 
5268   // Explicitly declared @interface's are already synthesized.
5269   if (CDecl->isImplicitInterfaceDecl()) {
5270     // FIXME: Implementation of a class with no @interface (legacy) does not
5271     // produce correct synthesis as yet.
5272     RewriteObjCInternalStruct(CDecl, Result);
5273   }
5274 
5275   // Build _objc_ivar_list metadata for classes ivars if needed
5276   unsigned NumIvars = !IDecl->ivar_empty()
5277   ? IDecl->ivar_size()
5278   : (CDecl ? CDecl->ivar_size() : 0);
5279   if (NumIvars > 0) {
5280     static bool objc_ivar = false;
5281     if (!objc_ivar) {
5282       /* struct _objc_ivar {
5283        char *ivar_name;
5284        char *ivar_type;
5285        int ivar_offset;
5286        };
5287        */
5288       Result += "\nstruct _objc_ivar {\n";
5289       Result += "\tchar *ivar_name;\n";
5290       Result += "\tchar *ivar_type;\n";
5291       Result += "\tint ivar_offset;\n";
5292       Result += "};\n";
5293 
5294       objc_ivar = true;
5295     }
5296 
5297     /* struct {
5298      int ivar_count;
5299      struct _objc_ivar ivar_list[nIvars];
5300      };
5301      */
5302     Result += "\nstatic struct {\n";
5303     Result += "\tint ivar_count;\n";
5304     Result += "\tstruct _objc_ivar ivar_list[";
5305     Result += utostr(NumIvars);
5306     Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5307     Result += IDecl->getNameAsString();
5308     Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5309     "{\n\t";
5310     Result += utostr(NumIvars);
5311     Result += "\n";
5312 
5313     ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5314     SmallVector<ObjCIvarDecl *, 8> IVars;
5315     if (!IDecl->ivar_empty()) {
5316       for (auto *IV : IDecl->ivars())
5317         IVars.push_back(IV);
5318       IVI = IDecl->ivar_begin();
5319       IVE = IDecl->ivar_end();
5320     } else {
5321       IVI = CDecl->ivar_begin();
5322       IVE = CDecl->ivar_end();
5323     }
5324     Result += "\t,{{\"";
5325     Result += IVI->getNameAsString();
5326     Result += "\", \"";
5327     std::string TmpString, StrEncoding;
5328     Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5329     QuoteDoublequotes(TmpString, StrEncoding);
5330     Result += StrEncoding;
5331     Result += "\", ";
5332     RewriteIvarOffsetComputation(*IVI, Result);
5333     Result += "}\n";
5334     for (++IVI; IVI != IVE; ++IVI) {
5335       Result += "\t  ,{\"";
5336       Result += IVI->getNameAsString();
5337       Result += "\", \"";
5338       std::string TmpString, StrEncoding;
5339       Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5340       QuoteDoublequotes(TmpString, StrEncoding);
5341       Result += StrEncoding;
5342       Result += "\", ";
5343       RewriteIvarOffsetComputation(*IVI, Result);
5344       Result += "}\n";
5345     }
5346 
5347     Result += "\t }\n};\n";
5348   }
5349 
5350   // Build _objc_method_list for class's instance methods if needed
5351   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5352 
5353   // If any of our property implementations have associated getters or
5354   // setters, produce metadata for them as well.
5355   for (const auto *Prop : IDecl->property_impls()) {
5356     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5357       continue;
5358     if (!Prop->getPropertyIvarDecl())
5359       continue;
5360     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5361     if (!PD)
5362       continue;
5363     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
5364       if (!Getter->isDefined())
5365         InstanceMethods.push_back(Getter);
5366     if (PD->isReadOnly())
5367       continue;
5368     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
5369       if (!Setter->isDefined())
5370         InstanceMethods.push_back(Setter);
5371   }
5372   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5373                              true, "", IDecl->getName(), Result);
5374 
5375   // Build _objc_method_list for class's class methods if needed
5376   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5377                              false, "", IDecl->getName(), Result);
5378 
5379   // Protocols referenced in class declaration?
5380   RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5381                                   "CLASS", CDecl->getName(), Result);
5382 
5383   // Declaration of class/meta-class metadata
5384   /* struct _objc_class {
5385    struct _objc_class *isa; // or const char *root_class_name when metadata
5386    const char *super_class_name;
5387    char *name;
5388    long version;
5389    long info;
5390    long instance_size;
5391    struct _objc_ivar_list *ivars;
5392    struct _objc_method_list *methods;
5393    struct objc_cache *cache;
5394    struct objc_protocol_list *protocols;
5395    const char *ivar_layout;
5396    struct _objc_class_ext  *ext;
5397    };
5398    */
5399   static bool objc_class = false;
5400   if (!objc_class) {
5401     Result += "\nstruct _objc_class {\n";
5402     Result += "\tstruct _objc_class *isa;\n";
5403     Result += "\tconst char *super_class_name;\n";
5404     Result += "\tchar *name;\n";
5405     Result += "\tlong version;\n";
5406     Result += "\tlong info;\n";
5407     Result += "\tlong instance_size;\n";
5408     Result += "\tstruct _objc_ivar_list *ivars;\n";
5409     Result += "\tstruct _objc_method_list *methods;\n";
5410     Result += "\tstruct objc_cache *cache;\n";
5411     Result += "\tstruct _objc_protocol_list *protocols;\n";
5412     Result += "\tconst char *ivar_layout;\n";
5413     Result += "\tstruct _objc_class_ext  *ext;\n";
5414     Result += "};\n";
5415     objc_class = true;
5416   }
5417 
5418   // Meta-class metadata generation.
5419   ObjCInterfaceDecl *RootClass = nullptr;
5420   ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5421   while (SuperClass) {
5422     RootClass = SuperClass;
5423     SuperClass = SuperClass->getSuperClass();
5424   }
5425   SuperClass = CDecl->getSuperClass();
5426 
5427   Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5428   Result += CDecl->getNameAsString();
5429   Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5430   "{\n\t(struct _objc_class *)\"";
5431   Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5432   Result += "\"";
5433 
5434   if (SuperClass) {
5435     Result += ", \"";
5436     Result += SuperClass->getNameAsString();
5437     Result += "\", \"";
5438     Result += CDecl->getNameAsString();
5439     Result += "\"";
5440   }
5441   else {
5442     Result += ", 0, \"";
5443     Result += CDecl->getNameAsString();
5444     Result += "\"";
5445   }
5446   // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5447   // 'info' field is initialized to CLS_META(2) for metaclass
5448   Result += ", 0,2, sizeof(struct _objc_class), 0";
5449   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5450     Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5451     Result += IDecl->getNameAsString();
5452     Result += "\n";
5453   }
5454   else
5455     Result += ", 0\n";
5456   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5457     Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5458     Result += CDecl->getNameAsString();
5459     Result += ",0,0\n";
5460   }
5461   else
5462     Result += "\t,0,0,0,0\n";
5463   Result += "};\n";
5464 
5465   // class metadata generation.
5466   Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5467   Result += CDecl->getNameAsString();
5468   Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5469   "{\n\t&_OBJC_METACLASS_";
5470   Result += CDecl->getNameAsString();
5471   if (SuperClass) {
5472     Result += ", \"";
5473     Result += SuperClass->getNameAsString();
5474     Result += "\", \"";
5475     Result += CDecl->getNameAsString();
5476     Result += "\"";
5477   }
5478   else {
5479     Result += ", 0, \"";
5480     Result += CDecl->getNameAsString();
5481     Result += "\"";
5482   }
5483   // 'info' field is initialized to CLS_CLASS(1) for class
5484   Result += ", 0,1";
5485   if (!ObjCSynthesizedStructs.count(CDecl))
5486     Result += ",0";
5487   else {
5488     // class has size. Must synthesize its size.
5489     Result += ",sizeof(struct ";
5490     Result += CDecl->getNameAsString();
5491     if (LangOpts.MicrosoftExt)
5492       Result += "_IMPL";
5493     Result += ")";
5494   }
5495   if (NumIvars > 0) {
5496     Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5497     Result += CDecl->getNameAsString();
5498     Result += "\n\t";
5499   }
5500   else
5501     Result += ",0";
5502   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5503     Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5504     Result += CDecl->getNameAsString();
5505     Result += ", 0\n\t";
5506   }
5507   else
5508     Result += ",0,0";
5509   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5510     Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5511     Result += CDecl->getNameAsString();
5512     Result += ", 0,0\n";
5513   }
5514   else
5515     Result += ",0,0,0\n";
5516   Result += "};\n";
5517 }
5518 
5519 void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5520   int ClsDefCount = ClassImplementation.size();
5521   int CatDefCount = CategoryImplementation.size();
5522 
5523   // For each implemented class, write out all its meta data.
5524   for (int i = 0; i < ClsDefCount; i++)
5525     RewriteObjCClassMetaData(ClassImplementation[i], Result);
5526 
5527   // For each implemented category, write out all its meta data.
5528   for (int i = 0; i < CatDefCount; i++)
5529     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5530 
5531   // Write objc_symtab metadata
5532   /*
5533    struct _objc_symtab
5534    {
5535    long sel_ref_cnt;
5536    SEL *refs;
5537    short cls_def_cnt;
5538    short cat_def_cnt;
5539    void *defs[cls_def_cnt + cat_def_cnt];
5540    };
5541    */
5542 
5543   Result += "\nstruct _objc_symtab {\n";
5544   Result += "\tlong sel_ref_cnt;\n";
5545   Result += "\tSEL *refs;\n";
5546   Result += "\tshort cls_def_cnt;\n";
5547   Result += "\tshort cat_def_cnt;\n";
5548   Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5549   Result += "};\n\n";
5550 
5551   Result += "static struct _objc_symtab "
5552   "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5553   Result += "\t0, 0, " + utostr(ClsDefCount)
5554   + ", " + utostr(CatDefCount) + "\n";
5555   for (int i = 0; i < ClsDefCount; i++) {
5556     Result += "\t,&_OBJC_CLASS_";
5557     Result += ClassImplementation[i]->getNameAsString();
5558     Result += "\n";
5559   }
5560 
5561   for (int i = 0; i < CatDefCount; i++) {
5562     Result += "\t,&_OBJC_CATEGORY_";
5563     Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5564     Result += "_";
5565     Result += CategoryImplementation[i]->getNameAsString();
5566     Result += "\n";
5567   }
5568 
5569   Result += "};\n\n";
5570 
5571   // Write objc_module metadata
5572 
5573   /*
5574    struct _objc_module {
5575    long version;
5576    long size;
5577    const char *name;
5578    struct _objc_symtab *symtab;
5579    }
5580    */
5581 
5582   Result += "\nstruct _objc_module {\n";
5583   Result += "\tlong version;\n";
5584   Result += "\tlong size;\n";
5585   Result += "\tconst char *name;\n";
5586   Result += "\tstruct _objc_symtab *symtab;\n";
5587   Result += "};\n\n";
5588   Result += "static struct _objc_module "
5589   "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5590   Result += "\t" + utostr(OBJC_ABI_VERSION) +
5591   ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5592   Result += "};\n\n";
5593 
5594   if (LangOpts.MicrosoftExt) {
5595     if (ProtocolExprDecls.size()) {
5596       Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5597       Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5598       for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5599         Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5600         Result += ProtDecl->getNameAsString();
5601         Result += " = &_OBJC_PROTOCOL_";
5602         Result += ProtDecl->getNameAsString();
5603         Result += ";\n";
5604       }
5605       Result += "#pragma data_seg(pop)\n\n";
5606     }
5607     Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5608     Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5609     Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5610     Result += "&_OBJC_MODULES;\n";
5611     Result += "#pragma data_seg(pop)\n\n";
5612   }
5613 }
5614 
5615 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5616 /// implementation.
5617 void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5618                                               std::string &Result) {
5619   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5620   // Find category declaration for this implementation.
5621   ObjCCategoryDecl *CDecl
5622     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5623 
5624   std::string FullCategoryName = ClassDecl->getNameAsString();
5625   FullCategoryName += '_';
5626   FullCategoryName += IDecl->getNameAsString();
5627 
5628   // Build _objc_method_list for class's instance methods if needed
5629   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5630 
5631   // If any of our property implementations have associated getters or
5632   // setters, produce metadata for them as well.
5633   for (const auto *Prop : IDecl->property_impls()) {
5634     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5635       continue;
5636     if (!Prop->getPropertyIvarDecl())
5637       continue;
5638     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5639     if (!PD)
5640       continue;
5641     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
5642       InstanceMethods.push_back(Getter);
5643     if (PD->isReadOnly())
5644       continue;
5645     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
5646       InstanceMethods.push_back(Setter);
5647   }
5648   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5649                              true, "CATEGORY_", FullCategoryName, Result);
5650 
5651   // Build _objc_method_list for class's class methods if needed
5652   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5653                              false, "CATEGORY_", FullCategoryName, Result);
5654 
5655   // Protocols referenced in class declaration?
5656   // Null CDecl is case of a category implementation with no category interface
5657   if (CDecl)
5658     RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5659                                     FullCategoryName, Result);
5660   /* struct _objc_category {
5661    char *category_name;
5662    char *class_name;
5663    struct _objc_method_list *instance_methods;
5664    struct _objc_method_list *class_methods;
5665    struct _objc_protocol_list *protocols;
5666    // Objective-C 1.0 extensions
5667    uint32_t size;     // sizeof (struct _objc_category)
5668    struct _objc_property_list *instance_properties;  // category's own
5669    // @property decl.
5670    };
5671    */
5672 
5673   static bool objc_category = false;
5674   if (!objc_category) {
5675     Result += "\nstruct _objc_category {\n";
5676     Result += "\tchar *category_name;\n";
5677     Result += "\tchar *class_name;\n";
5678     Result += "\tstruct _objc_method_list *instance_methods;\n";
5679     Result += "\tstruct _objc_method_list *class_methods;\n";
5680     Result += "\tstruct _objc_protocol_list *protocols;\n";
5681     Result += "\tunsigned int size;\n";
5682     Result += "\tstruct _objc_property_list *instance_properties;\n";
5683     Result += "};\n";
5684     objc_category = true;
5685   }
5686   Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5687   Result += FullCategoryName;
5688   Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5689   Result += IDecl->getNameAsString();
5690   Result += "\"\n\t, \"";
5691   Result += ClassDecl->getNameAsString();
5692   Result += "\"\n";
5693 
5694   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5695     Result += "\t, (struct _objc_method_list *)"
5696     "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5697     Result += FullCategoryName;
5698     Result += "\n";
5699   }
5700   else
5701     Result += "\t, 0\n";
5702   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5703     Result += "\t, (struct _objc_method_list *)"
5704     "&_OBJC_CATEGORY_CLASS_METHODS_";
5705     Result += FullCategoryName;
5706     Result += "\n";
5707   }
5708   else
5709     Result += "\t, 0\n";
5710 
5711   if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5712     Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5713     Result += FullCategoryName;
5714     Result += "\n";
5715   }
5716   else
5717     Result += "\t, 0\n";
5718   Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5719 }
5720 
5721 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5722 /// class methods.
5723 template<typename MethodIterator>
5724 void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5725                                              MethodIterator MethodEnd,
5726                                              bool IsInstanceMethod,
5727                                              StringRef prefix,
5728                                              StringRef ClassName,
5729                                              std::string &Result) {
5730   if (MethodBegin == MethodEnd) return;
5731 
5732   if (!objc_impl_method) {
5733     /* struct _objc_method {
5734      SEL _cmd;
5735      char *method_types;
5736      void *_imp;
5737      }
5738      */
5739     Result += "\nstruct _objc_method {\n";
5740     Result += "\tSEL _cmd;\n";
5741     Result += "\tchar *method_types;\n";
5742     Result += "\tvoid *_imp;\n";
5743     Result += "};\n";
5744 
5745     objc_impl_method = true;
5746   }
5747 
5748   // Build _objc_method_list for class's methods if needed
5749 
5750   /* struct  {
5751    struct _objc_method_list *next_method;
5752    int method_count;
5753    struct _objc_method method_list[];
5754    }
5755    */
5756   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5757   Result += "\nstatic struct {\n";
5758   Result += "\tstruct _objc_method_list *next_method;\n";
5759   Result += "\tint method_count;\n";
5760   Result += "\tstruct _objc_method method_list[";
5761   Result += utostr(NumMethods);
5762   Result += "];\n} _OBJC_";
5763   Result += prefix;
5764   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5765   Result += "_METHODS_";
5766   Result += ClassName;
5767   Result += " __attribute__ ((used, section (\"__OBJC, __";
5768   Result += IsInstanceMethod ? "inst" : "cls";
5769   Result += "_meth\")))= ";
5770   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5771 
5772   Result += "\t,{{(SEL)\"";
5773   Result += (*MethodBegin)->getSelector().getAsString();
5774   std::string MethodTypeString =
5775     Context->getObjCEncodingForMethodDecl(*MethodBegin);
5776   Result += "\", \"";
5777   Result += MethodTypeString;
5778   Result += "\", (void *)";
5779   Result += MethodInternalNames[*MethodBegin];
5780   Result += "}\n";
5781   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5782     Result += "\t  ,{(SEL)\"";
5783     Result += (*MethodBegin)->getSelector().getAsString();
5784     std::string MethodTypeString =
5785       Context->getObjCEncodingForMethodDecl(*MethodBegin);
5786     Result += "\", \"";
5787     Result += MethodTypeString;
5788     Result += "\", (void *)";
5789     Result += MethodInternalNames[*MethodBegin];
5790     Result += "}\n";
5791   }
5792   Result += "\t }\n};\n";
5793 }
5794 
5795 Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5796   SourceRange OldRange = IV->getSourceRange();
5797   Expr *BaseExpr = IV->getBase();
5798 
5799   // Rewrite the base, but without actually doing replaces.
5800   {
5801     DisableReplaceStmtScope S(*this);
5802     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5803     IV->setBase(BaseExpr);
5804   }
5805 
5806   ObjCIvarDecl *D = IV->getDecl();
5807 
5808   Expr *Replacement = IV;
5809   if (CurMethodDef) {
5810     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5811       const ObjCInterfaceType *iFaceDecl =
5812       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5813       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5814       // lookup which class implements the instance variable.
5815       ObjCInterfaceDecl *clsDeclared = nullptr;
5816       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5817                                                    clsDeclared);
5818       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5819 
5820       // Synthesize an explicit cast to gain access to the ivar.
5821       std::string RecName =
5822           std::string(clsDeclared->getIdentifier()->getName());
5823       RecName += "_IMPL";
5824       IdentifierInfo *II = &Context->Idents.get(RecName);
5825       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5826                                           SourceLocation(), SourceLocation(),
5827                                           II);
5828       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5829       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5830       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5831                                                     CK_BitCast,
5832                                                     IV->getBase());
5833       // Don't forget the parens to enforce the proper binding.
5834       ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5835                                               OldRange.getEnd(),
5836                                               castExpr);
5837       if (IV->isFreeIvar() &&
5838           declaresSameEntity(CurMethodDef->getClassInterface(),
5839                              iFaceDecl->getDecl())) {
5840         MemberExpr *ME = MemberExpr::CreateImplicit(
5841             *Context, PE, true, D, D->getType(), VK_LValue, OK_Ordinary);
5842         Replacement = ME;
5843       } else {
5844         IV->setBase(PE);
5845       }
5846     }
5847   } else { // we are outside a method.
5848     assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5849 
5850     // Explicit ivar refs need to have a cast inserted.
5851     // FIXME: consider sharing some of this code with the code above.
5852     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5853       const ObjCInterfaceType *iFaceDecl =
5854       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5855       // lookup which class implements the instance variable.
5856       ObjCInterfaceDecl *clsDeclared = nullptr;
5857       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5858                                                    clsDeclared);
5859       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5860 
5861       // Synthesize an explicit cast to gain access to the ivar.
5862       std::string RecName =
5863           std::string(clsDeclared->getIdentifier()->getName());
5864       RecName += "_IMPL";
5865       IdentifierInfo *II = &Context->Idents.get(RecName);
5866       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5867                                           SourceLocation(), SourceLocation(),
5868                                           II);
5869       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5870       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5871       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5872                                                     CK_BitCast,
5873                                                     IV->getBase());
5874       // Don't forget the parens to enforce the proper binding.
5875       ParenExpr *PE = new (Context) ParenExpr(
5876           IV->getBase()->getBeginLoc(), IV->getBase()->getEndLoc(), castExpr);
5877       // Cannot delete IV->getBase(), since PE points to it.
5878       // Replace the old base with the cast. This is important when doing
5879       // embedded rewrites. For example, [newInv->_container addObject:0].
5880       IV->setBase(PE);
5881     }
5882   }
5883 
5884   ReplaceStmtWithRange(IV, Replacement, OldRange);
5885   return Replacement;
5886 }
5887 
5888 #endif // CLANG_ENABLE_OBJC_REWRITER
5889