2019-07-31 20:06:51 +08:00
|
|
|
//===- DivRemPairs.cpp - Hoist/[dr]ecompose division and remainder --------===//
|
2017-09-09 21:38:18 +08:00
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2017-09-09 21:38:18 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
2019-07-31 20:06:51 +08:00
|
|
|
// This pass hoists and/or decomposes/recomposes integer division and remainder
|
2017-09-09 21:38:18 +08:00
|
|
|
// instructions to enable CFG improvements and better codegen.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "llvm/Transforms/Scalar/DivRemPairs.h"
|
2018-04-25 10:17:56 +08:00
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/MapVector.h"
|
2017-09-09 21:38:18 +08:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
[DivRemPairs] Freeze operands if they can be undef values
Summary:
DivRemPairs is unsound with respect to undef values.
```
// bb1:
// %rem = srem %x, %y
// bb2:
// %div = sdiv %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// %mul = mul %div, %y
// %rem = sub %x, %mul
```
If X can be undef, X should be frozen first.
For example, let's assume that Y = 1 & X = undef:
```
%div = sdiv undef, 1 // %div = undef
%rem = srem undef, 1 // %rem = 0
=>
%div = sdiv undef, 1 // %div = undef
%mul = mul %div, 1 // %mul = undef
%rem = sub %x, %mul // %rem = undef - undef = undef
```
http://volta.cs.utah.edu:8080/z/m7Xrx5
Same for Y. If X = 1 and Y = (undef | 1), %rem in src is either 1 or 0,
but %rem in tgt can be one of many integer values.
This resolves https://bugs.llvm.org/show_bug.cgi?id=42619 .
This miscompilation disappears if undef value is removed, but it may take a while.
DivRemPair happens pretty late during the optimization pipeline, so this optimization seemed as a good candidate to fix without major regression using freeze than other broken optimizations.
Reviewers: spatel, lebedev.ri, george.burgess.iv
Reviewed By: spatel
Subscribers: wuzish, regehr, nlopes, nemanjai, hiraditya, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76483
2020-03-25 02:31:45 +08:00
|
|
|
#include "llvm/Analysis/ValueTracking.h"
|
2017-09-09 21:38:18 +08:00
|
|
|
#include "llvm/IR/Dominators.h"
|
|
|
|
#include "llvm/IR/Function.h"
|
2019-07-31 20:06:51 +08:00
|
|
|
#include "llvm/IR/PatternMatch.h"
|
Sink all InitializePasses.h includes
This file lists every pass in LLVM, and is included by Pass.h, which is
very popular. Every time we add, remove, or rename a pass in LLVM, it
caused lots of recompilation.
I found this fact by looking at this table, which is sorted by the
number of times a file was changed over the last 100,000 git commits
multiplied by the number of object files that depend on it in the
current checkout:
recompiles touches affected_files header
342380 95 3604 llvm/include/llvm/ADT/STLExtras.h
314730 234 1345 llvm/include/llvm/InitializePasses.h
307036 118 2602 llvm/include/llvm/ADT/APInt.h
213049 59 3611 llvm/include/llvm/Support/MathExtras.h
170422 47 3626 llvm/include/llvm/Support/Compiler.h
162225 45 3605 llvm/include/llvm/ADT/Optional.h
158319 63 2513 llvm/include/llvm/ADT/Triple.h
140322 39 3598 llvm/include/llvm/ADT/StringRef.h
137647 59 2333 llvm/include/llvm/Support/Error.h
131619 73 1803 llvm/include/llvm/Support/FileSystem.h
Before this change, touching InitializePasses.h would cause 1345 files
to recompile. After this change, touching it only causes 550 compiles in
an incremental rebuild.
Reviewers: bkramer, asbirlea, bollu, jdoerfert
Differential Revision: https://reviews.llvm.org/D70211
2019-11-14 05:15:01 +08:00
|
|
|
#include "llvm/InitializePasses.h"
|
2017-09-09 21:38:18 +08:00
|
|
|
#include "llvm/Pass.h"
|
2018-08-02 07:14:14 +08:00
|
|
|
#include "llvm/Support/DebugCounter.h"
|
2017-09-09 21:38:18 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
|
|
|
#include "llvm/Transforms/Utils/BypassSlowDivision.h"
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
|
2017-09-09 21:38:18 +08:00
|
|
|
using namespace llvm;
|
2019-07-31 20:06:51 +08:00
|
|
|
using namespace llvm::PatternMatch;
|
2017-09-09 21:38:18 +08:00
|
|
|
|
|
|
|
#define DEBUG_TYPE "div-rem-pairs"
|
|
|
|
STATISTIC(NumPairs, "Number of div/rem pairs");
|
2019-07-31 20:06:51 +08:00
|
|
|
STATISTIC(NumRecomposed, "Number of instructions recomposed");
|
2017-09-09 21:38:18 +08:00
|
|
|
STATISTIC(NumHoisted, "Number of instructions hoisted");
|
|
|
|
STATISTIC(NumDecomposed, "Number of instructions decomposed");
|
2018-08-02 07:14:14 +08:00
|
|
|
DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform",
|
|
|
|
"Controls transformations in div-rem-pairs pass");
|
2017-09-09 21:38:18 +08:00
|
|
|
|
2019-07-31 20:06:51 +08:00
|
|
|
namespace {
|
|
|
|
struct ExpandedMatch {
|
|
|
|
DivRemMapKey Key;
|
|
|
|
Instruction *Value;
|
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
|
|
|
/// See if we can match: (which is the form we expand into)
|
|
|
|
/// X - ((X ?/ Y) * Y)
|
|
|
|
/// which is equivalent to:
|
|
|
|
/// X ?% Y
|
|
|
|
static llvm::Optional<ExpandedMatch> matchExpandedRem(Instruction &I) {
|
|
|
|
Value *Dividend, *XroundedDownToMultipleOfY;
|
|
|
|
if (!match(&I, m_Sub(m_Value(Dividend), m_Value(XroundedDownToMultipleOfY))))
|
|
|
|
return llvm::None;
|
|
|
|
|
|
|
|
Value *Divisor;
|
|
|
|
Instruction *Div;
|
|
|
|
// Look for ((X / Y) * Y)
|
|
|
|
if (!match(
|
|
|
|
XroundedDownToMultipleOfY,
|
|
|
|
m_c_Mul(m_CombineAnd(m_IDiv(m_Specific(Dividend), m_Value(Divisor)),
|
|
|
|
m_Instruction(Div)),
|
|
|
|
m_Deferred(Divisor))))
|
|
|
|
return llvm::None;
|
|
|
|
|
|
|
|
ExpandedMatch M;
|
|
|
|
M.Key.SignedOp = Div->getOpcode() == Instruction::SDiv;
|
|
|
|
M.Key.Dividend = Dividend;
|
|
|
|
M.Key.Divisor = Divisor;
|
|
|
|
M.Value = &I;
|
|
|
|
return M;
|
|
|
|
}
|
|
|
|
|
2020-03-11 01:24:04 +08:00
|
|
|
namespace {
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
/// A thin wrapper to store two values that we matched as div-rem pair.
|
|
|
|
/// We want this extra indirection to avoid dealing with RAUW'ing the map keys.
|
|
|
|
struct DivRemPairWorklistEntry {
|
|
|
|
/// The actual udiv/sdiv instruction. Source of truth.
|
|
|
|
AssertingVH<Instruction> DivInst;
|
|
|
|
|
|
|
|
/// The instruction that we have matched as a remainder instruction.
|
|
|
|
/// Should only be used as Value, don't introspect it.
|
|
|
|
AssertingVH<Instruction> RemInst;
|
|
|
|
|
|
|
|
DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_)
|
|
|
|
: DivInst(DivInst_), RemInst(RemInst_) {
|
|
|
|
assert((DivInst->getOpcode() == Instruction::UDiv ||
|
|
|
|
DivInst->getOpcode() == Instruction::SDiv) &&
|
|
|
|
"Not a division.");
|
|
|
|
assert(DivInst->getType() == RemInst->getType() && "Types should match.");
|
|
|
|
// We can't check anything else about remainder instruction,
|
|
|
|
// it's not strictly required to be a urem/srem.
|
|
|
|
}
|
2017-09-09 21:38:18 +08:00
|
|
|
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
/// The type for this pair, identical for both the div and rem.
|
|
|
|
Type *getType() const { return DivInst->getType(); }
|
|
|
|
|
|
|
|
/// Is this pair signed or unsigned?
|
|
|
|
bool isSigned() const { return DivInst->getOpcode() == Instruction::SDiv; }
|
|
|
|
|
|
|
|
/// In this pair, what are the divident and divisor?
|
|
|
|
Value *getDividend() const { return DivInst->getOperand(0); }
|
|
|
|
Value *getDivisor() const { return DivInst->getOperand(1); }
|
2019-07-31 20:06:51 +08:00
|
|
|
|
|
|
|
bool isRemExpanded() const {
|
|
|
|
switch (RemInst->getOpcode()) {
|
|
|
|
case Instruction::SRem:
|
|
|
|
case Instruction::URem:
|
|
|
|
return false; // single 'rem' instruction - unexpanded form.
|
|
|
|
default:
|
|
|
|
return true; // anything else means we have remainder in expanded form.
|
|
|
|
}
|
|
|
|
}
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
};
|
2020-03-11 01:24:04 +08:00
|
|
|
} // namespace
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
using DivRemWorklistTy = SmallVector<DivRemPairWorklistEntry, 4>;
|
|
|
|
|
|
|
|
/// Find matching pairs of integer div/rem ops (they have the same numerator,
|
|
|
|
/// denominator, and signedness). Place those pairs into a worklist for further
|
|
|
|
/// processing. This indirection is needed because we have to use TrackingVH<>
|
|
|
|
/// because we will be doing RAUW, and if one of the rem instructions we change
|
|
|
|
/// happens to be an input to another div/rem in the maps, we'd have problems.
|
|
|
|
static DivRemWorklistTy getWorklist(Function &F) {
|
2017-09-09 21:38:18 +08:00
|
|
|
// Insert all divide and remainder instructions into maps keyed by their
|
|
|
|
// operands and opcode (signed or unsigned).
|
2018-04-25 10:17:56 +08:00
|
|
|
DenseMap<DivRemMapKey, Instruction *> DivMap;
|
|
|
|
// Use a MapVector for RemMap so that instructions are moved/inserted in a
|
|
|
|
// deterministic order.
|
2019-07-30 15:44:58 +08:00
|
|
|
MapVector<DivRemMapKey, Instruction *> RemMap;
|
2017-09-09 21:38:18 +08:00
|
|
|
for (auto &BB : F) {
|
|
|
|
for (auto &I : BB) {
|
|
|
|
if (I.getOpcode() == Instruction::SDiv)
|
|
|
|
DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
|
|
|
|
else if (I.getOpcode() == Instruction::UDiv)
|
|
|
|
DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
|
|
|
|
else if (I.getOpcode() == Instruction::SRem)
|
2019-07-30 15:44:58 +08:00
|
|
|
RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
|
2017-09-09 21:38:18 +08:00
|
|
|
else if (I.getOpcode() == Instruction::URem)
|
2019-07-30 15:44:58 +08:00
|
|
|
RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
|
2019-07-31 20:06:51 +08:00
|
|
|
else if (auto Match = matchExpandedRem(I))
|
|
|
|
RemMap[Match->Key] = Match->Value;
|
2017-09-09 21:38:18 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
// We'll accumulate the matching pairs of div-rem instructions here.
|
|
|
|
DivRemWorklistTy Worklist;
|
|
|
|
|
2017-09-09 21:38:18 +08:00
|
|
|
// We can iterate over either map because we are only looking for matched
|
|
|
|
// pairs. Choose remainders for efficiency because they are usually even more
|
|
|
|
// rare than division.
|
|
|
|
for (auto &RemPair : RemMap) {
|
|
|
|
// Find the matching division instruction from the division map.
|
2018-04-25 10:17:56 +08:00
|
|
|
Instruction *DivInst = DivMap[RemPair.first];
|
2017-09-09 21:38:18 +08:00
|
|
|
if (!DivInst)
|
|
|
|
continue;
|
|
|
|
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
// We have a matching pair of div/rem instructions.
|
2017-09-09 21:38:18 +08:00
|
|
|
NumPairs++;
|
2019-07-30 15:44:58 +08:00
|
|
|
Instruction *RemInst = RemPair.second;
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
|
|
|
|
// Place it in the worklist.
|
|
|
|
Worklist.emplace_back(DivInst, RemInst);
|
|
|
|
}
|
|
|
|
|
|
|
|
return Worklist;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Find matching pairs of integer div/rem ops (they have the same numerator,
|
|
|
|
/// denominator, and signedness). If they exist in different basic blocks, bring
|
|
|
|
/// them together by hoisting or replace the common division operation that is
|
|
|
|
/// implicit in the remainder:
|
|
|
|
/// X % Y <--> X - ((X / Y) * Y).
|
|
|
|
///
|
|
|
|
/// We can largely ignore the normal safety and cost constraints on speculation
|
|
|
|
/// of these ops when we find a matching pair. This is because we are already
|
|
|
|
/// guaranteed that any exceptions and most cost are already incurred by the
|
|
|
|
/// first member of the pair.
|
|
|
|
///
|
|
|
|
/// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or
|
|
|
|
/// SimplifyCFG, but it's split off on its own because it's different enough
|
|
|
|
/// that it doesn't quite match the stated objectives of those passes.
|
|
|
|
static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI,
|
|
|
|
const DominatorTree &DT) {
|
|
|
|
bool Changed = false;
|
|
|
|
|
|
|
|
// Get the matching pairs of div-rem instructions. We want this extra
|
|
|
|
// indirection to avoid dealing with having to RAUW the keys of the maps.
|
|
|
|
DivRemWorklistTy Worklist = getWorklist(F);
|
|
|
|
|
|
|
|
// Process each entry in the worklist.
|
|
|
|
for (DivRemPairWorklistEntry &E : Worklist) {
|
2019-07-31 20:06:51 +08:00
|
|
|
if (!DebugCounter::shouldExecute(DRPCounter))
|
|
|
|
continue;
|
|
|
|
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
bool HasDivRemOp = TTI.hasDivRemOp(E.getType(), E.isSigned());
|
|
|
|
|
|
|
|
auto &DivInst = E.DivInst;
|
|
|
|
auto &RemInst = E.RemInst;
|
2017-09-09 21:38:18 +08:00
|
|
|
|
2019-07-31 20:06:51 +08:00
|
|
|
const bool RemOriginallyWasInExpandedForm = E.isRemExpanded();
|
2019-07-31 20:26:37 +08:00
|
|
|
(void)RemOriginallyWasInExpandedForm; // suppress unused variable warning
|
2019-07-31 20:06:51 +08:00
|
|
|
|
|
|
|
if (HasDivRemOp && E.isRemExpanded()) {
|
|
|
|
// The target supports div+rem but the rem is expanded.
|
|
|
|
// We should recompose it first.
|
|
|
|
Value *X = E.getDividend();
|
|
|
|
Value *Y = E.getDivisor();
|
|
|
|
Instruction *RealRem = E.isSigned() ? BinaryOperator::CreateSRem(X, Y)
|
|
|
|
: BinaryOperator::CreateURem(X, Y);
|
|
|
|
// Note that we place it right next to the original expanded instruction,
|
|
|
|
// and letting further handling to move it if needed.
|
|
|
|
RealRem->setName(RemInst->getName() + ".recomposed");
|
|
|
|
RealRem->insertAfter(RemInst);
|
|
|
|
Instruction *OrigRemInst = RemInst;
|
|
|
|
// Update AssertingVH<> with new instruction so it doesn't assert.
|
|
|
|
RemInst = RealRem;
|
|
|
|
// And replace the original instruction with the new one.
|
|
|
|
OrigRemInst->replaceAllUsesWith(RealRem);
|
|
|
|
OrigRemInst->eraseFromParent();
|
|
|
|
NumRecomposed++;
|
|
|
|
// Note that we have left ((X / Y) * Y) around.
|
|
|
|
// If it had other uses we could rewrite it as X - X % Y
|
2020-06-05 04:24:31 +08:00
|
|
|
Changed = true;
|
2019-07-31 20:06:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
assert((!E.isRemExpanded() || !HasDivRemOp) &&
|
|
|
|
"*If* the target supports div-rem, then by now the RemInst *is* "
|
|
|
|
"Instruction::[US]Rem.");
|
|
|
|
|
2017-09-09 21:38:18 +08:00
|
|
|
// If the target supports div+rem and the instructions are in the same block
|
|
|
|
// already, there's nothing to do. The backend should handle this. If the
|
|
|
|
// target does not support div+rem, then we will decompose the rem.
|
|
|
|
if (HasDivRemOp && RemInst->getParent() == DivInst->getParent())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
bool DivDominates = DT.dominates(DivInst, RemInst);
|
2019-07-31 20:06:51 +08:00
|
|
|
if (!DivDominates && !DT.dominates(RemInst, DivInst)) {
|
|
|
|
// We have matching div-rem pair, but they are in two different blocks,
|
|
|
|
// neither of which dominates one another.
|
|
|
|
// FIXME: We could hoist both ops to the common predecessor block?
|
2017-09-09 21:38:18 +08:00
|
|
|
continue;
|
2019-07-31 20:06:51 +08:00
|
|
|
}
|
2017-09-09 21:38:18 +08:00
|
|
|
|
2019-07-31 20:06:51 +08:00
|
|
|
// The target does not have a single div/rem operation,
|
|
|
|
// and the rem is already in expanded form. Nothing to do.
|
|
|
|
if (!HasDivRemOp && E.isRemExpanded())
|
2018-08-02 07:14:14 +08:00
|
|
|
continue;
|
|
|
|
|
2017-09-09 21:38:18 +08:00
|
|
|
if (HasDivRemOp) {
|
|
|
|
// The target has a single div/rem operation. Hoist the lower instruction
|
|
|
|
// to make the matched pair visible to the backend.
|
|
|
|
if (DivDominates)
|
|
|
|
RemInst->moveAfter(DivInst);
|
|
|
|
else
|
|
|
|
DivInst->moveAfter(RemInst);
|
|
|
|
NumHoisted++;
|
|
|
|
} else {
|
2019-07-31 20:06:51 +08:00
|
|
|
// The target does not have a single div/rem operation,
|
|
|
|
// and the rem is *not* in a already-expanded form.
|
|
|
|
// Decompose the remainder calculation as:
|
2017-09-09 21:38:18 +08:00
|
|
|
// X % Y --> X - ((X / Y) * Y).
|
2019-07-31 20:06:51 +08:00
|
|
|
|
|
|
|
assert(!RemOriginallyWasInExpandedForm &&
|
|
|
|
"We should not be expanding if the rem was in expanded form to "
|
|
|
|
"begin with.");
|
|
|
|
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
Value *X = E.getDividend();
|
|
|
|
Value *Y = E.getDivisor();
|
2017-09-09 21:38:18 +08:00
|
|
|
Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y);
|
|
|
|
Instruction *Sub = BinaryOperator::CreateSub(X, Mul);
|
|
|
|
|
|
|
|
// If the remainder dominates, then hoist the division up to that block:
|
|
|
|
//
|
|
|
|
// bb1:
|
|
|
|
// %rem = srem %x, %y
|
|
|
|
// bb2:
|
|
|
|
// %div = sdiv %x, %y
|
|
|
|
// -->
|
|
|
|
// bb1:
|
|
|
|
// %div = sdiv %x, %y
|
|
|
|
// %mul = mul %div, %y
|
|
|
|
// %rem = sub %x, %mul
|
|
|
|
//
|
|
|
|
// If the division dominates, it's already in the right place. The mul+sub
|
|
|
|
// will be in a different block because we don't assume that they are
|
|
|
|
// cheap to speculatively execute:
|
|
|
|
//
|
|
|
|
// bb1:
|
|
|
|
// %div = sdiv %x, %y
|
|
|
|
// bb2:
|
|
|
|
// %rem = srem %x, %y
|
|
|
|
// -->
|
|
|
|
// bb1:
|
|
|
|
// %div = sdiv %x, %y
|
|
|
|
// bb2:
|
|
|
|
// %mul = mul %div, %y
|
|
|
|
// %rem = sub %x, %mul
|
|
|
|
//
|
|
|
|
// If the div and rem are in the same block, we do the same transform,
|
|
|
|
// but any code movement would be within the same block.
|
|
|
|
|
|
|
|
if (!DivDominates)
|
|
|
|
DivInst->moveBefore(RemInst);
|
|
|
|
Mul->insertAfter(RemInst);
|
|
|
|
Sub->insertAfter(Mul);
|
|
|
|
|
[DivRemPairs] Freeze operands if they can be undef values
Summary:
DivRemPairs is unsound with respect to undef values.
```
// bb1:
// %rem = srem %x, %y
// bb2:
// %div = sdiv %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// %mul = mul %div, %y
// %rem = sub %x, %mul
```
If X can be undef, X should be frozen first.
For example, let's assume that Y = 1 & X = undef:
```
%div = sdiv undef, 1 // %div = undef
%rem = srem undef, 1 // %rem = 0
=>
%div = sdiv undef, 1 // %div = undef
%mul = mul %div, 1 // %mul = undef
%rem = sub %x, %mul // %rem = undef - undef = undef
```
http://volta.cs.utah.edu:8080/z/m7Xrx5
Same for Y. If X = 1 and Y = (undef | 1), %rem in src is either 1 or 0,
but %rem in tgt can be one of many integer values.
This resolves https://bugs.llvm.org/show_bug.cgi?id=42619 .
This miscompilation disappears if undef value is removed, but it may take a while.
DivRemPair happens pretty late during the optimization pipeline, so this optimization seemed as a good candidate to fix without major regression using freeze than other broken optimizations.
Reviewers: spatel, lebedev.ri, george.burgess.iv
Reviewed By: spatel
Subscribers: wuzish, regehr, nlopes, nemanjai, hiraditya, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76483
2020-03-25 02:31:45 +08:00
|
|
|
// If X can be undef, X should be frozen first.
|
|
|
|
// For example, let's assume that Y = 1 & X = undef:
|
|
|
|
// %div = sdiv undef, 1 // %div = undef
|
|
|
|
// %rem = srem undef, 1 // %rem = 0
|
|
|
|
// =>
|
|
|
|
// %div = sdiv undef, 1 // %div = undef
|
|
|
|
// %mul = mul %div, 1 // %mul = undef
|
|
|
|
// %rem = sub %x, %mul // %rem = undef - undef = undef
|
|
|
|
// If X is not frozen, %rem becomes undef after transformation.
|
|
|
|
// TODO: We need a undef-specific checking function in ValueTracking
|
|
|
|
if (!isGuaranteedNotToBeUndefOrPoison(X, DivInst, &DT)) {
|
|
|
|
auto *FrX = new FreezeInst(X, X->getName() + ".frozen", DivInst);
|
|
|
|
DivInst->setOperand(0, FrX);
|
|
|
|
Sub->setOperand(0, FrX);
|
|
|
|
}
|
|
|
|
// Same for Y. If X = 1 and Y = (undef | 1), %rem in src is either 1 or 0,
|
|
|
|
// but %rem in tgt can be one of many integer values.
|
|
|
|
if (!isGuaranteedNotToBeUndefOrPoison(Y, DivInst, &DT)) {
|
|
|
|
auto *FrY = new FreezeInst(Y, Y->getName() + ".frozen", DivInst);
|
|
|
|
DivInst->setOperand(1, FrY);
|
|
|
|
Mul->setOperand(1, FrY);
|
|
|
|
}
|
|
|
|
|
2017-09-09 21:38:18 +08:00
|
|
|
// Now kill the explicit remainder. We have replaced it with:
|
|
|
|
// (sub X, (mul (div X, Y), Y)
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
Sub->setName(RemInst->getName() + ".decomposed");
|
|
|
|
Instruction *OrigRemInst = RemInst;
|
|
|
|
// Update AssertingVH<> with new instruction so it doesn't assert.
|
|
|
|
RemInst = Sub;
|
|
|
|
// And replace the original instruction with the new one.
|
|
|
|
OrigRemInst->replaceAllUsesWith(Sub);
|
|
|
|
OrigRemInst->eraseFromParent();
|
2017-09-09 21:38:18 +08:00
|
|
|
NumDecomposed++;
|
|
|
|
}
|
|
|
|
Changed = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pass manager boilerplate below here.
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
struct DivRemPairsLegacyPass : public FunctionPass {
|
|
|
|
static char ID;
|
|
|
|
DivRemPairsLegacyPass() : FunctionPass(ID) {
|
|
|
|
initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
AU.addRequired<DominatorTreeWrapperPass>();
|
|
|
|
AU.addRequired<TargetTransformInfoWrapperPass>();
|
|
|
|
AU.setPreservesCFG();
|
|
|
|
AU.addPreserved<DominatorTreeWrapperPass>();
|
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
|
|
|
FunctionPass::getAnalysisUsage(AU);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnFunction(Function &F) override {
|
|
|
|
if (skipFunction(F))
|
|
|
|
return false;
|
|
|
|
auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
|
|
|
|
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
|
|
|
|
return optimizeDivRem(F, TTI, DT);
|
|
|
|
}
|
|
|
|
};
|
[DivRemPairs] Avoid RAUW pitfalls (PR42823)
Summary:
`DivRemPairs` internally creates two maps:
* {sign, divident, divisor} -> div instruction
* {sign, divident, divisor} -> rem instruction
Then it iterates over rem map, and looks if there is an entry
in div map with the same key. Then depending on some internal logic
it may RAUW rem instruction with something else.
But if that rem instruction is an input to other div/rem,
then it was used as a key in these maps, so the old value (used in key)
is now dandling, because RAUW didn't update those maps.
And we can't even RAUW map keys in general, there's `ValueMap`,
but we don't have a single `Value` as key...
The bug was discovered via D65298, and the test there exists.
Now, i'm not sure how to expose this issue in trunk.
The bug is clearly there if i change the map keys to be `AssertingVH`/`PoisoningVH`,
but i guess this didn't miscompiled anything thus far?
I really don't think this is benin without that patch.
The fix is actually rather straight-forward - instead of trying to somehow
shoe-horn `ValueMap` here (doesn't fit, key isn't just `Value`), or writing a new
`ValueMap` with key being a struct of `Value`s, we can just have an intermediate
data structure - a vector, each entry containing matching `Div, Rem` pair,
and pre-filling it before doing any modifications.
This way we won't need to query map after doing RAUW, so no bug is possible.
Reviewers: spatel, bogner, RKSimon, craig.topper
Reviewed By: spatel
Subscribers: hiraditya, hans, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D65451
llvm-svn: 367417
2019-07-31 20:06:38 +08:00
|
|
|
} // namespace
|
2017-09-09 21:38:18 +08:00
|
|
|
|
|
|
|
char DivRemPairsLegacyPass::ID = 0;
|
|
|
|
INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs",
|
|
|
|
"Hoist/decompose integer division and remainder", false,
|
|
|
|
false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
|
|
|
|
INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs",
|
|
|
|
"Hoist/decompose integer division and remainder", false,
|
|
|
|
false)
|
|
|
|
FunctionPass *llvm::createDivRemPairsPass() {
|
|
|
|
return new DivRemPairsLegacyPass();
|
|
|
|
}
|
|
|
|
|
|
|
|
PreservedAnalyses DivRemPairsPass::run(Function &F,
|
|
|
|
FunctionAnalysisManager &FAM) {
|
|
|
|
TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
|
|
|
|
DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
|
|
|
|
if (!optimizeDivRem(F, TTI, DT))
|
|
|
|
return PreservedAnalyses::all();
|
|
|
|
// TODO: This pass just hoists/replaces math ops - all analyses are preserved?
|
|
|
|
PreservedAnalyses PA;
|
|
|
|
PA.preserveSet<CFGAnalyses>();
|
|
|
|
PA.preserve<GlobalsAA>();
|
|
|
|
return PA;
|
|
|
|
}
|