2015-03-27 11:36:57 +01:00
|
|
|
//===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
|
|
|
|
//
|
2019-01-19 09:50:56 +01: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
|
2015-03-27 11:36:57 +01:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file implements the Float2Int pass, which aims to demote floating
|
|
|
|
// point operations to work on integers, where that is losslessly possible.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#define DEBUG_TYPE "float2int"
|
2016-06-25 01:32:02 +02:00
|
|
|
|
|
|
|
#include "llvm/Transforms/Scalar/Float2Int.h"
|
2015-03-27 11:36:57 +01:00
|
|
|
#include "llvm/ADT/APInt.h"
|
|
|
|
#include "llvm/ADT/APSInt.h"
|
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2015-07-23 11:34:01 +02:00
|
|
|
#include "llvm/Analysis/AliasAnalysis.h"
|
[PM/AA] Rebuild LLVM's alias analysis infrastructure in a way compatible
with the new pass manager, and no longer relying on analysis groups.
This builds essentially a ground-up new AA infrastructure stack for
LLVM. The core ideas are the same that are used throughout the new pass
manager: type erased polymorphism and direct composition. The design is
as follows:
- FunctionAAResults is a type-erasing alias analysis results aggregation
interface to walk a single query across a range of results from
different alias analyses. Currently this is function-specific as we
always assume that aliasing queries are *within* a function.
- AAResultBase is a CRTP utility providing stub implementations of
various parts of the alias analysis result concept, notably in several
cases in terms of other more general parts of the interface. This can
be used to implement only a narrow part of the interface rather than
the entire interface. This isn't really ideal, this logic should be
hoisted into FunctionAAResults as currently it will cause
a significant amount of redundant work, but it faithfully models the
behavior of the prior infrastructure.
- All the alias analysis passes are ported to be wrapper passes for the
legacy PM and new-style analysis passes for the new PM with a shared
result object. In some cases (most notably CFL), this is an extremely
naive approach that we should revisit when we can specialize for the
new pass manager.
- BasicAA has been restructured to reflect that it is much more
fundamentally a function analysis because it uses dominator trees and
loop info that need to be constructed for each function.
All of the references to getting alias analysis results have been
updated to use the new aggregation interface. All the preservation and
other pass management code has been updated accordingly.
The way the FunctionAAResultsWrapperPass works is to detect the
available alias analyses when run, and add them to the results object.
This means that we should be able to continue to respect when various
passes are added to the pipeline, for example adding CFL or adding TBAA
passes should just cause their results to be available and to get folded
into this. The exception to this rule is BasicAA which really needs to
be a function pass due to using dominator trees and loop info. As
a consequence, the FunctionAAResultsWrapperPass directly depends on
BasicAA and always includes it in the aggregation.
This has significant implications for preserving analyses. Generally,
most passes shouldn't bother preserving FunctionAAResultsWrapperPass
because rebuilding the results just updates the set of known AA passes.
The exception to this rule are LoopPass instances which need to preserve
all the function analyses that the loop pass manager will end up
needing. This means preserving both BasicAAWrapperPass and the
aggregating FunctionAAResultsWrapperPass.
Now, when preserving an alias analysis, you do so by directly preserving
that analysis. This is only necessary for non-immutable-pass-provided
alias analyses though, and there are only three of interest: BasicAA,
GlobalsAA (formerly GlobalsModRef), and SCEVAA. Usually BasicAA is
preserved when needed because it (like DominatorTree and LoopInfo) is
marked as a CFG-only pass. I've expanded GlobalsAA into the preserved
set everywhere we previously were preserving all of AliasAnalysis, and
I've added SCEVAA in the intersection of that with where we preserve
SCEV itself.
One significant challenge to all of this is that the CGSCC passes were
actually using the alias analysis implementations by taking advantage of
a pretty amazing set of loop holes in the old pass manager's analysis
management code which allowed analysis groups to slide through in many
cases. Moving away from analysis groups makes this problem much more
obvious. To fix it, I've leveraged the flexibility the design of the new
PM components provides to just directly construct the relevant alias
analyses for the relevant functions in the IPO passes that need them.
This is a bit hacky, but should go away with the new pass manager, and
is already in many ways cleaner than the prior state.
Another significant challenge is that various facilities of the old
alias analysis infrastructure just don't fit any more. The most
significant of these is the alias analysis 'counter' pass. That pass
relied on the ability to snoop on AA queries at different points in the
analysis group chain. Instead, I'm planning to build printing
functionality directly into the aggregation layer. I've not included
that in this patch merely to keep it smaller.
Note that all of this needs a nearly complete rewrite of the AA
documentation. I'm planning to do that, but I'd like to make sure the
new design settles, and to flesh out a bit more of what it looks like in
the new pass manager first.
Differential Revision: http://reviews.llvm.org/D12080
llvm-svn: 247167
2015-09-09 19:55:00 +02:00
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
2015-03-27 11:36:57 +01:00
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
#include "llvm/IR/IRBuilder.h"
|
|
|
|
#include "llvm/IR/InstIterator.h"
|
|
|
|
#include "llvm/IR/Instructions.h"
|
|
|
|
#include "llvm/IR/Module.h"
|
|
|
|
#include "llvm/Pass.h"
|
|
|
|
#include "llvm/Support/Debug.h"
|
|
|
|
#include "llvm/Support/raw_ostream.h"
|
|
|
|
#include "llvm/Transforms/Scalar.h"
|
|
|
|
#include <deque>
|
|
|
|
#include <functional> // For std::function
|
|
|
|
using namespace llvm;
|
|
|
|
|
|
|
|
// The algorithm is simple. Start at instructions that convert from the
|
|
|
|
// float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
|
|
|
|
// graph, using an equivalence datastructure to unify graphs that interfere.
|
|
|
|
//
|
|
|
|
// Mappable instructions are those with an integer corrollary that, given
|
|
|
|
// integer domain inputs, produce an integer output; fadd, for example.
|
|
|
|
//
|
|
|
|
// If a non-mappable instruction is seen, this entire def-use graph is marked
|
2015-09-22 13:14:12 +02:00
|
|
|
// as non-transformable. If we see an instruction that converts from the
|
2015-03-27 11:36:57 +01:00
|
|
|
// integer domain to FP domain (uitofp,sitofp), we terminate our walk.
|
|
|
|
|
|
|
|
/// The largest integer type worth dealing with.
|
|
|
|
static cl::opt<unsigned>
|
|
|
|
MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
|
|
|
|
cl::desc("Max integer bitwidth to consider in float2int"
|
|
|
|
"(default=64)"));
|
|
|
|
|
|
|
|
namespace {
|
2016-06-25 01:32:02 +02:00
|
|
|
struct Float2IntLegacyPass : public FunctionPass {
|
2015-03-27 11:36:57 +01:00
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2016-06-25 01:32:02 +02:00
|
|
|
Float2IntLegacyPass() : FunctionPass(ID) {
|
|
|
|
initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnFunction(Function &F) override {
|
|
|
|
if (skipFunction(F))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return Impl.runImpl(F);
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
AU.setPreservesCFG();
|
[PM/AA] Rebuild LLVM's alias analysis infrastructure in a way compatible
with the new pass manager, and no longer relying on analysis groups.
This builds essentially a ground-up new AA infrastructure stack for
LLVM. The core ideas are the same that are used throughout the new pass
manager: type erased polymorphism and direct composition. The design is
as follows:
- FunctionAAResults is a type-erasing alias analysis results aggregation
interface to walk a single query across a range of results from
different alias analyses. Currently this is function-specific as we
always assume that aliasing queries are *within* a function.
- AAResultBase is a CRTP utility providing stub implementations of
various parts of the alias analysis result concept, notably in several
cases in terms of other more general parts of the interface. This can
be used to implement only a narrow part of the interface rather than
the entire interface. This isn't really ideal, this logic should be
hoisted into FunctionAAResults as currently it will cause
a significant amount of redundant work, but it faithfully models the
behavior of the prior infrastructure.
- All the alias analysis passes are ported to be wrapper passes for the
legacy PM and new-style analysis passes for the new PM with a shared
result object. In some cases (most notably CFL), this is an extremely
naive approach that we should revisit when we can specialize for the
new pass manager.
- BasicAA has been restructured to reflect that it is much more
fundamentally a function analysis because it uses dominator trees and
loop info that need to be constructed for each function.
All of the references to getting alias analysis results have been
updated to use the new aggregation interface. All the preservation and
other pass management code has been updated accordingly.
The way the FunctionAAResultsWrapperPass works is to detect the
available alias analyses when run, and add them to the results object.
This means that we should be able to continue to respect when various
passes are added to the pipeline, for example adding CFL or adding TBAA
passes should just cause their results to be available and to get folded
into this. The exception to this rule is BasicAA which really needs to
be a function pass due to using dominator trees and loop info. As
a consequence, the FunctionAAResultsWrapperPass directly depends on
BasicAA and always includes it in the aggregation.
This has significant implications for preserving analyses. Generally,
most passes shouldn't bother preserving FunctionAAResultsWrapperPass
because rebuilding the results just updates the set of known AA passes.
The exception to this rule are LoopPass instances which need to preserve
all the function analyses that the loop pass manager will end up
needing. This means preserving both BasicAAWrapperPass and the
aggregating FunctionAAResultsWrapperPass.
Now, when preserving an alias analysis, you do so by directly preserving
that analysis. This is only necessary for non-immutable-pass-provided
alias analyses though, and there are only three of interest: BasicAA,
GlobalsAA (formerly GlobalsModRef), and SCEVAA. Usually BasicAA is
preserved when needed because it (like DominatorTree and LoopInfo) is
marked as a CFG-only pass. I've expanded GlobalsAA into the preserved
set everywhere we previously were preserving all of AliasAnalysis, and
I've added SCEVAA in the intersection of that with where we preserve
SCEV itself.
One significant challenge to all of this is that the CGSCC passes were
actually using the alias analysis implementations by taking advantage of
a pretty amazing set of loop holes in the old pass manager's analysis
management code which allowed analysis groups to slide through in many
cases. Moving away from analysis groups makes this problem much more
obvious. To fix it, I've leveraged the flexibility the design of the new
PM components provides to just directly construct the relevant alias
analyses for the relevant functions in the IPO passes that need them.
This is a bit hacky, but should go away with the new pass manager, and
is already in many ways cleaner than the prior state.
Another significant challenge is that various facilities of the old
alias analysis infrastructure just don't fit any more. The most
significant of these is the alias analysis 'counter' pass. That pass
relied on the ability to snoop on AA queries at different points in the
analysis group chain. Instead, I'm planning to build printing
functionality directly into the aggregation layer. I've not included
that in this patch merely to keep it smaller.
Note that all of this needs a nearly complete rewrite of the AA
documentation. I'm planning to do that, but I'd like to make sure the
new design settles, and to flesh out a bit more of what it looks like in
the new pass manager first.
Differential Revision: http://reviews.llvm.org/D12080
llvm-svn: 247167
2015-09-09 19:55:00 +02:00
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
|
|
|
|
2016-06-25 01:32:02 +02:00
|
|
|
private:
|
|
|
|
Float2IntPass Impl;
|
2015-03-27 11:36:57 +01:00
|
|
|
};
|
2015-06-23 11:49:53 +02:00
|
|
|
}
|
2015-03-27 11:36:57 +01:00
|
|
|
|
2016-06-25 01:32:02 +02:00
|
|
|
char Float2IntLegacyPass::ID = 0;
|
|
|
|
INITIALIZE_PASS(Float2IntLegacyPass, "float2int", "Float to int", false, false)
|
2015-03-27 11:36:57 +01:00
|
|
|
|
|
|
|
// Given a FCmp predicate, return a matching ICmp predicate if one
|
|
|
|
// exists, otherwise return BAD_ICMP_PREDICATE.
|
|
|
|
static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
|
|
|
|
switch (P) {
|
|
|
|
case CmpInst::FCMP_OEQ:
|
|
|
|
case CmpInst::FCMP_UEQ:
|
|
|
|
return CmpInst::ICMP_EQ;
|
|
|
|
case CmpInst::FCMP_OGT:
|
|
|
|
case CmpInst::FCMP_UGT:
|
|
|
|
return CmpInst::ICMP_SGT;
|
|
|
|
case CmpInst::FCMP_OGE:
|
|
|
|
case CmpInst::FCMP_UGE:
|
|
|
|
return CmpInst::ICMP_SGE;
|
|
|
|
case CmpInst::FCMP_OLT:
|
|
|
|
case CmpInst::FCMP_ULT:
|
|
|
|
return CmpInst::ICMP_SLT;
|
|
|
|
case CmpInst::FCMP_OLE:
|
|
|
|
case CmpInst::FCMP_ULE:
|
|
|
|
return CmpInst::ICMP_SLE;
|
|
|
|
case CmpInst::FCMP_ONE:
|
|
|
|
case CmpInst::FCMP_UNE:
|
|
|
|
return CmpInst::ICMP_NE;
|
|
|
|
default:
|
|
|
|
return CmpInst::BAD_ICMP_PREDICATE;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Given a floating point binary operator, return the matching
|
|
|
|
// integer version.
|
|
|
|
static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
|
|
|
|
switch (Opcode) {
|
|
|
|
default: llvm_unreachable("Unhandled opcode!");
|
|
|
|
case Instruction::FAdd: return Instruction::Add;
|
|
|
|
case Instruction::FSub: return Instruction::Sub;
|
|
|
|
case Instruction::FMul: return Instruction::Mul;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find the roots - instructions that convert from the FP domain to
|
|
|
|
// integer domain.
|
2016-06-25 01:32:02 +02:00
|
|
|
void Float2IntPass::findRoots(Function &F, SmallPtrSet<Instruction*,8> &Roots) {
|
2015-08-06 21:10:45 +02:00
|
|
|
for (auto &I : instructions(F)) {
|
2015-12-09 22:08:18 +01:00
|
|
|
if (isa<VectorType>(I.getType()))
|
|
|
|
continue;
|
2015-03-27 11:36:57 +01:00
|
|
|
switch (I.getOpcode()) {
|
|
|
|
default: break;
|
|
|
|
case Instruction::FPToUI:
|
|
|
|
case Instruction::FPToSI:
|
|
|
|
Roots.insert(&I);
|
|
|
|
break;
|
|
|
|
case Instruction::FCmp:
|
2015-09-22 13:19:03 +02:00
|
|
|
if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
|
2015-03-27 11:36:57 +01:00
|
|
|
CmpInst::BAD_ICMP_PREDICATE)
|
|
|
|
Roots.insert(&I);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper - mark I as having been traversed, having range R.
|
2017-05-04 23:29:45 +02:00
|
|
|
void Float2IntPass::seen(Instruction *I, ConstantRange R) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
|
2017-05-05 19:09:29 +02:00
|
|
|
auto IT = SeenInsts.find(I);
|
|
|
|
if (IT != SeenInsts.end())
|
|
|
|
IT->second = std::move(R);
|
2015-03-27 11:36:57 +01:00
|
|
|
else
|
2017-05-05 19:09:29 +02:00
|
|
|
SeenInsts.insert(std::make_pair(I, std::move(R)));
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Helper - get a range representing a poison value.
|
2016-06-25 01:32:02 +02:00
|
|
|
ConstantRange Float2IntPass::badRange() {
|
2019-03-24 10:34:40 +01:00
|
|
|
return ConstantRange::getFull(MaxIntegerBW + 1);
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
2016-06-25 01:32:02 +02:00
|
|
|
ConstantRange Float2IntPass::unknownRange() {
|
2019-03-24 10:34:40 +01:00
|
|
|
return ConstantRange::getEmpty(MaxIntegerBW + 1);
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
2016-06-25 01:32:02 +02:00
|
|
|
ConstantRange Float2IntPass::validateRange(ConstantRange R) {
|
2015-03-27 11:36:57 +01:00
|
|
|
if (R.getBitWidth() > MaxIntegerBW + 1)
|
|
|
|
return badRange();
|
|
|
|
return R;
|
|
|
|
}
|
|
|
|
|
|
|
|
// The most obvious way to structure the search is a depth-first, eager
|
|
|
|
// search from each root. However, that require direct recursion and so
|
|
|
|
// can only handle small instruction sequences. Instead, we split the search
|
|
|
|
// up into two phases:
|
|
|
|
// - walkBackwards: A breadth-first walk of the use-def graph starting from
|
|
|
|
// the roots. Populate "SeenInsts" with interesting
|
|
|
|
// instructions and poison values if they're obvious and
|
|
|
|
// cheap to compute. Calculate the equivalance set structure
|
|
|
|
// while we're here too.
|
|
|
|
// - walkForwards: Iterate over SeenInsts in reverse order, so we visit
|
|
|
|
// defs before their uses. Calculate the real range info.
|
|
|
|
|
2015-09-22 13:14:12 +02:00
|
|
|
// Breadth-first walk of the use-def graph; determine the set of nodes
|
2015-03-27 11:36:57 +01:00
|
|
|
// we care about and eagerly determine if some of them are poisonous.
|
2016-06-25 01:32:02 +02:00
|
|
|
void Float2IntPass::walkBackwards(const SmallPtrSetImpl<Instruction*> &Roots) {
|
2015-03-27 11:36:57 +01:00
|
|
|
std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
|
|
|
|
while (!Worklist.empty()) {
|
|
|
|
Instruction *I = Worklist.back();
|
|
|
|
Worklist.pop_back();
|
|
|
|
|
|
|
|
if (SeenInsts.find(I) != SeenInsts.end())
|
|
|
|
// Seen already.
|
|
|
|
continue;
|
|
|
|
|
|
|
|
switch (I->getOpcode()) {
|
|
|
|
// FIXME: Handle select and phi nodes.
|
|
|
|
default:
|
|
|
|
// Path terminated uncleanly.
|
|
|
|
seen(I, badRange());
|
|
|
|
break;
|
|
|
|
|
2016-12-01 21:08:47 +01:00
|
|
|
case Instruction::UIToFP:
|
2015-03-27 11:36:57 +01:00
|
|
|
case Instruction::SIToFP: {
|
2016-12-01 21:08:47 +01:00
|
|
|
// Path terminated cleanly - use the type of the integer input to seed
|
|
|
|
// the analysis.
|
2015-03-27 11:36:57 +01:00
|
|
|
unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
|
2019-03-24 10:34:40 +01:00
|
|
|
auto Input = ConstantRange::getFull(BW);
|
2016-12-01 21:08:47 +01:00
|
|
|
auto CastOp = (Instruction::CastOps)I->getOpcode();
|
|
|
|
seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
|
2015-03-27 11:36:57 +01:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
case Instruction::FAdd:
|
|
|
|
case Instruction::FSub:
|
|
|
|
case Instruction::FMul:
|
|
|
|
case Instruction::FPToUI:
|
|
|
|
case Instruction::FPToSI:
|
|
|
|
case Instruction::FCmp:
|
|
|
|
seen(I, unknownRange());
|
|
|
|
break;
|
|
|
|
}
|
2015-09-22 13:14:39 +02:00
|
|
|
|
2015-03-27 11:36:57 +01:00
|
|
|
for (Value *O : I->operands()) {
|
|
|
|
if (Instruction *OI = dyn_cast<Instruction>(O)) {
|
|
|
|
// Unify def-use chains if they interfere.
|
|
|
|
ECs.unionSets(I, OI);
|
2015-09-22 13:15:07 +02:00
|
|
|
if (SeenInsts.find(I)->second != badRange())
|
2015-03-27 11:36:57 +01:00
|
|
|
Worklist.push_back(OI);
|
2015-09-22 13:19:03 +02:00
|
|
|
} else if (!isa<ConstantFP>(O)) {
|
2015-03-27 11:36:57 +01:00
|
|
|
// Not an instruction or ConstantFP? we can't do anything.
|
|
|
|
seen(I, badRange());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Walk forwards down the list of seen instructions, so we visit defs before
|
|
|
|
// uses.
|
2016-06-25 01:32:02 +02:00
|
|
|
void Float2IntPass::walkForwards() {
|
2016-06-24 06:05:21 +02:00
|
|
|
for (auto &It : reverse(SeenInsts)) {
|
2015-07-24 23:13:43 +02:00
|
|
|
if (It.second != unknownRange())
|
2015-03-27 11:36:57 +01:00
|
|
|
continue;
|
|
|
|
|
2015-07-24 23:13:43 +02:00
|
|
|
Instruction *I = It.first;
|
2015-03-27 11:36:57 +01:00
|
|
|
std::function<ConstantRange(ArrayRef<ConstantRange>)> Op;
|
|
|
|
switch (I->getOpcode()) {
|
|
|
|
// FIXME: Handle select and phi nodes.
|
|
|
|
default:
|
|
|
|
case Instruction::UIToFP:
|
|
|
|
case Instruction::SIToFP:
|
|
|
|
llvm_unreachable("Should have been handled in walkForwards!");
|
|
|
|
|
|
|
|
case Instruction::FAdd:
|
|
|
|
case Instruction::FSub:
|
|
|
|
case Instruction::FMul:
|
2016-12-01 21:08:47 +01:00
|
|
|
Op = [I](ArrayRef<ConstantRange> Ops) {
|
|
|
|
assert(Ops.size() == 2 && "its a binary operator!");
|
|
|
|
auto BinOp = (Instruction::BinaryOps) I->getOpcode();
|
|
|
|
return Ops[0].binaryOp(BinOp, Ops[1]);
|
2015-03-27 11:36:57 +01:00
|
|
|
};
|
|
|
|
break;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Root-only instructions - we'll only see these if they're the
|
|
|
|
// first node in a walk.
|
|
|
|
//
|
|
|
|
case Instruction::FPToUI:
|
|
|
|
case Instruction::FPToSI:
|
2016-12-01 21:08:47 +01:00
|
|
|
Op = [I](ArrayRef<ConstantRange> Ops) {
|
2015-03-27 11:36:57 +01:00
|
|
|
assert(Ops.size() == 1 && "FPTo[US]I is a unary operator!");
|
2016-12-01 21:08:47 +01:00
|
|
|
// Note: We're ignoring the casts output size here as that's what the
|
|
|
|
// caller expects.
|
|
|
|
auto CastOp = (Instruction::CastOps)I->getOpcode();
|
|
|
|
return Ops[0].castOp(CastOp, MaxIntegerBW+1);
|
2015-03-27 11:36:57 +01:00
|
|
|
};
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Instruction::FCmp:
|
|
|
|
Op = [](ArrayRef<ConstantRange> Ops) {
|
|
|
|
assert(Ops.size() == 2 && "FCmp is a binary operator!");
|
|
|
|
return Ops[0].unionWith(Ops[1]);
|
|
|
|
};
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Abort = false;
|
|
|
|
SmallVector<ConstantRange,4> OpRanges;
|
|
|
|
for (Value *O : I->operands()) {
|
|
|
|
if (Instruction *OI = dyn_cast<Instruction>(O)) {
|
|
|
|
assert(SeenInsts.find(OI) != SeenInsts.end() &&
|
2015-09-22 13:15:07 +02:00
|
|
|
"def not seen before use!");
|
2015-03-27 11:36:57 +01:00
|
|
|
OpRanges.push_back(SeenInsts.find(OI)->second);
|
|
|
|
} else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
|
|
|
|
// Work out if the floating point number can be losslessly represented
|
|
|
|
// as an integer.
|
|
|
|
// APFloat::convertToInteger(&Exact) purports to do what we want, but
|
|
|
|
// the exactness can be too precise. For example, negative zero can
|
|
|
|
// never be exactly converted to an integer.
|
|
|
|
//
|
|
|
|
// Instead, we ask APFloat to round itself to an integral value - this
|
|
|
|
// preserves sign-of-zero - then compare the result with the original.
|
|
|
|
//
|
2016-06-08 12:01:20 +02:00
|
|
|
const APFloat &F = CF->getValueAPF();
|
2015-03-27 11:36:57 +01:00
|
|
|
|
|
|
|
// First, weed out obviously incorrect values. Non-finite numbers
|
2015-09-22 13:14:12 +02:00
|
|
|
// can't be represented and neither can negative zero, unless
|
2015-03-27 11:36:57 +01:00
|
|
|
// we're in fast math mode.
|
|
|
|
if (!F.isFinite() ||
|
|
|
|
(F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
|
2015-09-22 13:15:07 +02:00
|
|
|
!I->hasNoSignedZeros())) {
|
2015-03-27 11:36:57 +01:00
|
|
|
seen(I, badRange());
|
|
|
|
Abort = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
APFloat NewF = F;
|
|
|
|
auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
|
|
|
|
if (Res != APFloat::opOK || NewF.compare(F) != APFloat::cmpEqual) {
|
|
|
|
seen(I, badRange());
|
|
|
|
Abort = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
// OK, it's representable. Now get it.
|
|
|
|
APSInt Int(MaxIntegerBW+1, false);
|
|
|
|
bool Exact;
|
|
|
|
CF->getValueAPF().convertToInteger(Int,
|
|
|
|
APFloat::rmNearestTiesToEven,
|
|
|
|
&Exact);
|
|
|
|
OpRanges.push_back(ConstantRange(Int));
|
|
|
|
} else {
|
|
|
|
llvm_unreachable("Should have already marked this as badRange!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reduce the operands' ranges to a single range and return.
|
|
|
|
if (!Abort)
|
2015-09-22 13:19:03 +02:00
|
|
|
seen(I, Op(OpRanges));
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there is a valid transform to be done, do it.
|
2016-06-25 01:32:02 +02:00
|
|
|
bool Float2IntPass::validateAndTransform() {
|
2015-03-27 11:36:57 +01:00
|
|
|
bool MadeChange = false;
|
|
|
|
|
|
|
|
// Iterate over every disjoint partition of the def-use graph.
|
|
|
|
for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
|
|
|
|
ConstantRange R(MaxIntegerBW + 1, false);
|
|
|
|
bool Fail = false;
|
|
|
|
Type *ConvertedToTy = nullptr;
|
|
|
|
|
|
|
|
// For every member of the partition, union all the ranges together.
|
|
|
|
for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
|
|
|
|
MI != ME; ++MI) {
|
|
|
|
Instruction *I = *MI;
|
|
|
|
auto SeenI = SeenInsts.find(I);
|
|
|
|
if (SeenI == SeenInsts.end())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
R = R.unionWith(SeenI->second);
|
|
|
|
// We need to ensure I has no users that have not been seen.
|
|
|
|
// If it does, transformation would be illegal.
|
|
|
|
//
|
|
|
|
// Don't count the roots, as they terminate the graphs.
|
|
|
|
if (Roots.count(I) == 0) {
|
|
|
|
// Set the type of the conversion while we're here.
|
|
|
|
if (!ConvertedToTy)
|
|
|
|
ConvertedToTy = I->getType();
|
|
|
|
for (User *U : I->users()) {
|
|
|
|
Instruction *UI = dyn_cast<Instruction>(U);
|
|
|
|
if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
|
2015-03-27 11:36:57 +01:00
|
|
|
Fail = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Fail)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the set was empty, or we failed, or the range is poisonous,
|
|
|
|
// bail out.
|
|
|
|
if (ECs.member_begin(It) == ECs.member_end() || Fail ||
|
|
|
|
R.isFullSet() || R.isSignWrappedSet())
|
|
|
|
continue;
|
|
|
|
assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
|
2015-09-22 13:14:39 +02:00
|
|
|
|
2015-03-27 11:36:57 +01:00
|
|
|
// The number of bits required is the maximum of the upper and
|
|
|
|
// lower limits, plus one so it can be signed.
|
|
|
|
unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
|
|
|
|
R.getUpper().getMinSignedBits()) + 1;
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
|
2015-03-27 11:36:57 +01:00
|
|
|
|
|
|
|
// If we've run off the realms of the exactly representable integers,
|
|
|
|
// the floating point result will differ from an integer approximation.
|
|
|
|
|
|
|
|
// Do we need more bits than are in the mantissa of the type we converted
|
|
|
|
// to? semanticsPrecision returns the number of mantissa bits plus one
|
|
|
|
// for the sign bit.
|
|
|
|
unsigned MaxRepresentableBits
|
|
|
|
= APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
|
|
|
|
if (MinBW > MaxRepresentableBits) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
|
2015-03-27 11:36:57 +01:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (MinBW > 64) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
|
2015-03-27 11:36:57 +01:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// OK, R is known to be representable. Now pick a type for it.
|
|
|
|
// FIXME: Pick the smallest legal type that will fit.
|
|
|
|
Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
|
|
|
|
|
|
|
|
for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
|
|
|
|
MI != ME; ++MI)
|
|
|
|
convert(*MI, Ty);
|
|
|
|
MadeChange = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return MadeChange;
|
|
|
|
}
|
|
|
|
|
2016-06-25 01:32:02 +02:00
|
|
|
Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
|
2015-03-27 11:36:57 +01:00
|
|
|
if (ConvertedInsts.find(I) != ConvertedInsts.end())
|
|
|
|
// Already converted this instruction.
|
|
|
|
return ConvertedInsts[I];
|
|
|
|
|
|
|
|
SmallVector<Value*,4> NewOperands;
|
|
|
|
for (Value *V : I->operands()) {
|
|
|
|
// Don't recurse if we're an instruction that terminates the path.
|
|
|
|
if (I->getOpcode() == Instruction::UIToFP ||
|
|
|
|
I->getOpcode() == Instruction::SIToFP) {
|
|
|
|
NewOperands.push_back(V);
|
|
|
|
} else if (Instruction *VI = dyn_cast<Instruction>(V)) {
|
|
|
|
NewOperands.push_back(convert(VI, ToTy));
|
|
|
|
} else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
|
|
|
|
APSInt Val(ToTy->getPrimitiveSizeInBits(), /*IsUnsigned=*/false);
|
|
|
|
bool Exact;
|
|
|
|
CF->getValueAPF().convertToInteger(Val,
|
|
|
|
APFloat::rmNearestTiesToEven,
|
|
|
|
&Exact);
|
|
|
|
NewOperands.push_back(ConstantInt::get(ToTy, Val));
|
|
|
|
} else {
|
|
|
|
llvm_unreachable("Unhandled operand type?");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now create a new instruction.
|
|
|
|
IRBuilder<> IRB(I);
|
|
|
|
Value *NewV = nullptr;
|
|
|
|
switch (I->getOpcode()) {
|
|
|
|
default: llvm_unreachable("Unhandled instruction!");
|
|
|
|
|
|
|
|
case Instruction::FPToUI:
|
|
|
|
NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Instruction::FPToSI:
|
|
|
|
NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Instruction::FCmp: {
|
|
|
|
CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
|
|
|
|
assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
|
|
|
|
NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
case Instruction::UIToFP:
|
|
|
|
NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Instruction::SIToFP:
|
|
|
|
NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Instruction::FAdd:
|
|
|
|
case Instruction::FSub:
|
|
|
|
case Instruction::FMul:
|
|
|
|
NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
|
|
|
|
NewOperands[0], NewOperands[1],
|
|
|
|
I->getName());
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we're a root instruction, RAUW.
|
|
|
|
if (Roots.count(I))
|
|
|
|
I->replaceAllUsesWith(NewV);
|
|
|
|
|
|
|
|
ConvertedInsts[I] = NewV;
|
|
|
|
return NewV;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Perform dead code elimination on the instructions we just modified.
|
2016-06-25 01:32:02 +02:00
|
|
|
void Float2IntPass::cleanup() {
|
2016-06-24 06:05:21 +02:00
|
|
|
for (auto &I : reverse(ConvertedInsts))
|
2015-07-24 23:13:43 +02:00
|
|
|
I.first->eraseFromParent();
|
2015-03-27 11:36:57 +01:00
|
|
|
}
|
|
|
|
|
2016-06-25 01:32:02 +02:00
|
|
|
bool Float2IntPass::runImpl(Function &F) {
|
2018-05-14 14:53:11 +02:00
|
|
|
LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
|
2015-03-27 11:36:57 +01:00
|
|
|
// Clear out all state.
|
|
|
|
ECs = EquivalenceClasses<Instruction*>();
|
|
|
|
SeenInsts.clear();
|
|
|
|
ConvertedInsts.clear();
|
|
|
|
Roots.clear();
|
|
|
|
|
|
|
|
Ctx = &F.getParent()->getContext();
|
|
|
|
|
|
|
|
findRoots(F, Roots);
|
|
|
|
|
|
|
|
walkBackwards(Roots);
|
|
|
|
walkForwards();
|
|
|
|
|
|
|
|
bool Modified = validateAndTransform();
|
|
|
|
if (Modified)
|
|
|
|
cleanup();
|
|
|
|
return Modified;
|
|
|
|
}
|
|
|
|
|
2016-06-25 01:32:02 +02:00
|
|
|
namespace llvm {
|
|
|
|
FunctionPass *createFloat2IntPass() { return new Float2IntLegacyPass(); }
|
|
|
|
|
|
|
|
PreservedAnalyses Float2IntPass::run(Function &F, FunctionAnalysisManager &) {
|
|
|
|
if (!runImpl(F))
|
|
|
|
return PreservedAnalyses::all();
|
2017-01-15 07:32:49 +01:00
|
|
|
|
|
|
|
PreservedAnalyses PA;
|
|
|
|
PA.preserveSet<CFGAnalyses>();
|
|
|
|
PA.preserve<GlobalsAA>();
|
|
|
|
return PA;
|
2016-06-25 01:32:02 +02:00
|
|
|
}
|
|
|
|
} // End namespace llvm
|