1 //===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Float2Int pass, which aims to demote floating
10 // point operations to work on integers, where that is losslessly possible.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/Float2Int.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include <deque>
30 #include <functional> // For std::function
31 
32 #define DEBUG_TYPE "float2int"
33 
34 using namespace llvm;
35 
36 // The algorithm is simple. Start at instructions that convert from the
37 // float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
38 // graph, using an equivalence datastructure to unify graphs that interfere.
39 //
40 // Mappable instructions are those with an integer corrollary that, given
41 // integer domain inputs, produce an integer output; fadd, for example.
42 //
43 // If a non-mappable instruction is seen, this entire def-use graph is marked
44 // as non-transformable. If we see an instruction that converts from the
45 // integer domain to FP domain (uitofp,sitofp), we terminate our walk.
46 
47 /// The largest integer type worth dealing with.
48 static cl::opt<unsigned>
49 MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
50              cl::desc("Max integer bitwidth to consider in float2int"
51                       "(default=64)"));
52 
53 namespace {
54   struct Float2IntLegacyPass : public FunctionPass {
55     static char ID; // Pass identification, replacement for typeid
56     Float2IntLegacyPass() : FunctionPass(ID) {
57       initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
58     }
59 
60     bool runOnFunction(Function &F) override {
61       if (skipFunction(F))
62         return false;
63 
64       const DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
65       return Impl.runImpl(F, DT);
66     }
67 
68     void getAnalysisUsage(AnalysisUsage &AU) const override {
69       AU.setPreservesCFG();
70       AU.addRequired<DominatorTreeWrapperPass>();
71       AU.addPreserved<GlobalsAAWrapperPass>();
72     }
73 
74   private:
75     Float2IntPass Impl;
76   };
77 }
78 
79 char Float2IntLegacyPass::ID = 0;
80 INITIALIZE_PASS(Float2IntLegacyPass, "float2int", "Float to int", false, false)
81 
82 // Given a FCmp predicate, return a matching ICmp predicate if one
83 // exists, otherwise return BAD_ICMP_PREDICATE.
84 static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
85   switch (P) {
86   case CmpInst::FCMP_OEQ:
87   case CmpInst::FCMP_UEQ:
88     return CmpInst::ICMP_EQ;
89   case CmpInst::FCMP_OGT:
90   case CmpInst::FCMP_UGT:
91     return CmpInst::ICMP_SGT;
92   case CmpInst::FCMP_OGE:
93   case CmpInst::FCMP_UGE:
94     return CmpInst::ICMP_SGE;
95   case CmpInst::FCMP_OLT:
96   case CmpInst::FCMP_ULT:
97     return CmpInst::ICMP_SLT;
98   case CmpInst::FCMP_OLE:
99   case CmpInst::FCMP_ULE:
100     return CmpInst::ICMP_SLE;
101   case CmpInst::FCMP_ONE:
102   case CmpInst::FCMP_UNE:
103     return CmpInst::ICMP_NE;
104   default:
105     return CmpInst::BAD_ICMP_PREDICATE;
106   }
107 }
108 
109 // Given a floating point binary operator, return the matching
110 // integer version.
111 static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
112   switch (Opcode) {
113   default: llvm_unreachable("Unhandled opcode!");
114   case Instruction::FAdd: return Instruction::Add;
115   case Instruction::FSub: return Instruction::Sub;
116   case Instruction::FMul: return Instruction::Mul;
117   }
118 }
119 
120 // Find the roots - instructions that convert from the FP domain to
121 // integer domain.
122 void Float2IntPass::findRoots(Function &F, const DominatorTree &DT) {
123   for (BasicBlock &BB : F) {
124     // Unreachable code can take on strange forms that we are not prepared to
125     // handle. For example, an instruction may have itself as an operand.
126     if (!DT.isReachableFromEntry(&BB))
127       continue;
128 
129     for (Instruction &I : BB) {
130       if (isa<VectorType>(I.getType()))
131         continue;
132       switch (I.getOpcode()) {
133       default: break;
134       case Instruction::FPToUI:
135       case Instruction::FPToSI:
136         Roots.insert(&I);
137         break;
138       case Instruction::FCmp:
139         if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
140             CmpInst::BAD_ICMP_PREDICATE)
141           Roots.insert(&I);
142         break;
143       }
144     }
145   }
146 }
147 
148 // Helper - mark I as having been traversed, having range R.
149 void Float2IntPass::seen(Instruction *I, ConstantRange R) {
150   LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
151   auto IT = SeenInsts.find(I);
152   if (IT != SeenInsts.end())
153     IT->second = std::move(R);
154   else
155     SeenInsts.insert(std::make_pair(I, std::move(R)));
156 }
157 
158 // Helper - get a range representing a poison value.
159 ConstantRange Float2IntPass::badRange() {
160   return ConstantRange::getFull(MaxIntegerBW + 1);
161 }
162 ConstantRange Float2IntPass::unknownRange() {
163   return ConstantRange::getEmpty(MaxIntegerBW + 1);
164 }
165 ConstantRange Float2IntPass::validateRange(ConstantRange R) {
166   if (R.getBitWidth() > MaxIntegerBW + 1)
167     return badRange();
168   return R;
169 }
170 
171 // The most obvious way to structure the search is a depth-first, eager
172 // search from each root. However, that require direct recursion and so
173 // can only handle small instruction sequences. Instead, we split the search
174 // up into two phases:
175 //   - walkBackwards:  A breadth-first walk of the use-def graph starting from
176 //                     the roots. Populate "SeenInsts" with interesting
177 //                     instructions and poison values if they're obvious and
178 //                     cheap to compute. Calculate the equivalance set structure
179 //                     while we're here too.
180 //   - walkForwards:  Iterate over SeenInsts in reverse order, so we visit
181 //                     defs before their uses. Calculate the real range info.
182 
183 // Breadth-first walk of the use-def graph; determine the set of nodes
184 // we care about and eagerly determine if some of them are poisonous.
185 void Float2IntPass::walkBackwards() {
186   std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
187   while (!Worklist.empty()) {
188     Instruction *I = Worklist.back();
189     Worklist.pop_back();
190 
191     if (SeenInsts.find(I) != SeenInsts.end())
192       // Seen already.
193       continue;
194 
195     switch (I->getOpcode()) {
196       // FIXME: Handle select and phi nodes.
197     default:
198       // Path terminated uncleanly.
199       seen(I, badRange());
200       break;
201 
202     case Instruction::UIToFP:
203     case Instruction::SIToFP: {
204       // Path terminated cleanly - use the type of the integer input to seed
205       // the analysis.
206       unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
207       auto Input = ConstantRange::getFull(BW);
208       auto CastOp = (Instruction::CastOps)I->getOpcode();
209       seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
210       continue;
211     }
212 
213     case Instruction::FNeg:
214     case Instruction::FAdd:
215     case Instruction::FSub:
216     case Instruction::FMul:
217     case Instruction::FPToUI:
218     case Instruction::FPToSI:
219     case Instruction::FCmp:
220       seen(I, unknownRange());
221       break;
222     }
223 
224     for (Value *O : I->operands()) {
225       if (Instruction *OI = dyn_cast<Instruction>(O)) {
226         // Unify def-use chains if they interfere.
227         ECs.unionSets(I, OI);
228         if (SeenInsts.find(I)->second != badRange())
229           Worklist.push_back(OI);
230       } else if (!isa<ConstantFP>(O)) {
231         // Not an instruction or ConstantFP? we can't do anything.
232         seen(I, badRange());
233       }
234     }
235   }
236 }
237 
238 // Calculate result range from operand ranges
239 ConstantRange Float2IntPass::calcRange(Instruction *I) {
240   std::function<ConstantRange(ArrayRef<ConstantRange>)> Op;
241   switch (I->getOpcode()) {
242     // FIXME: Handle select and phi nodes.
243   default:
244   case Instruction::UIToFP:
245   case Instruction::SIToFP:
246     llvm_unreachable("Should have been handled in walkForwards!");
247 
248   case Instruction::FNeg:
249     Op = [](ArrayRef<ConstantRange> Ops) {
250       assert(Ops.size() == 1 && "FNeg is a unary operator!");
251       unsigned Size = Ops[0].getBitWidth();
252       auto Zero = ConstantRange(APInt::getZero(Size));
253       return Zero.sub(Ops[0]);
254     };
255     break;
256 
257   case Instruction::FAdd:
258   case Instruction::FSub:
259   case Instruction::FMul:
260     Op = [I](ArrayRef<ConstantRange> Ops) {
261       assert(Ops.size() == 2 && "its a binary operator!");
262       auto BinOp = (Instruction::BinaryOps) I->getOpcode();
263       return Ops[0].binaryOp(BinOp, Ops[1]);
264     };
265     break;
266 
267   //
268   // Root-only instructions - we'll only see these if they're the
269   //                          first node in a walk.
270   //
271   case Instruction::FPToUI:
272   case Instruction::FPToSI:
273     Op = [I](ArrayRef<ConstantRange> Ops) {
274       assert(Ops.size() == 1 && "FPTo[US]I is a unary operator!");
275       // Note: We're ignoring the casts output size here as that's what the
276       // caller expects.
277       auto CastOp = (Instruction::CastOps)I->getOpcode();
278       return Ops[0].castOp(CastOp, MaxIntegerBW+1);
279     };
280     break;
281 
282   case Instruction::FCmp:
283     Op = [](ArrayRef<ConstantRange> Ops) {
284       assert(Ops.size() == 2 && "FCmp is a binary operator!");
285       return Ops[0].unionWith(Ops[1]);
286     };
287     break;
288   }
289 
290   SmallVector<ConstantRange, 4> OpRanges;
291   for (Value *O : I->operands()) {
292     if (Instruction *OI = dyn_cast<Instruction>(O)) {
293       assert(SeenInsts.find(OI) != SeenInsts.end() &&
294              "def not seen before use!");
295       OpRanges.push_back(SeenInsts.find(OI)->second);
296     } else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
297       // Work out if the floating point number can be losslessly represented
298       // as an integer.
299       // APFloat::convertToInteger(&Exact) purports to do what we want, but
300       // the exactness can be too precise. For example, negative zero can
301       // never be exactly converted to an integer.
302       //
303       // Instead, we ask APFloat to round itself to an integral value - this
304       // preserves sign-of-zero - then compare the result with the original.
305       //
306       const APFloat &F = CF->getValueAPF();
307 
308       // First, weed out obviously incorrect values. Non-finite numbers
309       // can't be represented and neither can negative zero, unless
310       // we're in fast math mode.
311       if (!F.isFinite() ||
312           (F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
313            !I->hasNoSignedZeros()))
314         return badRange();
315 
316       APFloat NewF = F;
317       auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
318       if (Res != APFloat::opOK || NewF != F)
319         return badRange();
320 
321       // OK, it's representable. Now get it.
322       APSInt Int(MaxIntegerBW+1, false);
323       bool Exact;
324       CF->getValueAPF().convertToInteger(Int,
325                                          APFloat::rmNearestTiesToEven,
326                                          &Exact);
327       OpRanges.push_back(ConstantRange(Int));
328     } else {
329       llvm_unreachable("Should have already marked this as badRange!");
330     }
331   }
332 
333   // Reduce the operands' ranges to a single range.
334   return Op(OpRanges);
335 }
336 
337 // Walk forwards down the list of seen instructions, so we visit defs before
338 // uses.
339 void Float2IntPass::walkForwards() {
340   for (auto &It : reverse(SeenInsts)) {
341     if (It.second != unknownRange())
342       continue;
343 
344     Instruction *I = It.first;
345     seen(I, calcRange(I));
346   }
347 }
348 
349 // If there is a valid transform to be done, do it.
350 bool Float2IntPass::validateAndTransform() {
351   bool MadeChange = false;
352 
353   // Iterate over every disjoint partition of the def-use graph.
354   for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
355     ConstantRange R(MaxIntegerBW + 1, false);
356     bool Fail = false;
357     Type *ConvertedToTy = nullptr;
358 
359     // For every member of the partition, union all the ranges together.
360     for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
361          MI != ME; ++MI) {
362       Instruction *I = *MI;
363       auto SeenI = SeenInsts.find(I);
364       if (SeenI == SeenInsts.end())
365         continue;
366 
367       R = R.unionWith(SeenI->second);
368       // We need to ensure I has no users that have not been seen.
369       // If it does, transformation would be illegal.
370       //
371       // Don't count the roots, as they terminate the graphs.
372       if (!Roots.contains(I)) {
373         // Set the type of the conversion while we're here.
374         if (!ConvertedToTy)
375           ConvertedToTy = I->getType();
376         for (User *U : I->users()) {
377           Instruction *UI = dyn_cast<Instruction>(U);
378           if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
379             LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
380             Fail = true;
381             break;
382           }
383         }
384       }
385       if (Fail)
386         break;
387     }
388 
389     // If the set was empty, or we failed, or the range is poisonous,
390     // bail out.
391     if (ECs.member_begin(It) == ECs.member_end() || Fail ||
392         R.isFullSet() || R.isSignWrappedSet())
393       continue;
394     assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
395 
396     // The number of bits required is the maximum of the upper and
397     // lower limits, plus one so it can be signed.
398     unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
399                               R.getUpper().getMinSignedBits()) + 1;
400     LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
401 
402     // If we've run off the realms of the exactly representable integers,
403     // the floating point result will differ from an integer approximation.
404 
405     // Do we need more bits than are in the mantissa of the type we converted
406     // to? semanticsPrecision returns the number of mantissa bits plus one
407     // for the sign bit.
408     unsigned MaxRepresentableBits
409       = APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
410     if (MinBW > MaxRepresentableBits) {
411       LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
412       continue;
413     }
414     if (MinBW > 64) {
415       LLVM_DEBUG(
416           dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
417       continue;
418     }
419 
420     // OK, R is known to be representable. Now pick a type for it.
421     // FIXME: Pick the smallest legal type that will fit.
422     Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
423 
424     for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
425          MI != ME; ++MI)
426       convert(*MI, Ty);
427     MadeChange = true;
428   }
429 
430   return MadeChange;
431 }
432 
433 Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
434   if (ConvertedInsts.find(I) != ConvertedInsts.end())
435     // Already converted this instruction.
436     return ConvertedInsts[I];
437 
438   SmallVector<Value*,4> NewOperands;
439   for (Value *V : I->operands()) {
440     // Don't recurse if we're an instruction that terminates the path.
441     if (I->getOpcode() == Instruction::UIToFP ||
442         I->getOpcode() == Instruction::SIToFP) {
443       NewOperands.push_back(V);
444     } else if (Instruction *VI = dyn_cast<Instruction>(V)) {
445       NewOperands.push_back(convert(VI, ToTy));
446     } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
447       APSInt Val(ToTy->getPrimitiveSizeInBits(), /*isUnsigned=*/false);
448       bool Exact;
449       CF->getValueAPF().convertToInteger(Val,
450                                          APFloat::rmNearestTiesToEven,
451                                          &Exact);
452       NewOperands.push_back(ConstantInt::get(ToTy, Val));
453     } else {
454       llvm_unreachable("Unhandled operand type?");
455     }
456   }
457 
458   // Now create a new instruction.
459   IRBuilder<> IRB(I);
460   Value *NewV = nullptr;
461   switch (I->getOpcode()) {
462   default: llvm_unreachable("Unhandled instruction!");
463 
464   case Instruction::FPToUI:
465     NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
466     break;
467 
468   case Instruction::FPToSI:
469     NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
470     break;
471 
472   case Instruction::FCmp: {
473     CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
474     assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
475     NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
476     break;
477   }
478 
479   case Instruction::UIToFP:
480     NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
481     break;
482 
483   case Instruction::SIToFP:
484     NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
485     break;
486 
487   case Instruction::FNeg:
488     NewV = IRB.CreateNeg(NewOperands[0], I->getName());
489     break;
490 
491   case Instruction::FAdd:
492   case Instruction::FSub:
493   case Instruction::FMul:
494     NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
495                            NewOperands[0], NewOperands[1],
496                            I->getName());
497     break;
498   }
499 
500   // If we're a root instruction, RAUW.
501   if (Roots.count(I))
502     I->replaceAllUsesWith(NewV);
503 
504   ConvertedInsts[I] = NewV;
505   return NewV;
506 }
507 
508 // Perform dead code elimination on the instructions we just modified.
509 void Float2IntPass::cleanup() {
510   for (auto &I : reverse(ConvertedInsts))
511     I.first->eraseFromParent();
512 }
513 
514 bool Float2IntPass::runImpl(Function &F, const DominatorTree &DT) {
515   LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
516   // Clear out all state.
517   ECs = EquivalenceClasses<Instruction*>();
518   SeenInsts.clear();
519   ConvertedInsts.clear();
520   Roots.clear();
521 
522   Ctx = &F.getParent()->getContext();
523 
524   findRoots(F, DT);
525 
526   walkBackwards();
527   walkForwards();
528 
529   bool Modified = validateAndTransform();
530   if (Modified)
531     cleanup();
532   return Modified;
533 }
534 
535 namespace llvm {
536 FunctionPass *createFloat2IntPass() { return new Float2IntLegacyPass(); }
537 
538 PreservedAnalyses Float2IntPass::run(Function &F, FunctionAnalysisManager &AM) {
539   const DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
540   if (!runImpl(F, DT))
541     return PreservedAnalyses::all();
542 
543   PreservedAnalyses PA;
544   PA.preserveSet<CFGAnalyses>();
545   return PA;
546 }
547 } // End namespace llvm
548