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