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