blob: cb0288a28f79d09dabbbea4dddc00120e114954f [file] [log] [blame]
James Molloy0cbb2a862015-03-27 10:36:57 +00001//===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
James Molloy0cbb2a862015-03-27 10:36:57 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Float2Int pass, which aims to demote floating
10// point operations to work on integers, where that is losslessly possible.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "float2int"
Michael Kuperstein83b753d2016-06-24 23:32:02 +000015
16#include "llvm/Transforms/Scalar/Float2Int.h"
James Molloy0cbb2a862015-03-27 10:36:57 +000017#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/APSInt.h"
James Molloy0cbb2a862015-03-27 10:36:57 +000019#include "llvm/ADT/SmallVector.h"
Chandler Carruth08eebe22015-07-23 09:34:01 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000021#include "llvm/Analysis/GlobalsModRef.h"
James Molloy0cbb2a862015-03-27 10:36:57 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/InstIterator.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Pass.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/Transforms/Scalar.h"
31#include <deque>
32#include <functional> // For std::function
33using namespace llvm;
34
35// The algorithm is simple. Start at instructions that convert from the
36// float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
37// graph, using an equivalence datastructure to unify graphs that interfere.
38//
39// Mappable instructions are those with an integer corrollary that, given
40// integer domain inputs, produce an integer output; fadd, for example.
41//
42// If a non-mappable instruction is seen, this entire def-use graph is marked
NAKAMURA Takumi84965032015-09-22 11:14:12 +000043// as non-transformable. If we see an instruction that converts from the
James Molloy0cbb2a862015-03-27 10:36:57 +000044// integer domain to FP domain (uitofp,sitofp), we terminate our walk.
45
46/// The largest integer type worth dealing with.
47static cl::opt<unsigned>
48MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
49 cl::desc("Max integer bitwidth to consider in float2int"
50 "(default=64)"));
51
52namespace {
Michael Kuperstein83b753d2016-06-24 23:32:02 +000053 struct Float2IntLegacyPass : public FunctionPass {
James Molloy0cbb2a862015-03-27 10:36:57 +000054 static char ID; // Pass identification, replacement for typeid
Michael Kuperstein83b753d2016-06-24 23:32:02 +000055 Float2IntLegacyPass() : FunctionPass(ID) {
56 initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
James Molloy0cbb2a862015-03-27 10:36:57 +000057 }
58
Michael Kuperstein83b753d2016-06-24 23:32:02 +000059 bool runOnFunction(Function &F) override {
60 if (skipFunction(F))
61 return false;
62
63 return Impl.runImpl(F);
64 }
65
James Molloy0cbb2a862015-03-27 10:36:57 +000066 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +000068 AU.addPreserved<GlobalsAAWrapperPass>();
James Molloy0cbb2a862015-03-27 10:36:57 +000069 }
70
Michael Kuperstein83b753d2016-06-24 23:32:02 +000071 private:
72 Float2IntPass Impl;
James Molloy0cbb2a862015-03-27 10:36:57 +000073 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000074}
James Molloy0cbb2a862015-03-27 10:36:57 +000075
Michael Kuperstein83b753d2016-06-24 23:32:02 +000076char Float2IntLegacyPass::ID = 0;
77INITIALIZE_PASS(Float2IntLegacyPass, "float2int", "Float to int", false, false)
James Molloy0cbb2a862015-03-27 10:36:57 +000078
79// Given a FCmp predicate, return a matching ICmp predicate if one
80// exists, otherwise return BAD_ICMP_PREDICATE.
81static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
82 switch (P) {
83 case CmpInst::FCMP_OEQ:
84 case CmpInst::FCMP_UEQ:
85 return CmpInst::ICMP_EQ;
86 case CmpInst::FCMP_OGT:
87 case CmpInst::FCMP_UGT:
88 return CmpInst::ICMP_SGT;
89 case CmpInst::FCMP_OGE:
90 case CmpInst::FCMP_UGE:
91 return CmpInst::ICMP_SGE;
92 case CmpInst::FCMP_OLT:
93 case CmpInst::FCMP_ULT:
94 return CmpInst::ICMP_SLT;
95 case CmpInst::FCMP_OLE:
96 case CmpInst::FCMP_ULE:
97 return CmpInst::ICMP_SLE;
98 case CmpInst::FCMP_ONE:
99 case CmpInst::FCMP_UNE:
100 return CmpInst::ICMP_NE;
101 default:
102 return CmpInst::BAD_ICMP_PREDICATE;
103 }
104}
105
106// Given a floating point binary operator, return the matching
107// integer version.
108static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
109 switch (Opcode) {
110 default: llvm_unreachable("Unhandled opcode!");
111 case Instruction::FAdd: return Instruction::Add;
112 case Instruction::FSub: return Instruction::Sub;
113 case Instruction::FMul: return Instruction::Mul;
114 }
115}
116
117// Find the roots - instructions that convert from the FP domain to
118// integer domain.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000119void Float2IntPass::findRoots(Function &F, SmallPtrSet<Instruction*,8> &Roots) {
Nico Rieck78199512015-08-06 19:10:45 +0000120 for (auto &I : instructions(F)) {
Reid Kleckner54ade232015-12-09 21:08:18 +0000121 if (isa<VectorType>(I.getType()))
122 continue;
James Molloy0cbb2a862015-03-27 10:36:57 +0000123 switch (I.getOpcode()) {
124 default: break;
125 case Instruction::FPToUI:
126 case Instruction::FPToSI:
127 Roots.insert(&I);
128 break;
129 case Instruction::FCmp:
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +0000130 if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
James Molloy0cbb2a862015-03-27 10:36:57 +0000131 CmpInst::BAD_ICMP_PREDICATE)
132 Roots.insert(&I);
133 break;
134 }
135 }
136}
137
138// Helper - mark I as having been traversed, having range R.
Craig Topper5974dad2017-05-04 21:29:45 +0000139void Float2IntPass::seen(Instruction *I, ConstantRange R) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000140 LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
Craig Topperfc481e52017-05-05 17:09:29 +0000141 auto IT = SeenInsts.find(I);
142 if (IT != SeenInsts.end())
143 IT->second = std::move(R);
James Molloy0cbb2a862015-03-27 10:36:57 +0000144 else
Craig Topperfc481e52017-05-05 17:09:29 +0000145 SeenInsts.insert(std::make_pair(I, std::move(R)));
James Molloy0cbb2a862015-03-27 10:36:57 +0000146}
147
148// Helper - get a range representing a poison value.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000149ConstantRange Float2IntPass::badRange() {
Nikita Popov977934f2019-03-24 09:34:40 +0000150 return ConstantRange::getFull(MaxIntegerBW + 1);
James Molloy0cbb2a862015-03-27 10:36:57 +0000151}
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000152ConstantRange Float2IntPass::unknownRange() {
Nikita Popov977934f2019-03-24 09:34:40 +0000153 return ConstantRange::getEmpty(MaxIntegerBW + 1);
James Molloy0cbb2a862015-03-27 10:36:57 +0000154}
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000155ConstantRange Float2IntPass::validateRange(ConstantRange R) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000156 if (R.getBitWidth() > MaxIntegerBW + 1)
157 return badRange();
158 return R;
159}
160
161// The most obvious way to structure the search is a depth-first, eager
162// search from each root. However, that require direct recursion and so
163// can only handle small instruction sequences. Instead, we split the search
164// up into two phases:
165// - walkBackwards: A breadth-first walk of the use-def graph starting from
166// the roots. Populate "SeenInsts" with interesting
167// instructions and poison values if they're obvious and
168// cheap to compute. Calculate the equivalance set structure
169// while we're here too.
170// - walkForwards: Iterate over SeenInsts in reverse order, so we visit
171// defs before their uses. Calculate the real range info.
172
NAKAMURA Takumi84965032015-09-22 11:14:12 +0000173// Breadth-first walk of the use-def graph; determine the set of nodes
James Molloy0cbb2a862015-03-27 10:36:57 +0000174// we care about and eagerly determine if some of them are poisonous.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000175void Float2IntPass::walkBackwards(const SmallPtrSetImpl<Instruction*> &Roots) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000176 std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
177 while (!Worklist.empty()) {
178 Instruction *I = Worklist.back();
179 Worklist.pop_back();
180
181 if (SeenInsts.find(I) != SeenInsts.end())
182 // Seen already.
183 continue;
184
185 switch (I->getOpcode()) {
186 // FIXME: Handle select and phi nodes.
187 default:
188 // Path terminated uncleanly.
189 seen(I, badRange());
190 break;
191
Philip Reames4d00af12016-12-01 20:08:47 +0000192 case Instruction::UIToFP:
James Molloy0cbb2a862015-03-27 10:36:57 +0000193 case Instruction::SIToFP: {
Philip Reames4d00af12016-12-01 20:08:47 +0000194 // Path terminated cleanly - use the type of the integer input to seed
195 // the analysis.
James Molloy0cbb2a862015-03-27 10:36:57 +0000196 unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Nikita Popov977934f2019-03-24 09:34:40 +0000197 auto Input = ConstantRange::getFull(BW);
Philip Reames4d00af12016-12-01 20:08:47 +0000198 auto CastOp = (Instruction::CastOps)I->getOpcode();
199 seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
James Molloy0cbb2a862015-03-27 10:36:57 +0000200 continue;
201 }
202
203 case Instruction::FAdd:
204 case Instruction::FSub:
205 case Instruction::FMul:
206 case Instruction::FPToUI:
207 case Instruction::FPToSI:
208 case Instruction::FCmp:
209 seen(I, unknownRange());
210 break;
211 }
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000212
James Molloy0cbb2a862015-03-27 10:36:57 +0000213 for (Value *O : I->operands()) {
214 if (Instruction *OI = dyn_cast<Instruction>(O)) {
215 // Unify def-use chains if they interfere.
216 ECs.unionSets(I, OI);
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000217 if (SeenInsts.find(I)->second != badRange())
James Molloy0cbb2a862015-03-27 10:36:57 +0000218 Worklist.push_back(OI);
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +0000219 } else if (!isa<ConstantFP>(O)) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000220 // Not an instruction or ConstantFP? we can't do anything.
221 seen(I, badRange());
222 }
223 }
224 }
225}
226
227// Walk forwards down the list of seen instructions, so we visit defs before
228// uses.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000229void Float2IntPass::walkForwards() {
David Majnemerd7708772016-06-24 04:05:21 +0000230 for (auto &It : reverse(SeenInsts)) {
Pete Cooper7679afd2015-07-24 21:13:43 +0000231 if (It.second != unknownRange())
James Molloy0cbb2a862015-03-27 10:36:57 +0000232 continue;
233
Pete Cooper7679afd2015-07-24 21:13:43 +0000234 Instruction *I = It.first;
James Molloy0cbb2a862015-03-27 10:36:57 +0000235 std::function<ConstantRange(ArrayRef<ConstantRange>)> Op;
236 switch (I->getOpcode()) {
237 // FIXME: Handle select and phi nodes.
238 default:
239 case Instruction::UIToFP:
240 case Instruction::SIToFP:
241 llvm_unreachable("Should have been handled in walkForwards!");
242
243 case Instruction::FAdd:
James Molloy0cbb2a862015-03-27 10:36:57 +0000244 case Instruction::FSub:
James Molloy0cbb2a862015-03-27 10:36:57 +0000245 case Instruction::FMul:
Philip Reames4d00af12016-12-01 20:08:47 +0000246 Op = [I](ArrayRef<ConstantRange> Ops) {
247 assert(Ops.size() == 2 && "its a binary operator!");
248 auto BinOp = (Instruction::BinaryOps) I->getOpcode();
249 return Ops[0].binaryOp(BinOp, Ops[1]);
James Molloy0cbb2a862015-03-27 10:36:57 +0000250 };
251 break;
252
253 //
254 // Root-only instructions - we'll only see these if they're the
255 // first node in a walk.
256 //
257 case Instruction::FPToUI:
258 case Instruction::FPToSI:
Philip Reames4d00af12016-12-01 20:08:47 +0000259 Op = [I](ArrayRef<ConstantRange> Ops) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000260 assert(Ops.size() == 1 && "FPTo[US]I is a unary operator!");
Philip Reames4d00af12016-12-01 20:08:47 +0000261 // Note: We're ignoring the casts output size here as that's what the
262 // caller expects.
263 auto CastOp = (Instruction::CastOps)I->getOpcode();
264 return Ops[0].castOp(CastOp, MaxIntegerBW+1);
James Molloy0cbb2a862015-03-27 10:36:57 +0000265 };
266 break;
267
268 case Instruction::FCmp:
269 Op = [](ArrayRef<ConstantRange> Ops) {
270 assert(Ops.size() == 2 && "FCmp is a binary operator!");
271 return Ops[0].unionWith(Ops[1]);
272 };
273 break;
274 }
275
276 bool Abort = false;
277 SmallVector<ConstantRange,4> OpRanges;
278 for (Value *O : I->operands()) {
279 if (Instruction *OI = dyn_cast<Instruction>(O)) {
280 assert(SeenInsts.find(OI) != SeenInsts.end() &&
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000281 "def not seen before use!");
James Molloy0cbb2a862015-03-27 10:36:57 +0000282 OpRanges.push_back(SeenInsts.find(OI)->second);
283 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
284 // Work out if the floating point number can be losslessly represented
285 // as an integer.
286 // APFloat::convertToInteger(&Exact) purports to do what we want, but
287 // the exactness can be too precise. For example, negative zero can
288 // never be exactly converted to an integer.
289 //
290 // Instead, we ask APFloat to round itself to an integral value - this
291 // preserves sign-of-zero - then compare the result with the original.
292 //
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000293 const APFloat &F = CF->getValueAPF();
James Molloy0cbb2a862015-03-27 10:36:57 +0000294
295 // First, weed out obviously incorrect values. Non-finite numbers
NAKAMURA Takumi84965032015-09-22 11:14:12 +0000296 // can't be represented and neither can negative zero, unless
James Molloy0cbb2a862015-03-27 10:36:57 +0000297 // we're in fast math mode.
298 if (!F.isFinite() ||
299 (F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000300 !I->hasNoSignedZeros())) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000301 seen(I, badRange());
302 Abort = true;
303 break;
304 }
305
306 APFloat NewF = F;
307 auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
308 if (Res != APFloat::opOK || NewF.compare(F) != APFloat::cmpEqual) {
309 seen(I, badRange());
310 Abort = true;
311 break;
312 }
313 // OK, it's representable. Now get it.
314 APSInt Int(MaxIntegerBW+1, false);
315 bool Exact;
316 CF->getValueAPF().convertToInteger(Int,
317 APFloat::rmNearestTiesToEven,
318 &Exact);
319 OpRanges.push_back(ConstantRange(Int));
320 } else {
321 llvm_unreachable("Should have already marked this as badRange!");
322 }
323 }
324
325 // Reduce the operands' ranges to a single range and return.
326 if (!Abort)
NAKAMURA Takumi10c80e72015-09-22 11:19:03 +0000327 seen(I, Op(OpRanges));
James Molloy0cbb2a862015-03-27 10:36:57 +0000328 }
329}
330
331// If there is a valid transform to be done, do it.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000332bool Float2IntPass::validateAndTransform() {
James Molloy0cbb2a862015-03-27 10:36:57 +0000333 bool MadeChange = false;
334
335 // Iterate over every disjoint partition of the def-use graph.
336 for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
337 ConstantRange R(MaxIntegerBW + 1, false);
338 bool Fail = false;
339 Type *ConvertedToTy = nullptr;
340
341 // For every member of the partition, union all the ranges together.
342 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
343 MI != ME; ++MI) {
344 Instruction *I = *MI;
345 auto SeenI = SeenInsts.find(I);
346 if (SeenI == SeenInsts.end())
347 continue;
348
349 R = R.unionWith(SeenI->second);
350 // We need to ensure I has no users that have not been seen.
351 // If it does, transformation would be illegal.
352 //
353 // Don't count the roots, as they terminate the graphs.
354 if (Roots.count(I) == 0) {
355 // Set the type of the conversion while we're here.
356 if (!ConvertedToTy)
357 ConvertedToTy = I->getType();
358 for (User *U : I->users()) {
359 Instruction *UI = dyn_cast<Instruction>(U);
360 if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000361 LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
James Molloy0cbb2a862015-03-27 10:36:57 +0000362 Fail = true;
363 break;
364 }
365 }
366 }
367 if (Fail)
368 break;
369 }
370
371 // If the set was empty, or we failed, or the range is poisonous,
372 // bail out.
373 if (ECs.member_begin(It) == ECs.member_end() || Fail ||
374 R.isFullSet() || R.isSignWrappedSet())
375 continue;
376 assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000377
James Molloy0cbb2a862015-03-27 10:36:57 +0000378 // The number of bits required is the maximum of the upper and
379 // lower limits, plus one so it can be signed.
380 unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
381 R.getUpper().getMinSignedBits()) + 1;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000382 LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
James Molloy0cbb2a862015-03-27 10:36:57 +0000383
384 // If we've run off the realms of the exactly representable integers,
385 // the floating point result will differ from an integer approximation.
386
387 // Do we need more bits than are in the mantissa of the type we converted
388 // to? semanticsPrecision returns the number of mantissa bits plus one
389 // for the sign bit.
390 unsigned MaxRepresentableBits
391 = APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
392 if (MinBW > MaxRepresentableBits) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000393 LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
James Molloy0cbb2a862015-03-27 10:36:57 +0000394 continue;
395 }
396 if (MinBW > 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000397 LLVM_DEBUG(
398 dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
James Molloy0cbb2a862015-03-27 10:36:57 +0000399 continue;
400 }
401
402 // OK, R is known to be representable. Now pick a type for it.
403 // FIXME: Pick the smallest legal type that will fit.
404 Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
405
406 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
407 MI != ME; ++MI)
408 convert(*MI, Ty);
409 MadeChange = true;
410 }
411
412 return MadeChange;
413}
414
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000415Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
James Molloy0cbb2a862015-03-27 10:36:57 +0000416 if (ConvertedInsts.find(I) != ConvertedInsts.end())
417 // Already converted this instruction.
418 return ConvertedInsts[I];
419
420 SmallVector<Value*,4> NewOperands;
421 for (Value *V : I->operands()) {
422 // Don't recurse if we're an instruction that terminates the path.
423 if (I->getOpcode() == Instruction::UIToFP ||
424 I->getOpcode() == Instruction::SIToFP) {
425 NewOperands.push_back(V);
426 } else if (Instruction *VI = dyn_cast<Instruction>(V)) {
427 NewOperands.push_back(convert(VI, ToTy));
428 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
429 APSInt Val(ToTy->getPrimitiveSizeInBits(), /*IsUnsigned=*/false);
430 bool Exact;
431 CF->getValueAPF().convertToInteger(Val,
432 APFloat::rmNearestTiesToEven,
433 &Exact);
434 NewOperands.push_back(ConstantInt::get(ToTy, Val));
435 } else {
436 llvm_unreachable("Unhandled operand type?");
437 }
438 }
439
440 // Now create a new instruction.
441 IRBuilder<> IRB(I);
442 Value *NewV = nullptr;
443 switch (I->getOpcode()) {
444 default: llvm_unreachable("Unhandled instruction!");
445
446 case Instruction::FPToUI:
447 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
448 break;
449
450 case Instruction::FPToSI:
451 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
452 break;
453
454 case Instruction::FCmp: {
455 CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
456 assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
457 NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
458 break;
459 }
460
461 case Instruction::UIToFP:
462 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
463 break;
464
465 case Instruction::SIToFP:
466 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
467 break;
468
469 case Instruction::FAdd:
470 case Instruction::FSub:
471 case Instruction::FMul:
472 NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
473 NewOperands[0], NewOperands[1],
474 I->getName());
475 break;
476 }
477
478 // If we're a root instruction, RAUW.
479 if (Roots.count(I))
480 I->replaceAllUsesWith(NewV);
481
482 ConvertedInsts[I] = NewV;
483 return NewV;
484}
485
486// Perform dead code elimination on the instructions we just modified.
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000487void Float2IntPass::cleanup() {
David Majnemerd7708772016-06-24 04:05:21 +0000488 for (auto &I : reverse(ConvertedInsts))
Pete Cooper7679afd2015-07-24 21:13:43 +0000489 I.first->eraseFromParent();
James Molloy0cbb2a862015-03-27 10:36:57 +0000490}
491
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000492bool Float2IntPass::runImpl(Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000493 LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
James Molloy0cbb2a862015-03-27 10:36:57 +0000494 // Clear out all state.
495 ECs = EquivalenceClasses<Instruction*>();
496 SeenInsts.clear();
497 ConvertedInsts.clear();
498 Roots.clear();
499
500 Ctx = &F.getParent()->getContext();
501
502 findRoots(F, Roots);
503
504 walkBackwards(Roots);
505 walkForwards();
506
507 bool Modified = validateAndTransform();
508 if (Modified)
509 cleanup();
510 return Modified;
511}
512
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000513namespace llvm {
514FunctionPass *createFloat2IntPass() { return new Float2IntLegacyPass(); }
515
516PreservedAnalyses Float2IntPass::run(Function &F, FunctionAnalysisManager &) {
517 if (!runImpl(F))
518 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000519
520 PreservedAnalyses PA;
521 PA.preserveSet<CFGAnalyses>();
522 PA.preserve<GlobalsAA>();
523 return PA;
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000524}
525} // End namespace llvm