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