InstCombineNegator.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. //===- InstCombineNegator.cpp -----------------------------------*- C++ -*-===//
  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. // This file implements sinking of negation into expression trees,
  10. // as long as that can be done without increasing instruction count.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/Analysis/TargetFolder.h"
  24. #include "llvm/Analysis/ValueTracking.h"
  25. #include "llvm/IR/Constant.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DebugLoc.h"
  28. #include "llvm/IR/IRBuilder.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/PatternMatch.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/Use.h"
  34. #include "llvm/IR/User.h"
  35. #include "llvm/IR/Value.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/Compiler.h"
  39. #include "llvm/Support/DebugCounter.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  43. #include <cassert>
  44. #include <cstdint>
  45. #include <functional>
  46. #include <tuple>
  47. #include <type_traits>
  48. #include <utility>
  49. namespace llvm {
  50. class AssumptionCache;
  51. class DataLayout;
  52. class DominatorTree;
  53. class LLVMContext;
  54. } // namespace llvm
  55. using namespace llvm;
  56. #define DEBUG_TYPE "instcombine"
  57. STATISTIC(NegatorTotalNegationsAttempted,
  58. "Negator: Number of negations attempted to be sinked");
  59. STATISTIC(NegatorNumTreesNegated,
  60. "Negator: Number of negations successfully sinked");
  61. STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
  62. "reached while attempting to sink negation");
  63. STATISTIC(NegatorTimesDepthLimitReached,
  64. "Negator: How many times did the traversal depth limit was reached "
  65. "during sinking");
  66. STATISTIC(
  67. NegatorNumValuesVisited,
  68. "Negator: Total number of values visited during attempts to sink negation");
  69. STATISTIC(NegatorNumNegationsFoundInCache,
  70. "Negator: How many negations did we retrieve/reuse from cache");
  71. STATISTIC(NegatorMaxTotalValuesVisited,
  72. "Negator: Maximal number of values ever visited while attempting to "
  73. "sink negation");
  74. STATISTIC(NegatorNumInstructionsCreatedTotal,
  75. "Negator: Number of new negated instructions created, total");
  76. STATISTIC(NegatorMaxInstructionsCreated,
  77. "Negator: Maximal number of new instructions created during negation "
  78. "attempt");
  79. STATISTIC(NegatorNumInstructionsNegatedSuccess,
  80. "Negator: Number of new negated instructions created in successful "
  81. "negation sinking attempts");
  82. DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
  83. "Controls Negator transformations in InstCombine pass");
  84. static cl::opt<bool>
  85. NegatorEnabled("instcombine-negator-enabled", cl::init(true),
  86. cl::desc("Should we attempt to sink negations?"));
  87. static cl::opt<unsigned>
  88. NegatorMaxDepth("instcombine-negator-max-depth",
  89. cl::init(NegatorDefaultMaxDepth),
  90. cl::desc("What is the maximal lookup depth when trying to "
  91. "check for viability of negation sinking."));
  92. Negator::Negator(LLVMContext &C, const DataLayout &DL_, AssumptionCache &AC_,
  93. const DominatorTree &DT_, bool IsTrulyNegation_)
  94. : Builder(C, TargetFolder(DL_),
  95. IRBuilderCallbackInserter([&](Instruction *I) {
  96. ++NegatorNumInstructionsCreatedTotal;
  97. NewInstructions.push_back(I);
  98. })),
  99. DL(DL_), AC(AC_), DT(DT_), IsTrulyNegation(IsTrulyNegation_) {}
  100. #if LLVM_ENABLE_STATS
  101. Negator::~Negator() {
  102. NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
  103. }
  104. #endif
  105. // Due to the InstCombine's worklist management, there are no guarantees that
  106. // each instruction we'll encounter has been visited by InstCombine already.
  107. // In particular, most importantly for us, that means we have to canonicalize
  108. // constants to RHS ourselves, since that is helpful sometimes.
  109. std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
  110. assert(I->getNumOperands() == 2 && "Only for binops!");
  111. std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)};
  112. if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
  113. InstCombiner::getComplexity(I->getOperand(1)))
  114. std::swap(Ops[0], Ops[1]);
  115. return Ops;
  116. }
  117. // FIXME: can this be reworked into a worklist-based algorithm while preserving
  118. // the depth-first, early bailout traversal?
  119. [[nodiscard]] Value *Negator::visitImpl(Value *V, unsigned Depth) {
  120. // -(undef) -> undef.
  121. if (match(V, m_Undef()))
  122. return V;
  123. // In i1, negation can simply be ignored.
  124. if (V->getType()->isIntOrIntVectorTy(1))
  125. return V;
  126. Value *X;
  127. // -(-(X)) -> X.
  128. if (match(V, m_Neg(m_Value(X))))
  129. return X;
  130. // Integral constants can be freely negated.
  131. if (match(V, m_AnyIntegralConstant()))
  132. return ConstantExpr::getNeg(cast<Constant>(V), /*HasNUW=*/false,
  133. /*HasNSW=*/false);
  134. // If we have a non-instruction, then give up.
  135. if (!isa<Instruction>(V))
  136. return nullptr;
  137. // If we have started with a true negation (i.e. `sub 0, %y`), then if we've
  138. // got instruction that does not require recursive reasoning, we can still
  139. // negate it even if it has other uses, without increasing instruction count.
  140. if (!V->hasOneUse() && !IsTrulyNegation)
  141. return nullptr;
  142. auto *I = cast<Instruction>(V);
  143. unsigned BitWidth = I->getType()->getScalarSizeInBits();
  144. // We must preserve the insertion point and debug info that is set in the
  145. // builder at the time this function is called.
  146. InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
  147. // And since we are trying to negate instruction I, that tells us about the
  148. // insertion point and the debug info that we need to keep.
  149. Builder.SetInsertPoint(I);
  150. // In some cases we can give the answer without further recursion.
  151. switch (I->getOpcode()) {
  152. case Instruction::Add: {
  153. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  154. // `inc` is always negatible.
  155. if (match(Ops[1], m_One()))
  156. return Builder.CreateNot(Ops[0], I->getName() + ".neg");
  157. break;
  158. }
  159. case Instruction::Xor:
  160. // `not` is always negatible.
  161. if (match(I, m_Not(m_Value(X))))
  162. return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
  163. I->getName() + ".neg");
  164. break;
  165. case Instruction::AShr:
  166. case Instruction::LShr: {
  167. // Right-shift sign bit smear is negatible.
  168. const APInt *Op1Val;
  169. if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
  170. Value *BO = I->getOpcode() == Instruction::AShr
  171. ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1))
  172. : Builder.CreateAShr(I->getOperand(0), I->getOperand(1));
  173. if (auto *NewInstr = dyn_cast<Instruction>(BO)) {
  174. NewInstr->copyIRFlags(I);
  175. NewInstr->setName(I->getName() + ".neg");
  176. }
  177. return BO;
  178. }
  179. // While we could negate exact arithmetic shift:
  180. // ashr exact %x, C --> sdiv exact i8 %x, -1<<C
  181. // iff C != 0 and C u< bitwidth(%x), we don't want to,
  182. // because division is *THAT* much worse than a shift.
  183. break;
  184. }
  185. case Instruction::SExt:
  186. case Instruction::ZExt:
  187. // `*ext` of i1 is always negatible
  188. if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
  189. return I->getOpcode() == Instruction::SExt
  190. ? Builder.CreateZExt(I->getOperand(0), I->getType(),
  191. I->getName() + ".neg")
  192. : Builder.CreateSExt(I->getOperand(0), I->getType(),
  193. I->getName() + ".neg");
  194. break;
  195. case Instruction::Select: {
  196. // If both arms of the select are constants, we don't need to recurse.
  197. // Therefore, this transform is not limited by uses.
  198. auto *Sel = cast<SelectInst>(I);
  199. Constant *TrueC, *FalseC;
  200. if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
  201. match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
  202. Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
  203. Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
  204. return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
  205. I->getName() + ".neg", /*MDFrom=*/I);
  206. }
  207. break;
  208. }
  209. default:
  210. break; // Other instructions require recursive reasoning.
  211. }
  212. if (I->getOpcode() == Instruction::Sub &&
  213. (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
  214. // `sub` is always negatible.
  215. // However, only do this either if the old `sub` doesn't stick around, or
  216. // it was subtracting from a constant. Otherwise, this isn't profitable.
  217. return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
  218. I->getName() + ".neg");
  219. }
  220. // Some other cases, while still don't require recursion,
  221. // are restricted to the one-use case.
  222. if (!V->hasOneUse())
  223. return nullptr;
  224. switch (I->getOpcode()) {
  225. case Instruction::ZExt: {
  226. // Negation of zext of signbit is signbit splat:
  227. // 0 - (zext (i8 X u>> 7) to iN) --> sext (i8 X s>> 7) to iN
  228. Value *SrcOp = I->getOperand(0);
  229. unsigned SrcWidth = SrcOp->getType()->getScalarSizeInBits();
  230. const APInt &FullShift = APInt(SrcWidth, SrcWidth - 1);
  231. if (IsTrulyNegation &&
  232. match(SrcOp, m_LShr(m_Value(X), m_SpecificIntAllowUndef(FullShift)))) {
  233. Value *Ashr = Builder.CreateAShr(X, FullShift);
  234. return Builder.CreateSExt(Ashr, I->getType());
  235. }
  236. break;
  237. }
  238. case Instruction::And: {
  239. Constant *ShAmt;
  240. // sub(y,and(lshr(x,C),1)) --> add(ashr(shl(x,(BW-1)-C),BW-1),y)
  241. if (match(I, m_c_And(m_OneUse(m_TruncOrSelf(
  242. m_LShr(m_Value(X), m_ImmConstant(ShAmt)))),
  243. m_One()))) {
  244. unsigned BW = X->getType()->getScalarSizeInBits();
  245. Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1);
  246. Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt));
  247. R = Builder.CreateAShr(R, BWMinusOne);
  248. return Builder.CreateTruncOrBitCast(R, I->getType());
  249. }
  250. break;
  251. }
  252. case Instruction::SDiv:
  253. // `sdiv` is negatible if divisor is not undef/INT_MIN/1.
  254. // While this is normally not behind a use-check,
  255. // let's consider division to be special since it's costly.
  256. if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
  257. if (!Op1C->containsUndefOrPoisonElement() &&
  258. Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
  259. Value *BO =
  260. Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
  261. I->getName() + ".neg");
  262. if (auto *NewInstr = dyn_cast<Instruction>(BO))
  263. NewInstr->setIsExact(I->isExact());
  264. return BO;
  265. }
  266. }
  267. break;
  268. }
  269. // Rest of the logic is recursive, so if it's time to give up then it's time.
  270. if (Depth > NegatorMaxDepth) {
  271. LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
  272. << *V << ". Giving up.\n");
  273. ++NegatorTimesDepthLimitReached;
  274. return nullptr;
  275. }
  276. switch (I->getOpcode()) {
  277. case Instruction::Freeze: {
  278. // `freeze` is negatible if its operand is negatible.
  279. Value *NegOp = negate(I->getOperand(0), Depth + 1);
  280. if (!NegOp) // Early return.
  281. return nullptr;
  282. return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
  283. }
  284. case Instruction::PHI: {
  285. // `phi` is negatible if all the incoming values are negatible.
  286. auto *PHI = cast<PHINode>(I);
  287. SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
  288. for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
  289. if (!(std::get<1>(I) =
  290. negate(std::get<0>(I), Depth + 1))) // Early return.
  291. return nullptr;
  292. }
  293. // All incoming values are indeed negatible. Create negated PHI node.
  294. PHINode *NegatedPHI = Builder.CreatePHI(
  295. PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg");
  296. for (auto I : zip(NegatedIncomingValues, PHI->blocks()))
  297. NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I));
  298. return NegatedPHI;
  299. }
  300. case Instruction::Select: {
  301. if (isKnownNegation(I->getOperand(1), I->getOperand(2))) {
  302. // Of one hand of select is known to be negation of another hand,
  303. // just swap the hands around.
  304. auto *NewSelect = cast<SelectInst>(I->clone());
  305. // Just swap the operands of the select.
  306. NewSelect->swapValues();
  307. // Don't swap prof metadata, we didn't change the branch behavior.
  308. NewSelect->setName(I->getName() + ".neg");
  309. Builder.Insert(NewSelect);
  310. return NewSelect;
  311. }
  312. // `select` is negatible if both hands of `select` are negatible.
  313. Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
  314. if (!NegOp1) // Early return.
  315. return nullptr;
  316. Value *NegOp2 = negate(I->getOperand(2), Depth + 1);
  317. if (!NegOp2)
  318. return nullptr;
  319. // Do preserve the metadata!
  320. return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
  321. I->getName() + ".neg", /*MDFrom=*/I);
  322. }
  323. case Instruction::ShuffleVector: {
  324. // `shufflevector` is negatible if both operands are negatible.
  325. auto *Shuf = cast<ShuffleVectorInst>(I);
  326. Value *NegOp0 = negate(I->getOperand(0), Depth + 1);
  327. if (!NegOp0) // Early return.
  328. return nullptr;
  329. Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
  330. if (!NegOp1)
  331. return nullptr;
  332. return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
  333. I->getName() + ".neg");
  334. }
  335. case Instruction::ExtractElement: {
  336. // `extractelement` is negatible if source operand is negatible.
  337. auto *EEI = cast<ExtractElementInst>(I);
  338. Value *NegVector = negate(EEI->getVectorOperand(), Depth + 1);
  339. if (!NegVector) // Early return.
  340. return nullptr;
  341. return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
  342. I->getName() + ".neg");
  343. }
  344. case Instruction::InsertElement: {
  345. // `insertelement` is negatible if both the source vector and
  346. // element-to-be-inserted are negatible.
  347. auto *IEI = cast<InsertElementInst>(I);
  348. Value *NegVector = negate(IEI->getOperand(0), Depth + 1);
  349. if (!NegVector) // Early return.
  350. return nullptr;
  351. Value *NegNewElt = negate(IEI->getOperand(1), Depth + 1);
  352. if (!NegNewElt) // Early return.
  353. return nullptr;
  354. return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
  355. I->getName() + ".neg");
  356. }
  357. case Instruction::Trunc: {
  358. // `trunc` is negatible if its operand is negatible.
  359. Value *NegOp = negate(I->getOperand(0), Depth + 1);
  360. if (!NegOp) // Early return.
  361. return nullptr;
  362. return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
  363. }
  364. case Instruction::Shl: {
  365. // `shl` is negatible if the first operand is negatible.
  366. if (Value *NegOp0 = negate(I->getOperand(0), Depth + 1))
  367. return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg");
  368. // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
  369. auto *Op1C = dyn_cast<Constant>(I->getOperand(1));
  370. if (!Op1C || !IsTrulyNegation)
  371. return nullptr;
  372. return Builder.CreateMul(
  373. I->getOperand(0),
  374. ConstantExpr::getShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
  375. I->getName() + ".neg");
  376. }
  377. case Instruction::Or: {
  378. if (!haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL, &AC, I,
  379. &DT))
  380. return nullptr; // Don't know how to handle `or` in general.
  381. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  382. // `or`/`add` are interchangeable when operands have no common bits set.
  383. // `inc` is always negatible.
  384. if (match(Ops[1], m_One()))
  385. return Builder.CreateNot(Ops[0], I->getName() + ".neg");
  386. // Else, just defer to Instruction::Add handling.
  387. [[fallthrough]];
  388. }
  389. case Instruction::Add: {
  390. // `add` is negatible if both of its operands are negatible.
  391. SmallVector<Value *, 2> NegatedOps, NonNegatedOps;
  392. for (Value *Op : I->operands()) {
  393. // Can we sink the negation into this operand?
  394. if (Value *NegOp = negate(Op, Depth + 1)) {
  395. NegatedOps.emplace_back(NegOp); // Successfully negated operand!
  396. continue;
  397. }
  398. // Failed to sink negation into this operand. IFF we started from negation
  399. // and we manage to sink negation into one operand, we can still do this.
  400. if (!IsTrulyNegation)
  401. return nullptr;
  402. NonNegatedOps.emplace_back(Op); // Just record which operand that was.
  403. }
  404. assert((NegatedOps.size() + NonNegatedOps.size()) == 2 &&
  405. "Internal consistency check failed.");
  406. // Did we manage to sink negation into both of the operands?
  407. if (NegatedOps.size() == 2) // Then we get to keep the `add`!
  408. return Builder.CreateAdd(NegatedOps[0], NegatedOps[1],
  409. I->getName() + ".neg");
  410. assert(IsTrulyNegation && "We should have early-exited then.");
  411. // Completely failed to sink negation?
  412. if (NonNegatedOps.size() == 2)
  413. return nullptr;
  414. // 0-(a+b) --> (-a)-b
  415. return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0],
  416. I->getName() + ".neg");
  417. }
  418. case Instruction::Xor: {
  419. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  420. // `xor` is negatible if one of its operands is invertible.
  421. // FIXME: InstCombineInverter? But how to connect Inverter and Negator?
  422. if (auto *C = dyn_cast<Constant>(Ops[1])) {
  423. Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
  424. return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
  425. I->getName() + ".neg");
  426. }
  427. return nullptr;
  428. }
  429. case Instruction::Mul: {
  430. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  431. // `mul` is negatible if one of its operands is negatible.
  432. Value *NegatedOp, *OtherOp;
  433. // First try the second operand, in case it's a constant it will be best to
  434. // just invert it instead of sinking the `neg` deeper.
  435. if (Value *NegOp1 = negate(Ops[1], Depth + 1)) {
  436. NegatedOp = NegOp1;
  437. OtherOp = Ops[0];
  438. } else if (Value *NegOp0 = negate(Ops[0], Depth + 1)) {
  439. NegatedOp = NegOp0;
  440. OtherOp = Ops[1];
  441. } else
  442. // Can't negate either of them.
  443. return nullptr;
  444. return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg");
  445. }
  446. default:
  447. return nullptr; // Don't know, likely not negatible for free.
  448. }
  449. llvm_unreachable("Can't get here. We always return from switch.");
  450. }
  451. [[nodiscard]] Value *Negator::negate(Value *V, unsigned Depth) {
  452. NegatorMaxDepthVisited.updateMax(Depth);
  453. ++NegatorNumValuesVisited;
  454. #if LLVM_ENABLE_STATS
  455. ++NumValuesVisitedInThisNegator;
  456. #endif
  457. #ifndef NDEBUG
  458. // We can't ever have a Value with such an address.
  459. Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
  460. #endif
  461. // Did we already try to negate this value?
  462. auto NegationsCacheIterator = NegationsCache.find(V);
  463. if (NegationsCacheIterator != NegationsCache.end()) {
  464. ++NegatorNumNegationsFoundInCache;
  465. Value *NegatedV = NegationsCacheIterator->second;
  466. assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
  467. return NegatedV;
  468. }
  469. #ifndef NDEBUG
  470. // We did not find a cached result for negation of V. While there,
  471. // let's temporairly cache a placeholder value, with the idea that if later
  472. // during negation we fetch it from cache, we'll know we're in a cycle.
  473. NegationsCache[V] = Placeholder;
  474. #endif
  475. // No luck. Try negating it for real.
  476. Value *NegatedV = visitImpl(V, Depth);
  477. // And cache the (real) result for the future.
  478. NegationsCache[V] = NegatedV;
  479. return NegatedV;
  480. }
  481. [[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root) {
  482. Value *Negated = negate(Root, /*Depth=*/0);
  483. if (!Negated) {
  484. // We must cleanup newly-inserted instructions, to avoid any potential
  485. // endless combine looping.
  486. for (Instruction *I : llvm::reverse(NewInstructions))
  487. I->eraseFromParent();
  488. return std::nullopt;
  489. }
  490. return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
  491. }
  492. [[nodiscard]] Value *Negator::Negate(bool LHSIsZero, Value *Root,
  493. InstCombinerImpl &IC) {
  494. ++NegatorTotalNegationsAttempted;
  495. LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
  496. << "\n");
  497. if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
  498. return nullptr;
  499. Negator N(Root->getContext(), IC.getDataLayout(), IC.getAssumptionCache(),
  500. IC.getDominatorTree(), LHSIsZero);
  501. std::optional<Result> Res = N.run(Root);
  502. if (!Res) { // Negation failed.
  503. LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
  504. << "\n");
  505. return nullptr;
  506. }
  507. LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
  508. << "\n NEW: " << *Res->second << "\n");
  509. ++NegatorNumTreesNegated;
  510. // We must temporarily unset the 'current' insertion point and DebugLoc of the
  511. // InstCombine's IRBuilder so that it won't interfere with the ones we have
  512. // already specified when producing negated instructions.
  513. InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
  514. IC.Builder.ClearInsertionPoint();
  515. IC.Builder.SetCurrentDebugLocation(DebugLoc());
  516. // And finally, we must add newly-created instructions into the InstCombine's
  517. // worklist (in a proper order!) so it can attempt to combine them.
  518. LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
  519. << " instrs to InstCombine\n");
  520. NegatorMaxInstructionsCreated.updateMax(Res->first.size());
  521. NegatorNumInstructionsNegatedSuccess += Res->first.size();
  522. // They are in def-use order, so nothing fancy, just insert them in order.
  523. for (Instruction *I : Res->first)
  524. IC.Builder.Insert(I, I->getName());
  525. // And return the new root.
  526. return Res->second;
  527. }