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