SelectionDAGAddressAnalysis.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. //==- llvm/CodeGen/SelectionDAGAddressAnalysis.cpp - DAG Address Analysis --==//
  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 "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  9. #include "llvm/Analysis/MemoryLocation.h"
  10. #include "llvm/CodeGen/ISDOpcodes.h"
  11. #include "llvm/CodeGen/MachineFrameInfo.h"
  12. #include "llvm/CodeGen/MachineFunction.h"
  13. #include "llvm/CodeGen/SelectionDAG.h"
  14. #include "llvm/CodeGen/SelectionDAGNodes.h"
  15. #include "llvm/CodeGen/TargetLowering.h"
  16. #include "llvm/IR/GlobalAlias.h"
  17. #include "llvm/Support/Casting.h"
  18. #include "llvm/Support/Debug.h"
  19. #include <cstdint>
  20. using namespace llvm;
  21. bool BaseIndexOffset::equalBaseIndex(const BaseIndexOffset &Other,
  22. const SelectionDAG &DAG,
  23. int64_t &Off) const {
  24. // Conservatively fail if we a match failed..
  25. if (!Base.getNode() || !Other.Base.getNode())
  26. return false;
  27. if (!hasValidOffset() || !Other.hasValidOffset())
  28. return false;
  29. // Initial Offset difference.
  30. Off = *Other.Offset - *Offset;
  31. if ((Other.Index == Index) && (Other.IsIndexSignExt == IsIndexSignExt)) {
  32. // Trivial match.
  33. if (Other.Base == Base)
  34. return true;
  35. // Match GlobalAddresses
  36. if (auto *A = dyn_cast<GlobalAddressSDNode>(Base))
  37. if (auto *B = dyn_cast<GlobalAddressSDNode>(Other.Base))
  38. if (A->getGlobal() == B->getGlobal()) {
  39. Off += B->getOffset() - A->getOffset();
  40. return true;
  41. }
  42. // Match Constants
  43. if (auto *A = dyn_cast<ConstantPoolSDNode>(Base))
  44. if (auto *B = dyn_cast<ConstantPoolSDNode>(Other.Base)) {
  45. bool IsMatch =
  46. A->isMachineConstantPoolEntry() == B->isMachineConstantPoolEntry();
  47. if (IsMatch) {
  48. if (A->isMachineConstantPoolEntry())
  49. IsMatch = A->getMachineCPVal() == B->getMachineCPVal();
  50. else
  51. IsMatch = A->getConstVal() == B->getConstVal();
  52. }
  53. if (IsMatch) {
  54. Off += B->getOffset() - A->getOffset();
  55. return true;
  56. }
  57. }
  58. const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  59. // Match FrameIndexes.
  60. if (auto *A = dyn_cast<FrameIndexSDNode>(Base))
  61. if (auto *B = dyn_cast<FrameIndexSDNode>(Other.Base)) {
  62. // Equal FrameIndexes - offsets are directly comparable.
  63. if (A->getIndex() == B->getIndex())
  64. return true;
  65. // Non-equal FrameIndexes - If both frame indices are fixed
  66. // we know their relative offsets and can compare them. Otherwise
  67. // we must be conservative.
  68. if (MFI.isFixedObjectIndex(A->getIndex()) &&
  69. MFI.isFixedObjectIndex(B->getIndex())) {
  70. Off += MFI.getObjectOffset(B->getIndex()) -
  71. MFI.getObjectOffset(A->getIndex());
  72. return true;
  73. }
  74. }
  75. }
  76. return false;
  77. }
  78. bool BaseIndexOffset::computeAliasing(const SDNode *Op0,
  79. const std::optional<int64_t> NumBytes0,
  80. const SDNode *Op1,
  81. const std::optional<int64_t> NumBytes1,
  82. const SelectionDAG &DAG, bool &IsAlias) {
  83. BaseIndexOffset BasePtr0 = match(Op0, DAG);
  84. BaseIndexOffset BasePtr1 = match(Op1, DAG);
  85. if (!(BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()))
  86. return false;
  87. int64_t PtrDiff;
  88. if (NumBytes0 && NumBytes1 &&
  89. BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) {
  90. // If the size of memory access is unknown, do not use it to analysis.
  91. // One example of unknown size memory access is to load/store scalable
  92. // vector objects on the stack.
  93. // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
  94. // following situations arise:
  95. if (PtrDiff >= 0 &&
  96. *NumBytes0 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
  97. // [----BasePtr0----]
  98. // [---BasePtr1--]
  99. // ========PtrDiff========>
  100. IsAlias = !(*NumBytes0 <= PtrDiff);
  101. return true;
  102. }
  103. if (PtrDiff < 0 &&
  104. *NumBytes1 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
  105. // [----BasePtr0----]
  106. // [---BasePtr1--]
  107. // =====(-PtrDiff)====>
  108. IsAlias = !((PtrDiff + *NumBytes1) <= 0);
  109. return true;
  110. }
  111. return false;
  112. }
  113. // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
  114. // able to calculate their relative offset if at least one arises
  115. // from an alloca. However, these allocas cannot overlap and we
  116. // can infer there is no alias.
  117. if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
  118. if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
  119. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  120. // If the base are the same frame index but the we couldn't find a
  121. // constant offset, (indices are different) be conservative.
  122. if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
  123. !MFI.isFixedObjectIndex(B->getIndex()))) {
  124. IsAlias = false;
  125. return true;
  126. }
  127. }
  128. bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
  129. bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
  130. bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
  131. bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
  132. bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
  133. bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
  134. if ((IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) {
  135. // We can derive NoAlias In case of mismatched base types.
  136. if (IsFI0 != IsFI1 || IsGV0 != IsGV1 || IsCV0 != IsCV1) {
  137. IsAlias = false;
  138. return true;
  139. }
  140. if (IsGV0 && IsGV1) {
  141. auto *GV0 = cast<GlobalAddressSDNode>(BasePtr0.getBase())->getGlobal();
  142. auto *GV1 = cast<GlobalAddressSDNode>(BasePtr1.getBase())->getGlobal();
  143. // It doesn't make sense to access one global value using another globals
  144. // values address, so we can assume that there is no aliasing in case of
  145. // two different globals (unless we have symbols that may indirectly point
  146. // to each other).
  147. // FIXME: This is perhaps a bit too defensive. We could try to follow the
  148. // chain with aliasee information for GlobalAlias variables to find out if
  149. // we indirect symbols may alias or not.
  150. if (GV0 != GV1 && !isa<GlobalAlias>(GV0) && !isa<GlobalAlias>(GV1)) {
  151. IsAlias = false;
  152. return true;
  153. }
  154. }
  155. }
  156. return false; // Cannot determine whether the pointers alias.
  157. }
  158. bool BaseIndexOffset::contains(const SelectionDAG &DAG, int64_t BitSize,
  159. const BaseIndexOffset &Other,
  160. int64_t OtherBitSize, int64_t &BitOffset) const {
  161. int64_t Offset;
  162. if (!equalBaseIndex(Other, DAG, Offset))
  163. return false;
  164. if (Offset >= 0) {
  165. // Other is after *this:
  166. // [-------*this---------]
  167. // [---Other--]
  168. // ==Offset==>
  169. BitOffset = 8 * Offset;
  170. return BitOffset + OtherBitSize <= BitSize;
  171. }
  172. // Other starts strictly before *this, it cannot be fully contained.
  173. // [-------*this---------]
  174. // [--Other--]
  175. return false;
  176. }
  177. /// Parses tree in Ptr for base, index, offset addresses.
  178. static BaseIndexOffset matchLSNode(const LSBaseSDNode *N,
  179. const SelectionDAG &DAG) {
  180. SDValue Ptr = N->getBasePtr();
  181. // (((B + I*M) + c)) + c ...
  182. SDValue Base = DAG.getTargetLoweringInfo().unwrapAddress(Ptr);
  183. SDValue Index = SDValue();
  184. int64_t Offset = 0;
  185. bool IsIndexSignExt = false;
  186. // pre-inc/pre-dec ops are components of EA.
  187. if (N->getAddressingMode() == ISD::PRE_INC) {
  188. if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
  189. Offset += C->getSExtValue();
  190. else // If unknown, give up now.
  191. return BaseIndexOffset(SDValue(), SDValue(), 0, false);
  192. } else if (N->getAddressingMode() == ISD::PRE_DEC) {
  193. if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
  194. Offset -= C->getSExtValue();
  195. else // If unknown, give up now.
  196. return BaseIndexOffset(SDValue(), SDValue(), 0, false);
  197. }
  198. // Consume constant adds & ors with appropriate masking.
  199. while (true) {
  200. switch (Base->getOpcode()) {
  201. case ISD::OR:
  202. // Only consider ORs which act as adds.
  203. if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
  204. if (DAG.MaskedValueIsZero(Base->getOperand(0), C->getAPIntValue())) {
  205. Offset += C->getSExtValue();
  206. Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
  207. continue;
  208. }
  209. break;
  210. case ISD::ADD:
  211. if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1))) {
  212. Offset += C->getSExtValue();
  213. Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
  214. continue;
  215. }
  216. break;
  217. case ISD::LOAD:
  218. case ISD::STORE: {
  219. auto *LSBase = cast<LSBaseSDNode>(Base.getNode());
  220. unsigned int IndexResNo = (Base->getOpcode() == ISD::LOAD) ? 1 : 0;
  221. if (LSBase->isIndexed() && Base.getResNo() == IndexResNo)
  222. if (auto *C = dyn_cast<ConstantSDNode>(LSBase->getOffset())) {
  223. auto Off = C->getSExtValue();
  224. if (LSBase->getAddressingMode() == ISD::PRE_DEC ||
  225. LSBase->getAddressingMode() == ISD::POST_DEC)
  226. Offset -= Off;
  227. else
  228. Offset += Off;
  229. Base = DAG.getTargetLoweringInfo().unwrapAddress(LSBase->getBasePtr());
  230. continue;
  231. }
  232. break;
  233. }
  234. }
  235. // If we get here break out of the loop.
  236. break;
  237. }
  238. if (Base->getOpcode() == ISD::ADD) {
  239. // TODO: The following code appears to be needless as it just
  240. // bails on some Ptrs early, reducing the cases where we
  241. // find equivalence. We should be able to remove this.
  242. // Inside a loop the current BASE pointer is calculated using an ADD and a
  243. // MUL instruction. In this case Base is the actual BASE pointer.
  244. // (i64 add (i64 %array_ptr)
  245. // (i64 mul (i64 %induction_var)
  246. // (i64 %element_size)))
  247. if (Base->getOperand(1)->getOpcode() == ISD::MUL)
  248. return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
  249. // Look at Base + Index + Offset cases.
  250. Index = Base->getOperand(1);
  251. SDValue PotentialBase = Base->getOperand(0);
  252. // Skip signextends.
  253. if (Index->getOpcode() == ISD::SIGN_EXTEND) {
  254. Index = Index->getOperand(0);
  255. IsIndexSignExt = true;
  256. }
  257. // Check if Index Offset pattern
  258. if (Index->getOpcode() != ISD::ADD ||
  259. !isa<ConstantSDNode>(Index->getOperand(1)))
  260. return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt);
  261. Offset += cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue();
  262. Index = Index->getOperand(0);
  263. if (Index->getOpcode() == ISD::SIGN_EXTEND) {
  264. Index = Index->getOperand(0);
  265. IsIndexSignExt = true;
  266. } else
  267. IsIndexSignExt = false;
  268. Base = PotentialBase;
  269. }
  270. return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
  271. }
  272. BaseIndexOffset BaseIndexOffset::match(const SDNode *N,
  273. const SelectionDAG &DAG) {
  274. if (const auto *LS0 = dyn_cast<LSBaseSDNode>(N))
  275. return matchLSNode(LS0, DAG);
  276. if (const auto *LN = dyn_cast<LifetimeSDNode>(N)) {
  277. if (LN->hasOffset())
  278. return BaseIndexOffset(LN->getOperand(1), SDValue(), LN->getOffset(),
  279. false);
  280. return BaseIndexOffset(LN->getOperand(1), SDValue(), false);
  281. }
  282. return BaseIndexOffset();
  283. }
  284. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  285. LLVM_DUMP_METHOD void BaseIndexOffset::dump() const {
  286. print(dbgs());
  287. }
  288. void BaseIndexOffset::print(raw_ostream& OS) const {
  289. OS << "BaseIndexOffset base=[";
  290. Base->print(OS);
  291. OS << "] index=[";
  292. if (Index)
  293. Index->print(OS);
  294. OS << "] offset=" << Offset;
  295. }
  296. #endif