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