TransGCAttrs.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. //===--- TransGCAttrs.cpp - Transformations to ARC mode --------------------===//
  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. #include "Transforms.h"
  9. #include "Internals.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/Basic/SourceManager.h"
  12. #include "clang/Lex/Lexer.h"
  13. #include "clang/Sema/SemaDiagnostic.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/TinyPtrVector.h"
  16. #include "llvm/Support/SaveAndRestore.h"
  17. using namespace clang;
  18. using namespace arcmt;
  19. using namespace trans;
  20. namespace {
  21. /// Collects all the places where GC attributes __strong/__weak occur.
  22. class GCAttrsCollector : public RecursiveASTVisitor<GCAttrsCollector> {
  23. MigrationContext &MigrateCtx;
  24. bool FullyMigratable;
  25. std::vector<ObjCPropertyDecl *> &AllProps;
  26. typedef RecursiveASTVisitor<GCAttrsCollector> base;
  27. public:
  28. GCAttrsCollector(MigrationContext &ctx,
  29. std::vector<ObjCPropertyDecl *> &AllProps)
  30. : MigrateCtx(ctx), FullyMigratable(false),
  31. AllProps(AllProps) { }
  32. bool shouldWalkTypesOfTypeLocs() const { return false; }
  33. bool VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  34. handleAttr(TL);
  35. return true;
  36. }
  37. bool TraverseDecl(Decl *D) {
  38. if (!D || D->isImplicit())
  39. return true;
  40. SaveAndRestore<bool> Save(FullyMigratable, isMigratable(D));
  41. if (ObjCPropertyDecl *PropD = dyn_cast<ObjCPropertyDecl>(D)) {
  42. lookForAttribute(PropD, PropD->getTypeSourceInfo());
  43. AllProps.push_back(PropD);
  44. } else if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  45. lookForAttribute(DD, DD->getTypeSourceInfo());
  46. }
  47. return base::TraverseDecl(D);
  48. }
  49. void lookForAttribute(Decl *D, TypeSourceInfo *TInfo) {
  50. if (!TInfo)
  51. return;
  52. TypeLoc TL = TInfo->getTypeLoc();
  53. while (TL) {
  54. if (QualifiedTypeLoc QL = TL.getAs<QualifiedTypeLoc>()) {
  55. TL = QL.getUnqualifiedLoc();
  56. } else if (AttributedTypeLoc Attr = TL.getAs<AttributedTypeLoc>()) {
  57. if (handleAttr(Attr, D))
  58. break;
  59. TL = Attr.getModifiedLoc();
  60. } else if (MacroQualifiedTypeLoc MDTL =
  61. TL.getAs<MacroQualifiedTypeLoc>()) {
  62. TL = MDTL.getInnerLoc();
  63. } else if (ArrayTypeLoc Arr = TL.getAs<ArrayTypeLoc>()) {
  64. TL = Arr.getElementLoc();
  65. } else if (PointerTypeLoc PT = TL.getAs<PointerTypeLoc>()) {
  66. TL = PT.getPointeeLoc();
  67. } else if (ReferenceTypeLoc RT = TL.getAs<ReferenceTypeLoc>())
  68. TL = RT.getPointeeLoc();
  69. else
  70. break;
  71. }
  72. }
  73. bool handleAttr(AttributedTypeLoc TL, Decl *D = nullptr) {
  74. auto *OwnershipAttr = TL.getAttrAs<ObjCOwnershipAttr>();
  75. if (!OwnershipAttr)
  76. return false;
  77. SourceLocation Loc = OwnershipAttr->getLocation();
  78. unsigned RawLoc = Loc.getRawEncoding();
  79. if (MigrateCtx.AttrSet.count(RawLoc))
  80. return true;
  81. ASTContext &Ctx = MigrateCtx.Pass.Ctx;
  82. SourceManager &SM = Ctx.getSourceManager();
  83. if (Loc.isMacroID())
  84. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  85. StringRef Spell = OwnershipAttr->getKind()->getName();
  86. MigrationContext::GCAttrOccurrence::AttrKind Kind;
  87. if (Spell == "strong")
  88. Kind = MigrationContext::GCAttrOccurrence::Strong;
  89. else if (Spell == "weak")
  90. Kind = MigrationContext::GCAttrOccurrence::Weak;
  91. else
  92. return false;
  93. MigrateCtx.AttrSet.insert(RawLoc);
  94. MigrateCtx.GCAttrs.push_back(MigrationContext::GCAttrOccurrence());
  95. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs.back();
  96. Attr.Kind = Kind;
  97. Attr.Loc = Loc;
  98. Attr.ModifiedType = TL.getModifiedLoc().getType();
  99. Attr.Dcl = D;
  100. Attr.FullyMigratable = FullyMigratable;
  101. return true;
  102. }
  103. bool isMigratable(Decl *D) {
  104. if (isa<TranslationUnitDecl>(D))
  105. return false;
  106. if (isInMainFile(D))
  107. return true;
  108. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  109. return FD->hasBody();
  110. if (ObjCContainerDecl *ContD = dyn_cast<ObjCContainerDecl>(D))
  111. return hasObjCImpl(ContD);
  112. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  113. for (const auto *MI : RD->methods()) {
  114. if (MI->isOutOfLine())
  115. return true;
  116. }
  117. return false;
  118. }
  119. return isMigratable(cast<Decl>(D->getDeclContext()));
  120. }
  121. static bool hasObjCImpl(Decl *D) {
  122. if (!D)
  123. return false;
  124. if (ObjCContainerDecl *ContD = dyn_cast<ObjCContainerDecl>(D)) {
  125. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ContD))
  126. return ID->getImplementation() != nullptr;
  127. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContD))
  128. return CD->getImplementation() != nullptr;
  129. return isa<ObjCImplDecl>(ContD);
  130. }
  131. return false;
  132. }
  133. bool isInMainFile(Decl *D) {
  134. if (!D)
  135. return false;
  136. for (auto I : D->redecls())
  137. if (!isInMainFile(I->getLocation()))
  138. return false;
  139. return true;
  140. }
  141. bool isInMainFile(SourceLocation Loc) {
  142. if (Loc.isInvalid())
  143. return false;
  144. SourceManager &SM = MigrateCtx.Pass.Ctx.getSourceManager();
  145. return SM.isInFileID(SM.getExpansionLoc(Loc), SM.getMainFileID());
  146. }
  147. };
  148. } // anonymous namespace
  149. static void errorForGCAttrsOnNonObjC(MigrationContext &MigrateCtx) {
  150. TransformActions &TA = MigrateCtx.Pass.TA;
  151. for (unsigned i = 0, e = MigrateCtx.GCAttrs.size(); i != e; ++i) {
  152. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs[i];
  153. if (Attr.FullyMigratable && Attr.Dcl) {
  154. if (Attr.ModifiedType.isNull())
  155. continue;
  156. if (!Attr.ModifiedType->isObjCRetainableType()) {
  157. TA.reportError("GC managed memory will become unmanaged in ARC",
  158. Attr.Loc);
  159. }
  160. }
  161. }
  162. }
  163. static void checkWeakGCAttrs(MigrationContext &MigrateCtx) {
  164. TransformActions &TA = MigrateCtx.Pass.TA;
  165. for (unsigned i = 0, e = MigrateCtx.GCAttrs.size(); i != e; ++i) {
  166. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs[i];
  167. if (Attr.Kind == MigrationContext::GCAttrOccurrence::Weak) {
  168. if (Attr.ModifiedType.isNull() ||
  169. !Attr.ModifiedType->isObjCRetainableType())
  170. continue;
  171. if (!canApplyWeak(MigrateCtx.Pass.Ctx, Attr.ModifiedType,
  172. /*AllowOnUnknownClass=*/true)) {
  173. Transaction Trans(TA);
  174. if (!MigrateCtx.RemovedAttrSet.count(Attr.Loc.getRawEncoding()))
  175. TA.replaceText(Attr.Loc, "__weak", "__unsafe_unretained");
  176. TA.clearDiagnostic(diag::err_arc_weak_no_runtime,
  177. diag::err_arc_unsupported_weak_class,
  178. Attr.Loc);
  179. }
  180. }
  181. }
  182. }
  183. typedef llvm::TinyPtrVector<ObjCPropertyDecl *> IndivPropsTy;
  184. static void checkAllAtProps(MigrationContext &MigrateCtx,
  185. SourceLocation AtLoc,
  186. IndivPropsTy &IndProps) {
  187. if (IndProps.empty())
  188. return;
  189. for (IndivPropsTy::iterator
  190. PI = IndProps.begin(), PE = IndProps.end(); PI != PE; ++PI) {
  191. QualType T = (*PI)->getType();
  192. if (T.isNull() || !T->isObjCRetainableType())
  193. return;
  194. }
  195. SmallVector<std::pair<AttributedTypeLoc, ObjCPropertyDecl *>, 4> ATLs;
  196. bool hasWeak = false, hasStrong = false;
  197. ObjCPropertyDecl::PropertyAttributeKind
  198. Attrs = ObjCPropertyDecl::OBJC_PR_noattr;
  199. for (IndivPropsTy::iterator
  200. PI = IndProps.begin(), PE = IndProps.end(); PI != PE; ++PI) {
  201. ObjCPropertyDecl *PD = *PI;
  202. Attrs = PD->getPropertyAttributesAsWritten();
  203. TypeSourceInfo *TInfo = PD->getTypeSourceInfo();
  204. if (!TInfo)
  205. return;
  206. TypeLoc TL = TInfo->getTypeLoc();
  207. if (AttributedTypeLoc ATL =
  208. TL.getAs<AttributedTypeLoc>()) {
  209. ATLs.push_back(std::make_pair(ATL, PD));
  210. if (TInfo->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  211. hasWeak = true;
  212. } else if (TInfo->getType().getObjCLifetime() == Qualifiers::OCL_Strong)
  213. hasStrong = true;
  214. else
  215. return;
  216. }
  217. }
  218. if (ATLs.empty())
  219. return;
  220. if (hasWeak && hasStrong)
  221. return;
  222. TransformActions &TA = MigrateCtx.Pass.TA;
  223. Transaction Trans(TA);
  224. if (GCAttrsCollector::hasObjCImpl(
  225. cast<Decl>(IndProps.front()->getDeclContext()))) {
  226. if (hasWeak)
  227. MigrateCtx.AtPropsWeak.insert(AtLoc.getRawEncoding());
  228. } else {
  229. StringRef toAttr = "strong";
  230. if (hasWeak) {
  231. if (canApplyWeak(MigrateCtx.Pass.Ctx, IndProps.front()->getType(),
  232. /*AllowOnUnknownClass=*/true))
  233. toAttr = "weak";
  234. else
  235. toAttr = "unsafe_unretained";
  236. }
  237. if (Attrs & ObjCPropertyDecl::OBJC_PR_assign)
  238. MigrateCtx.rewritePropertyAttribute("assign", toAttr, AtLoc);
  239. else
  240. MigrateCtx.addPropertyAttribute(toAttr, AtLoc);
  241. }
  242. for (unsigned i = 0, e = ATLs.size(); i != e; ++i) {
  243. SourceLocation Loc = ATLs[i].first.getAttr()->getLocation();
  244. if (Loc.isMacroID())
  245. Loc = MigrateCtx.Pass.Ctx.getSourceManager()
  246. .getImmediateExpansionRange(Loc)
  247. .getBegin();
  248. TA.remove(Loc);
  249. TA.clearDiagnostic(diag::err_objc_property_attr_mutually_exclusive, AtLoc);
  250. TA.clearDiagnostic(diag::err_arc_inconsistent_property_ownership,
  251. ATLs[i].second->getLocation());
  252. MigrateCtx.RemovedAttrSet.insert(Loc.getRawEncoding());
  253. }
  254. }
  255. static void checkAllProps(MigrationContext &MigrateCtx,
  256. std::vector<ObjCPropertyDecl *> &AllProps) {
  257. typedef llvm::TinyPtrVector<ObjCPropertyDecl *> IndivPropsTy;
  258. llvm::DenseMap<unsigned, IndivPropsTy> AtProps;
  259. for (unsigned i = 0, e = AllProps.size(); i != e; ++i) {
  260. ObjCPropertyDecl *PD = AllProps[i];
  261. if (PD->getPropertyAttributesAsWritten() &
  262. (ObjCPropertyDecl::OBJC_PR_assign |
  263. ObjCPropertyDecl::OBJC_PR_readonly)) {
  264. SourceLocation AtLoc = PD->getAtLoc();
  265. if (AtLoc.isInvalid())
  266. continue;
  267. unsigned RawAt = AtLoc.getRawEncoding();
  268. AtProps[RawAt].push_back(PD);
  269. }
  270. }
  271. for (llvm::DenseMap<unsigned, IndivPropsTy>::iterator
  272. I = AtProps.begin(), E = AtProps.end(); I != E; ++I) {
  273. SourceLocation AtLoc = SourceLocation::getFromRawEncoding(I->first);
  274. IndivPropsTy &IndProps = I->second;
  275. checkAllAtProps(MigrateCtx, AtLoc, IndProps);
  276. }
  277. }
  278. void GCAttrsTraverser::traverseTU(MigrationContext &MigrateCtx) {
  279. std::vector<ObjCPropertyDecl *> AllProps;
  280. GCAttrsCollector(MigrateCtx, AllProps).TraverseDecl(
  281. MigrateCtx.Pass.Ctx.getTranslationUnitDecl());
  282. errorForGCAttrsOnNonObjC(MigrateCtx);
  283. checkAllProps(MigrateCtx, AllProps);
  284. checkWeakGCAttrs(MigrateCtx);
  285. }
  286. void MigrationContext::dumpGCAttrs() {
  287. llvm::errs() << "\n################\n";
  288. for (unsigned i = 0, e = GCAttrs.size(); i != e; ++i) {
  289. GCAttrOccurrence &Attr = GCAttrs[i];
  290. llvm::errs() << "KIND: "
  291. << (Attr.Kind == GCAttrOccurrence::Strong ? "strong" : "weak");
  292. llvm::errs() << "\nLOC: ";
  293. Attr.Loc.print(llvm::errs(), Pass.Ctx.getSourceManager());
  294. llvm::errs() << "\nTYPE: ";
  295. Attr.ModifiedType.dump();
  296. if (Attr.Dcl) {
  297. llvm::errs() << "DECL:\n";
  298. Attr.Dcl->dump();
  299. } else {
  300. llvm::errs() << "DECL: NONE";
  301. }
  302. llvm::errs() << "\nMIGRATABLE: " << Attr.FullyMigratable;
  303. llvm::errs() << "\n----------------\n";
  304. }
  305. llvm::errs() << "\n################\n";
  306. }