Operator.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines various classes for working with Instructions and
  15. // ConstantExprs.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_OPERATOR_H
  19. #define LLVM_IR_OPERATOR_H
  20. #include "llvm/ADT/MapVector.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/FMF.h"
  23. #include "llvm/IR/Instruction.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/IR/Value.h"
  26. #include "llvm/Support/Casting.h"
  27. #include <cstddef>
  28. #include <optional>
  29. namespace llvm {
  30. /// This is a utility class that provides an abstraction for the common
  31. /// functionality between Instructions and ConstantExprs.
  32. class Operator : public User {
  33. public:
  34. // The Operator class is intended to be used as a utility, and is never itself
  35. // instantiated.
  36. Operator() = delete;
  37. ~Operator() = delete;
  38. void *operator new(size_t s) = delete;
  39. /// Return the opcode for this Instruction or ConstantExpr.
  40. unsigned getOpcode() const {
  41. if (const Instruction *I = dyn_cast<Instruction>(this))
  42. return I->getOpcode();
  43. return cast<ConstantExpr>(this)->getOpcode();
  44. }
  45. /// If V is an Instruction or ConstantExpr, return its opcode.
  46. /// Otherwise return UserOp1.
  47. static unsigned getOpcode(const Value *V) {
  48. if (const Instruction *I = dyn_cast<Instruction>(V))
  49. return I->getOpcode();
  50. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  51. return CE->getOpcode();
  52. return Instruction::UserOp1;
  53. }
  54. static bool classof(const Instruction *) { return true; }
  55. static bool classof(const ConstantExpr *) { return true; }
  56. static bool classof(const Value *V) {
  57. return isa<Instruction>(V) || isa<ConstantExpr>(V);
  58. }
  59. /// Return true if this operator has flags which may cause this operator
  60. /// to evaluate to poison despite having non-poison inputs.
  61. bool hasPoisonGeneratingFlags() const;
  62. /// Return true if this operator has poison-generating flags or metadata.
  63. /// The latter is only possible for instructions.
  64. bool hasPoisonGeneratingFlagsOrMetadata() const;
  65. };
  66. /// Utility class for integer operators which may exhibit overflow - Add, Sub,
  67. /// Mul, and Shl. It does not include SDiv, despite that operator having the
  68. /// potential for overflow.
  69. class OverflowingBinaryOperator : public Operator {
  70. public:
  71. enum {
  72. AnyWrap = 0,
  73. NoUnsignedWrap = (1 << 0),
  74. NoSignedWrap = (1 << 1)
  75. };
  76. private:
  77. friend class Instruction;
  78. friend class ConstantExpr;
  79. void setHasNoUnsignedWrap(bool B) {
  80. SubclassOptionalData =
  81. (SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
  82. }
  83. void setHasNoSignedWrap(bool B) {
  84. SubclassOptionalData =
  85. (SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
  86. }
  87. public:
  88. /// Test whether this operation is known to never
  89. /// undergo unsigned overflow, aka the nuw property.
  90. bool hasNoUnsignedWrap() const {
  91. return SubclassOptionalData & NoUnsignedWrap;
  92. }
  93. /// Test whether this operation is known to never
  94. /// undergo signed overflow, aka the nsw property.
  95. bool hasNoSignedWrap() const {
  96. return (SubclassOptionalData & NoSignedWrap) != 0;
  97. }
  98. static bool classof(const Instruction *I) {
  99. return I->getOpcode() == Instruction::Add ||
  100. I->getOpcode() == Instruction::Sub ||
  101. I->getOpcode() == Instruction::Mul ||
  102. I->getOpcode() == Instruction::Shl;
  103. }
  104. static bool classof(const ConstantExpr *CE) {
  105. return CE->getOpcode() == Instruction::Add ||
  106. CE->getOpcode() == Instruction::Sub ||
  107. CE->getOpcode() == Instruction::Mul ||
  108. CE->getOpcode() == Instruction::Shl;
  109. }
  110. static bool classof(const Value *V) {
  111. return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
  112. (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
  113. }
  114. };
  115. /// A udiv or sdiv instruction, which can be marked as "exact",
  116. /// indicating that no bits are destroyed.
  117. class PossiblyExactOperator : public Operator {
  118. public:
  119. enum {
  120. IsExact = (1 << 0)
  121. };
  122. private:
  123. friend class Instruction;
  124. friend class ConstantExpr;
  125. void setIsExact(bool B) {
  126. SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
  127. }
  128. public:
  129. /// Test whether this division is known to be exact, with zero remainder.
  130. bool isExact() const {
  131. return SubclassOptionalData & IsExact;
  132. }
  133. static bool isPossiblyExactOpcode(unsigned OpC) {
  134. return OpC == Instruction::SDiv ||
  135. OpC == Instruction::UDiv ||
  136. OpC == Instruction::AShr ||
  137. OpC == Instruction::LShr;
  138. }
  139. static bool classof(const ConstantExpr *CE) {
  140. return isPossiblyExactOpcode(CE->getOpcode());
  141. }
  142. static bool classof(const Instruction *I) {
  143. return isPossiblyExactOpcode(I->getOpcode());
  144. }
  145. static bool classof(const Value *V) {
  146. return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
  147. (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
  148. }
  149. };
  150. /// Utility class for floating point operations which can have
  151. /// information about relaxed accuracy requirements attached to them.
  152. class FPMathOperator : public Operator {
  153. private:
  154. friend class Instruction;
  155. /// 'Fast' means all bits are set.
  156. void setFast(bool B) {
  157. setHasAllowReassoc(B);
  158. setHasNoNaNs(B);
  159. setHasNoInfs(B);
  160. setHasNoSignedZeros(B);
  161. setHasAllowReciprocal(B);
  162. setHasAllowContract(B);
  163. setHasApproxFunc(B);
  164. }
  165. void setHasAllowReassoc(bool B) {
  166. SubclassOptionalData =
  167. (SubclassOptionalData & ~FastMathFlags::AllowReassoc) |
  168. (B * FastMathFlags::AllowReassoc);
  169. }
  170. void setHasNoNaNs(bool B) {
  171. SubclassOptionalData =
  172. (SubclassOptionalData & ~FastMathFlags::NoNaNs) |
  173. (B * FastMathFlags::NoNaNs);
  174. }
  175. void setHasNoInfs(bool B) {
  176. SubclassOptionalData =
  177. (SubclassOptionalData & ~FastMathFlags::NoInfs) |
  178. (B * FastMathFlags::NoInfs);
  179. }
  180. void setHasNoSignedZeros(bool B) {
  181. SubclassOptionalData =
  182. (SubclassOptionalData & ~FastMathFlags::NoSignedZeros) |
  183. (B * FastMathFlags::NoSignedZeros);
  184. }
  185. void setHasAllowReciprocal(bool B) {
  186. SubclassOptionalData =
  187. (SubclassOptionalData & ~FastMathFlags::AllowReciprocal) |
  188. (B * FastMathFlags::AllowReciprocal);
  189. }
  190. void setHasAllowContract(bool B) {
  191. SubclassOptionalData =
  192. (SubclassOptionalData & ~FastMathFlags::AllowContract) |
  193. (B * FastMathFlags::AllowContract);
  194. }
  195. void setHasApproxFunc(bool B) {
  196. SubclassOptionalData =
  197. (SubclassOptionalData & ~FastMathFlags::ApproxFunc) |
  198. (B * FastMathFlags::ApproxFunc);
  199. }
  200. /// Convenience function for setting multiple fast-math flags.
  201. /// FMF is a mask of the bits to set.
  202. void setFastMathFlags(FastMathFlags FMF) {
  203. SubclassOptionalData |= FMF.Flags;
  204. }
  205. /// Convenience function for copying all fast-math flags.
  206. /// All values in FMF are transferred to this operator.
  207. void copyFastMathFlags(FastMathFlags FMF) {
  208. SubclassOptionalData = FMF.Flags;
  209. }
  210. public:
  211. /// Test if this operation allows all non-strict floating-point transforms.
  212. bool isFast() const {
  213. return ((SubclassOptionalData & FastMathFlags::AllowReassoc) != 0 &&
  214. (SubclassOptionalData & FastMathFlags::NoNaNs) != 0 &&
  215. (SubclassOptionalData & FastMathFlags::NoInfs) != 0 &&
  216. (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0 &&
  217. (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0 &&
  218. (SubclassOptionalData & FastMathFlags::AllowContract) != 0 &&
  219. (SubclassOptionalData & FastMathFlags::ApproxFunc) != 0);
  220. }
  221. /// Test if this operation may be simplified with reassociative transforms.
  222. bool hasAllowReassoc() const {
  223. return (SubclassOptionalData & FastMathFlags::AllowReassoc) != 0;
  224. }
  225. /// Test if this operation's arguments and results are assumed not-NaN.
  226. bool hasNoNaNs() const {
  227. return (SubclassOptionalData & FastMathFlags::NoNaNs) != 0;
  228. }
  229. /// Test if this operation's arguments and results are assumed not-infinite.
  230. bool hasNoInfs() const {
  231. return (SubclassOptionalData & FastMathFlags::NoInfs) != 0;
  232. }
  233. /// Test if this operation can ignore the sign of zero.
  234. bool hasNoSignedZeros() const {
  235. return (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0;
  236. }
  237. /// Test if this operation can use reciprocal multiply instead of division.
  238. bool hasAllowReciprocal() const {
  239. return (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0;
  240. }
  241. /// Test if this operation can be floating-point contracted (FMA).
  242. bool hasAllowContract() const {
  243. return (SubclassOptionalData & FastMathFlags::AllowContract) != 0;
  244. }
  245. /// Test if this operation allows approximations of math library functions or
  246. /// intrinsics.
  247. bool hasApproxFunc() const {
  248. return (SubclassOptionalData & FastMathFlags::ApproxFunc) != 0;
  249. }
  250. /// Convenience function for getting all the fast-math flags
  251. FastMathFlags getFastMathFlags() const {
  252. return FastMathFlags(SubclassOptionalData);
  253. }
  254. /// Get the maximum error permitted by this operation in ULPs. An accuracy of
  255. /// 0.0 means that the operation should be performed with the default
  256. /// precision.
  257. float getFPAccuracy() const;
  258. static bool classof(const Value *V) {
  259. unsigned Opcode;
  260. if (auto *I = dyn_cast<Instruction>(V))
  261. Opcode = I->getOpcode();
  262. else if (auto *CE = dyn_cast<ConstantExpr>(V))
  263. Opcode = CE->getOpcode();
  264. else
  265. return false;
  266. switch (Opcode) {
  267. case Instruction::FNeg:
  268. case Instruction::FAdd:
  269. case Instruction::FSub:
  270. case Instruction::FMul:
  271. case Instruction::FDiv:
  272. case Instruction::FRem:
  273. // FIXME: To clean up and correct the semantics of fast-math-flags, FCmp
  274. // should not be treated as a math op, but the other opcodes should.
  275. // This would make things consistent with Select/PHI (FP value type
  276. // determines whether they are math ops and, therefore, capable of
  277. // having fast-math-flags).
  278. case Instruction::FCmp:
  279. return true;
  280. case Instruction::PHI:
  281. case Instruction::Select:
  282. case Instruction::Call: {
  283. Type *Ty = V->getType();
  284. while (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty))
  285. Ty = ArrTy->getElementType();
  286. return Ty->isFPOrFPVectorTy();
  287. }
  288. default:
  289. return false;
  290. }
  291. }
  292. };
  293. /// A helper template for defining operators for individual opcodes.
  294. template<typename SuperClass, unsigned Opc>
  295. class ConcreteOperator : public SuperClass {
  296. public:
  297. static bool classof(const Instruction *I) {
  298. return I->getOpcode() == Opc;
  299. }
  300. static bool classof(const ConstantExpr *CE) {
  301. return CE->getOpcode() == Opc;
  302. }
  303. static bool classof(const Value *V) {
  304. return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
  305. (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
  306. }
  307. };
  308. class AddOperator
  309. : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
  310. };
  311. class SubOperator
  312. : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
  313. };
  314. class MulOperator
  315. : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
  316. };
  317. class ShlOperator
  318. : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
  319. };
  320. class SDivOperator
  321. : public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
  322. };
  323. class UDivOperator
  324. : public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
  325. };
  326. class AShrOperator
  327. : public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
  328. };
  329. class LShrOperator
  330. : public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
  331. };
  332. class ZExtOperator : public ConcreteOperator<Operator, Instruction::ZExt> {};
  333. class GEPOperator
  334. : public ConcreteOperator<Operator, Instruction::GetElementPtr> {
  335. friend class GetElementPtrInst;
  336. friend class ConstantExpr;
  337. enum {
  338. IsInBounds = (1 << 0),
  339. // InRangeIndex: bits 1-6
  340. };
  341. void setIsInBounds(bool B) {
  342. SubclassOptionalData =
  343. (SubclassOptionalData & ~IsInBounds) | (B * IsInBounds);
  344. }
  345. public:
  346. /// Test whether this is an inbounds GEP, as defined by LangRef.html.
  347. bool isInBounds() const {
  348. return SubclassOptionalData & IsInBounds;
  349. }
  350. /// Returns the offset of the index with an inrange attachment, or
  351. /// std::nullopt if none.
  352. std::optional<unsigned> getInRangeIndex() const {
  353. if (SubclassOptionalData >> 1 == 0)
  354. return std::nullopt;
  355. return (SubclassOptionalData >> 1) - 1;
  356. }
  357. inline op_iterator idx_begin() { return op_begin()+1; }
  358. inline const_op_iterator idx_begin() const { return op_begin()+1; }
  359. inline op_iterator idx_end() { return op_end(); }
  360. inline const_op_iterator idx_end() const { return op_end(); }
  361. inline iterator_range<op_iterator> indices() {
  362. return make_range(idx_begin(), idx_end());
  363. }
  364. inline iterator_range<const_op_iterator> indices() const {
  365. return make_range(idx_begin(), idx_end());
  366. }
  367. Value *getPointerOperand() {
  368. return getOperand(0);
  369. }
  370. const Value *getPointerOperand() const {
  371. return getOperand(0);
  372. }
  373. static unsigned getPointerOperandIndex() {
  374. return 0U; // get index for modifying correct operand
  375. }
  376. /// Method to return the pointer operand as a PointerType.
  377. Type *getPointerOperandType() const {
  378. return getPointerOperand()->getType();
  379. }
  380. Type *getSourceElementType() const;
  381. Type *getResultElementType() const;
  382. /// Method to return the address space of the pointer operand.
  383. unsigned getPointerAddressSpace() const {
  384. return getPointerOperandType()->getPointerAddressSpace();
  385. }
  386. unsigned getNumIndices() const { // Note: always non-negative
  387. return getNumOperands() - 1;
  388. }
  389. bool hasIndices() const {
  390. return getNumOperands() > 1;
  391. }
  392. /// Return true if all of the indices of this GEP are zeros.
  393. /// If so, the result pointer and the first operand have the same
  394. /// value, just potentially different types.
  395. bool hasAllZeroIndices() const {
  396. for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
  397. if (ConstantInt *C = dyn_cast<ConstantInt>(I))
  398. if (C->isZero())
  399. continue;
  400. return false;
  401. }
  402. return true;
  403. }
  404. /// Return true if all of the indices of this GEP are constant integers.
  405. /// If so, the result pointer and the first operand have
  406. /// a constant offset between them.
  407. bool hasAllConstantIndices() const {
  408. for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
  409. if (!isa<ConstantInt>(I))
  410. return false;
  411. }
  412. return true;
  413. }
  414. unsigned countNonConstantIndices() const {
  415. return count_if(indices(), [](const Use& use) {
  416. return !isa<ConstantInt>(*use);
  417. });
  418. }
  419. /// Compute the maximum alignment that this GEP is garranteed to preserve.
  420. Align getMaxPreservedAlignment(const DataLayout &DL) const;
  421. /// Accumulate the constant address offset of this GEP if possible.
  422. ///
  423. /// This routine accepts an APInt into which it will try to accumulate the
  424. /// constant offset of this GEP.
  425. ///
  426. /// If \p ExternalAnalysis is provided it will be used to calculate a offset
  427. /// when a operand of GEP is not constant.
  428. /// For example, for a value \p ExternalAnalysis might try to calculate a
  429. /// lower bound. If \p ExternalAnalysis is successful, it should return true.
  430. ///
  431. /// If the \p ExternalAnalysis returns false or the value returned by \p
  432. /// ExternalAnalysis results in a overflow/underflow, this routine returns
  433. /// false and the value of the offset APInt is undefined (it is *not*
  434. /// preserved!).
  435. ///
  436. /// The APInt passed into this routine must be at exactly as wide as the
  437. /// IntPtr type for the address space of the base GEP pointer.
  438. bool accumulateConstantOffset(
  439. const DataLayout &DL, APInt &Offset,
  440. function_ref<bool(Value &, APInt &)> ExternalAnalysis = nullptr) const;
  441. static bool accumulateConstantOffset(
  442. Type *SourceType, ArrayRef<const Value *> Index, const DataLayout &DL,
  443. APInt &Offset,
  444. function_ref<bool(Value &, APInt &)> ExternalAnalysis = nullptr);
  445. /// Collect the offset of this GEP as a map of Values to their associated
  446. /// APInt multipliers, as well as a total Constant Offset.
  447. bool collectOffset(const DataLayout &DL, unsigned BitWidth,
  448. MapVector<Value *, APInt> &VariableOffsets,
  449. APInt &ConstantOffset) const;
  450. };
  451. class PtrToIntOperator
  452. : public ConcreteOperator<Operator, Instruction::PtrToInt> {
  453. friend class PtrToInt;
  454. friend class ConstantExpr;
  455. public:
  456. Value *getPointerOperand() {
  457. return getOperand(0);
  458. }
  459. const Value *getPointerOperand() const {
  460. return getOperand(0);
  461. }
  462. static unsigned getPointerOperandIndex() {
  463. return 0U; // get index for modifying correct operand
  464. }
  465. /// Method to return the pointer operand as a PointerType.
  466. Type *getPointerOperandType() const {
  467. return getPointerOperand()->getType();
  468. }
  469. /// Method to return the address space of the pointer operand.
  470. unsigned getPointerAddressSpace() const {
  471. return cast<PointerType>(getPointerOperandType())->getAddressSpace();
  472. }
  473. };
  474. class BitCastOperator
  475. : public ConcreteOperator<Operator, Instruction::BitCast> {
  476. friend class BitCastInst;
  477. friend class ConstantExpr;
  478. public:
  479. Type *getSrcTy() const {
  480. return getOperand(0)->getType();
  481. }
  482. Type *getDestTy() const {
  483. return getType();
  484. }
  485. };
  486. class AddrSpaceCastOperator
  487. : public ConcreteOperator<Operator, Instruction::AddrSpaceCast> {
  488. friend class AddrSpaceCastInst;
  489. friend class ConstantExpr;
  490. public:
  491. Value *getPointerOperand() { return getOperand(0); }
  492. const Value *getPointerOperand() const { return getOperand(0); }
  493. unsigned getSrcAddressSpace() const {
  494. return getPointerOperand()->getType()->getPointerAddressSpace();
  495. }
  496. unsigned getDestAddressSpace() const {
  497. return getType()->getPointerAddressSpace();
  498. }
  499. };
  500. } // end namespace llvm
  501. #endif // LLVM_IR_OPERATOR_H
  502. #ifdef __GNUC__
  503. #pragma GCC diagnostic pop
  504. #endif