LLVM 24.0.0git
InstCombineNegator.cpp
Go to the documentation of this file.
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
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.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"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Use.h"
34#include "llvm/IR/User.h"
35#include "llvm/IR/Value.h"
42#include <cassert>
43#include <cstdint>
44#include <functional>
45#include <utility>
46
47using namespace llvm;
48using namespace llvm::PatternMatch;
49
50#define DEBUG_TYPE "instcombine"
51
52STATISTIC(NegatorTotalNegationsAttempted,
53 "Negator: Number of negations attempted to be sinked");
54STATISTIC(NegatorNumTreesNegated,
55 "Negator: Number of negations successfully sinked");
56STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
57 "reached while attempting to sink negation");
58STATISTIC(NegatorTimesDepthLimitReached,
59 "Negator: How many times did the traversal depth limit was reached "
60 "during sinking");
62 NegatorNumValuesVisited,
63 "Negator: Total number of values visited during attempts to sink negation");
64STATISTIC(NegatorNumNegationsFoundInCache,
65 "Negator: How many negations did we retrieve/reuse from cache");
66STATISTIC(NegatorMaxTotalValuesVisited,
67 "Negator: Maximal number of values ever visited while attempting to "
68 "sink negation");
69STATISTIC(NegatorNumInstructionsCreatedTotal,
70 "Negator: Number of new negated instructions created, total");
71STATISTIC(NegatorMaxInstructionsCreated,
72 "Negator: Maximal number of new instructions created during negation "
73 "attempt");
74STATISTIC(NegatorNumInstructionsNegatedSuccess,
75 "Negator: Number of new negated instructions created in successful "
76 "negation sinking attempts");
77
78DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
79 "Controls Negator transformations in InstCombine pass");
80
81Negator::Negator(LLVMContext &C, const DataLayout &DL, const DominatorTree &DT_,
82 bool IsTrulyNegation_, unsigned MaxDepth)
83 : Builder(C, TargetFolder(DL),
85 ++NegatorNumInstructionsCreatedTotal;
86 NewInstructions.push_back(I);
87 })),
88 DT(DT_), IsTrulyNegation(IsTrulyNegation_), MaxDepth(MaxDepth) {}
89
90#if LLVM_ENABLE_STATS
91Negator::~Negator() {
92 NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
93}
94#endif
95
96// Due to the InstCombine's worklist management, there are no guarantees that
97// each instruction we'll encounter has been visited by InstCombine already.
98// In particular, most importantly for us, that means we have to canonicalize
99// constants to RHS ourselves, since that is helpful sometimes.
100std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
101 assert(I->getNumOperands() == 2 && "Only for binops!");
102 std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)};
103 if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
104 InstCombiner::getComplexity(I->getOperand(1)))
105 std::swap(Ops[0], Ops[1]);
106 return Ops;
107}
108
109// FIXME: can this be reworked into a worklist-based algorithm while preserving
110// the depth-first, early bailout traversal?
111[[nodiscard]] Value *Negator::visitImpl(Value *V, bool IsNSW, unsigned Depth) {
112 // -(undef) -> undef.
113 if (match(V, m_Undef()))
114 return V;
115
116 // In i1, negation can simply be ignored.
117 if (V->getType()->isIntOrIntVectorTy(1))
118 return V;
119
120 Value *X;
121
122 // -(-(X)) -> X.
123 if (match(V, m_Neg(m_Value(X))))
124 return X;
125
126 // Integral constants can be freely negated.
129 /*HasNSW=*/false);
130
131 // If we have a non-instruction, then give up.
132 if (!isa<Instruction>(V))
133 return nullptr;
134
135 // If we have started with a true negation (i.e. `sub 0, %y`), then if we've
136 // got instruction that does not require recursive reasoning, we can still
137 // negate it even if it has other uses, without increasing instruction count.
138 if (!V->hasOneUse() && !IsTrulyNegation)
139 return nullptr;
140
141 auto *I = cast<Instruction>(V);
142 unsigned BitWidth = I->getType()->getScalarSizeInBits();
143
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
151 // In some cases we can give the answer without further recursion.
152 switch (I->getOpcode()) {
153 case Instruction::Add: {
154 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
155 // `inc` is always negatible.
156 if (match(Ops[1], m_One()))
157 return Builder.CreateNot(Ops[0], I->getName() + ".neg");
158 break;
159 }
160 case Instruction::Xor:
161 // `not` is always negatible.
162 if (match(I, m_Not(m_Value(X))))
163 return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
164 I->getName() + ".neg");
165 break;
166 case Instruction::AShr:
167 case Instruction::LShr: {
168 // Right-shift sign bit smear is negatible.
169 const APInt *Op1Val;
170 if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
171 Value *BO = I->getOpcode() == Instruction::AShr
172 ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1))
173 : Builder.CreateAShr(I->getOperand(0), I->getOperand(1));
174 if (auto *NewInstr = dyn_cast<Instruction>(BO)) {
175 NewInstr->copyIRFlags(I);
176 NewInstr->setName(I->getName() + ".neg");
177 }
178 return BO;
179 }
180 // While we could negate exact arithmetic shift:
181 // ashr exact %x, C --> sdiv exact i8 %x, -1<<C
182 // iff C != 0 and C u< bitwidth(%x), we don't want to,
183 // because division is *THAT* much worse than a shift.
184 break;
185 }
186 case Instruction::SExt:
187 case Instruction::ZExt:
188 // `*ext` of i1 is always negatible
189 if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
190 return I->getOpcode() == Instruction::SExt
191 ? Builder.CreateZExt(I->getOperand(0), I->getType(),
192 I->getName() + ".neg")
193 : Builder.CreateSExt(I->getOperand(0), I->getType(),
194 I->getName() + ".neg");
195 break;
196 case Instruction::Select: {
197 // If both arms of the select are constants, we don't need to recurse.
198 // Therefore, this transform is not limited by uses.
199 auto *Sel = cast<SelectInst>(I);
200 Constant *TrueC, *FalseC;
201 if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
202 match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
203 Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
204 Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
205 return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
206 I->getName() + ".neg", /*MDFrom=*/I);
207 }
208 break;
209 }
210 case Instruction::Call:
211 if (auto *CI = dyn_cast<CmpIntrinsic>(I); CI && CI->hasOneUse())
212 return Builder.CreateIntrinsic(CI->getType(), CI->getIntrinsicID(),
213 {CI->getRHS(), CI->getLHS()});
214 break;
215 default:
216 break; // Other instructions require recursive reasoning.
217 }
218
219 if (I->getOpcode() == Instruction::Sub &&
220 (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
221 // `sub` is always negatible.
222 // However, only do this either if the old `sub` doesn't stick around, or
223 // it was subtracting from a constant. Otherwise, this isn't profitable.
224 return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
225 I->getName() + ".neg", /*HasNUW=*/false,
226 IsNSW && I->hasNoSignedWrap());
227 }
228
229 // Some other cases, while still don't require recursion,
230 // are restricted to the one-use case.
231 if (!V->hasOneUse())
232 return nullptr;
233
234 switch (I->getOpcode()) {
235 case Instruction::ZExt: {
236 // Negation of zext of signbit is signbit splat:
237 // 0 - (zext (i8 X u>> 7) to iN) --> sext (i8 X s>> 7) to iN
238 Value *SrcOp = I->getOperand(0);
239 unsigned SrcWidth = SrcOp->getType()->getScalarSizeInBits();
240 const APInt &FullShift = APInt(SrcWidth, SrcWidth - 1);
241 if (IsTrulyNegation &&
242 match(SrcOp, m_LShr(m_Value(X), m_SpecificIntAllowPoison(FullShift)))) {
243 Value *Ashr = Builder.CreateAShr(X, FullShift);
244 return Builder.CreateSExt(Ashr, I->getType());
245 }
246 break;
247 }
248 case Instruction::And: {
249 Constant *ShAmt;
250 // sub(0,and(lshr(x,C),1)) --> add(ashr(shl(x,(BW-1)-C),BW-1),0)
251 // Only applies when this is a true negation (LHS is zero). For the
252 // general sub(y,and(lshr(x,C),1)) case the rewrite replaces one 2-insn
253 // sequence with another without reducing instruction count, and the
254 // resulting shl/ashr form prevents later target-specific combines (e.g.
255 // on PowerPC the original lshr+and maps to a single rldicl, while the
256 // shl+ashr form requires sldi+sradi).
257 if (IsTrulyNegation &&
259 m_LShr(m_Value(X), m_ImmConstant(ShAmt)))),
260 m_One()))) {
261 unsigned BW = X->getType()->getScalarSizeInBits();
262 Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1);
263 Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt));
264 R = Builder.CreateAShr(R, BWMinusOne);
265 return Builder.CreateTruncOrBitCast(R, I->getType());
266 }
267 break;
268 }
269 case Instruction::SDiv:
270 // `sdiv` is negatible if divisor is not undef/INT_MIN/1.
271 // While this is normally not behind a use-check,
272 // let's consider division to be special since it's costly.
273 if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
274 if (!Op1C->containsUndefOrPoisonElement() &&
275 Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
276 Value *BO =
277 Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
278 I->getName() + ".neg");
279 if (auto *NewInstr = dyn_cast<Instruction>(BO))
280 NewInstr->setIsExact(I->isExact());
281 return BO;
282 }
283 }
284 break;
285 }
286
287 // Rest of the logic is recursive, so if it's time to give up then it's time.
288 if (Depth > MaxDepth) {
289 LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
290 << *V << ". Giving up.\n");
291 ++NegatorTimesDepthLimitReached;
292 return nullptr;
293 }
294
295 switch (I->getOpcode()) {
296 case Instruction::Freeze: {
297 // `freeze` is negatible if its operand is negatible.
298 Value *NegOp = negate(I->getOperand(0), IsNSW, Depth + 1);
299 if (!NegOp) // Early return.
300 return nullptr;
301 return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
302 }
303 case Instruction::PHI: {
304 // `phi` is negatible if all the incoming values are negatible.
305 auto *PHI = cast<PHINode>(I);
306 SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
307 for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
308 // Don't negate indvars to avoid infinite loops.
309 if (DT.dominates(PHI->getParent(), std::get<0>(I)))
310 return nullptr;
311 if (!(std::get<1>(I) =
312 negate(std::get<0>(I), IsNSW, Depth + 1))) // Early return.
313 return nullptr;
314 }
315 // All incoming values are indeed negatible. Create negated PHI node.
316 PHINode *NegatedPHI = Builder.CreatePHI(
317 PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg");
318 for (auto I : zip(NegatedIncomingValues, PHI->blocks()))
319 NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I));
320 return NegatedPHI;
321 }
322 case Instruction::Select: {
323 if (isKnownNegation(I->getOperand(1), I->getOperand(2), /*NeedNSW=*/false,
324 /*AllowPoison=*/false)) {
325 // Of one hand of select is known to be negation of another hand,
326 // just swap the hands around.
327 auto *NewSelect = cast<SelectInst>(I->clone());
328 // Just swap the operands of the select.
329 NewSelect->swapValues();
330 // Don't swap prof metadata, we didn't change the branch behavior.
331 NewSelect->setName(I->getName() + ".neg");
332 // Poison-generating flags should be dropped
333 Value *TV = NewSelect->getTrueValue();
334 Value *FV = NewSelect->getFalseValue();
335 if (match(TV, m_Neg(m_Specific(FV))))
336 cast<Instruction>(TV)->dropPoisonGeneratingFlags();
337 else if (match(FV, m_Neg(m_Specific(TV))))
338 cast<Instruction>(FV)->dropPoisonGeneratingFlags();
339 else {
340 cast<Instruction>(TV)->dropPoisonGeneratingFlags();
341 cast<Instruction>(FV)->dropPoisonGeneratingFlags();
342 }
343 Builder.Insert(NewSelect);
344 return NewSelect;
345 }
346 // `select` is negatible if both hands of `select` are negatible.
347 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
348 if (!NegOp1) // Early return.
349 return nullptr;
350 Value *NegOp2 = negate(I->getOperand(2), IsNSW, Depth + 1);
351 if (!NegOp2)
352 return nullptr;
353 // Do preserve the metadata!
354 return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
355 I->getName() + ".neg", /*MDFrom=*/I);
356 }
357 case Instruction::ShuffleVector: {
358 // `shufflevector` is negatible if both operands are negatible.
359 auto *Shuf = cast<ShuffleVectorInst>(I);
360 Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1);
361 if (!NegOp0) // Early return.
362 return nullptr;
363 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
364 if (!NegOp1)
365 return nullptr;
366 return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
367 I->getName() + ".neg");
368 }
369 case Instruction::ExtractElement: {
370 // `extractelement` is negatible if source operand is negatible.
371 auto *EEI = cast<ExtractElementInst>(I);
372 Value *NegVector = negate(EEI->getVectorOperand(), IsNSW, Depth + 1);
373 if (!NegVector) // Early return.
374 return nullptr;
375 return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
376 I->getName() + ".neg");
377 }
378 case Instruction::InsertElement: {
379 // `insertelement` is negatible if both the source vector and
380 // element-to-be-inserted are negatible.
381 auto *IEI = cast<InsertElementInst>(I);
382 Value *NegVector = negate(IEI->getOperand(0), IsNSW, Depth + 1);
383 if (!NegVector) // Early return.
384 return nullptr;
385 Value *NegNewElt = negate(IEI->getOperand(1), IsNSW, Depth + 1);
386 if (!NegNewElt) // Early return.
387 return nullptr;
388 return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
389 I->getName() + ".neg");
390 }
391 case Instruction::Trunc: {
392 // `trunc` is negatible if its operand is negatible.
393 Value *NegOp = negate(I->getOperand(0), /* IsNSW */ false, Depth + 1);
394 if (!NegOp) // Early return.
395 return nullptr;
396 return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
397 }
398 case Instruction::Shl: {
399 // `shl` is negatible if the first operand is negatible.
400 IsNSW &= I->hasNoSignedWrap();
401 if (Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1))
402 return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg",
403 /*HasNUW=*/false, IsNSW);
404 // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
405 Constant *Op1C;
406 if (!match(I->getOperand(1), m_ImmConstant(Op1C)) || !IsTrulyNegation)
407 return nullptr;
408 return Builder.CreateMul(
409 I->getOperand(0),
410 Builder.CreateShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
411 I->getName() + ".neg", /*HasNUW=*/false, IsNSW);
412 }
413 case Instruction::Or: {
414 if (!cast<PossiblyDisjointInst>(I)->isDisjoint())
415 return nullptr; // Don't know how to handle `or` in general.
416 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
417 // `or`/`add` are interchangeable when operands have no common bits set.
418 // `inc` is always negatible.
419 if (match(Ops[1], m_One()))
420 return Builder.CreateNot(Ops[0], I->getName() + ".neg");
421 // Else, just defer to Instruction::Add handling.
422 [[fallthrough]];
423 }
424 case Instruction::Add: {
425 // `add` is negatible if both of its operands are negatible.
426 SmallVector<Value *, 2> NegatedOps, NonNegatedOps;
427 for (Value *Op : I->operands()) {
428 // Can we sink the negation into this operand?
429 if (Value *NegOp = negate(Op, /* IsNSW */ false, Depth + 1)) {
430 NegatedOps.emplace_back(NegOp); // Successfully negated operand!
431 continue;
432 }
433 // Failed to sink negation into this operand. IFF we started from negation
434 // and we manage to sink negation into one operand, we can still do this.
435 if (!IsTrulyNegation)
436 return nullptr;
437 NonNegatedOps.emplace_back(Op); // Just record which operand that was.
438 }
439 assert((NegatedOps.size() + NonNegatedOps.size()) == 2 &&
440 "Internal consistency check failed.");
441 // Did we manage to sink negation into both of the operands?
442 if (NegatedOps.size() == 2) // Then we get to keep the `add`!
443 return Builder.CreateAdd(NegatedOps[0], NegatedOps[1],
444 I->getName() + ".neg");
445 assert(IsTrulyNegation && "We should have early-exited then.");
446 // Completely failed to sink negation?
447 if (NonNegatedOps.size() == 2)
448 return nullptr;
449 // 0-(a+b) --> (-a)-b
450 return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0],
451 I->getName() + ".neg");
452 }
453 case Instruction::Xor: {
454 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
455 // `xor` is negatible if one of its operands is invertible.
456 // FIXME: InstCombineInverter? But how to connect Inverter and Negator?
457 if (auto *C = dyn_cast<Constant>(Ops[1])) {
458 if (IsTrulyNegation) {
459 Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
460 return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
461 I->getName() + ".neg");
462 }
463 }
464 return nullptr;
465 }
466 case Instruction::Mul: {
467 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
468 // `mul` is negatible if one of its operands is negatible.
469 Value *NegatedOp, *OtherOp;
470 // First try the second operand, in case it's a constant it will be best to
471 // just invert it instead of sinking the `neg` deeper.
472 if (Value *NegOp1 = negate(Ops[1], /* IsNSW */ false, Depth + 1)) {
473 NegatedOp = NegOp1;
474 OtherOp = Ops[0];
475 } else if (Value *NegOp0 = negate(Ops[0], /* IsNSW */ false, Depth + 1)) {
476 NegatedOp = NegOp0;
477 OtherOp = Ops[1];
478 } else
479 // Can't negate either of them.
480 return nullptr;
481 return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg",
482 /*HasNUW=*/false, IsNSW && I->hasNoSignedWrap());
483 }
484 default:
485 return nullptr; // Don't know, likely not negatible for free.
486 }
487
488 llvm_unreachable("Can't get here. We always return from switch.");
489}
490
491[[nodiscard]] Value *Negator::negate(Value *V, bool IsNSW, unsigned Depth) {
492 NegatorMaxDepthVisited.updateMax(Depth);
493 ++NegatorNumValuesVisited;
494
495#if LLVM_ENABLE_STATS
496 ++NumValuesVisitedInThisNegator;
497#endif
498
499#ifndef NDEBUG
500 // We can't ever have a Value with such an address.
501 Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
502#endif
503
504 // Did we already try to negate this value?
505 auto NegationsCacheIterator = NegationsCache.find(V);
506 if (NegationsCacheIterator != NegationsCache.end()) {
507 ++NegatorNumNegationsFoundInCache;
508 Value *NegatedV = NegationsCacheIterator->second;
509 assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
510 return NegatedV;
511 }
512
513#ifndef NDEBUG
514 // We did not find a cached result for negation of V. While there,
515 // let's temporairly cache a placeholder value, with the idea that if later
516 // during negation we fetch it from cache, we'll know we're in a cycle.
517 NegationsCache[V] = Placeholder;
518#endif
519
520 // No luck. Try negating it for real.
521 Value *NegatedV = visitImpl(V, IsNSW, Depth);
522 // And cache the (real) result for the future.
523 NegationsCache[V] = NegatedV;
524
525 return NegatedV;
526}
527
528[[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root,
529 bool IsNSW) {
530 Value *Negated = negate(Root, IsNSW, /*Depth=*/0);
531 if (!Negated) {
532 // We must cleanup newly-inserted instructions, to avoid any potential
533 // endless combine looping.
534 for (Instruction *I : llvm::reverse(NewInstructions))
535 I->eraseFromParent();
536 return std::nullopt;
537 }
538 return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
539}
540
541[[nodiscard]] Value *Negator::Negate(bool LHSIsZero, bool IsNSW, Value *Root,
542 InstCombinerImpl &IC) {
543 ++NegatorTotalNegationsAttempted;
544 LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
545 << "\n");
546
547 if (!IC.CLOpts.negator_enabled ||
548 !DebugCounter::shouldExecute(NegatorCounter))
549 return nullptr;
550
551 Negator N(Root->getContext(), IC.getDataLayout(), IC.getDominatorTree(),
552 LHSIsZero, IC.CLOpts.negator_max_depth);
553 std::optional<Result> Res = N.run(Root, IsNSW);
554 if (!Res) { // Negation failed.
555 LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
556 << "\n");
557 return nullptr;
558 }
559
560 LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
561 << "\n NEW: " << *Res->second << "\n");
562 ++NegatorNumTreesNegated;
563
564 // And finally, we must add newly-created instructions into the InstCombine's
565 // worklist (in a proper order!) so it can attempt to combine them.
566 LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
567 << " instrs to InstCombine\n");
568 NegatorMaxInstructionsCreated.updateMax(Res->first.size());
569 NegatorNumInstructionsNegatedSuccess += Res->first.size();
570
571 for (Instruction *I : Res->first)
572 IC.addToWorklist(I);
573
574 // And return the new root.
575 return Res->second;
576}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
This defines the Use class.
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static bool shouldExecute(CounterInfo &Counter)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:75
const InstCombineCLOptions & CLOpts
const DataLayout & getDataLayout() const
DominatorTree & getDominatorTree() const
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
void addToWorklist(Instruction *I)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
reference emplace_back(ArgTypes &&... Args)
TargetFolder - Create constants with target dependent folding.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
auto m_Value()
Match an arbitrary value and ignore it.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Xor
Bitwise or logical XOR of integers.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N