LLVM 24.0.0git
InstCombineCasts.cpp
Go to the documentation of this file.
1//===- InstCombineCasts.cpp -----------------------------------------------===//
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 visit functions for cast operations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SetVector.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DebugInfo.h"
23#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Type.h"
26#include "llvm/IR/Value.h"
29#include <optional>
30
31using namespace llvm;
32using namespace PatternMatch;
33
34#define DEBUG_TYPE "instcombine"
35
37
40 EvaluatedMap &Processed) {
41 // Since we cover transformation of instructions with multiple users, we might
42 // come to the same node via multiple paths. We should not create a
43 // replacement for every single one of them though.
44 if (Value *Result = Processed.lookup(V))
45 return Result;
46
49
50 // Otherwise, it must be an instruction.
52 Instruction *Res = nullptr;
53 unsigned Opc = I->getOpcode();
54 switch (Opc) {
55 case Instruction::Add:
56 case Instruction::Sub:
57 case Instruction::Mul:
58 case Instruction::And:
59 case Instruction::Or:
60 case Instruction::Xor:
61 case Instruction::AShr:
62 case Instruction::LShr:
63 case Instruction::Shl:
64 case Instruction::UDiv:
65 case Instruction::URem: {
66 Value *LHS = EvaluateInDifferentTypeImpl(I->getOperand(0), Ty, isSigned, IC,
67 Processed);
68 Value *RHS = EvaluateInDifferentTypeImpl(I->getOperand(1), Ty, isSigned, IC,
69 Processed);
71 if (Opc == Instruction::LShr || Opc == Instruction::AShr)
72 Res->setIsExact(I->isExact());
73 break;
74 }
75 case Instruction::Trunc:
76 case Instruction::ZExt:
77 case Instruction::SExt:
78 // If the source type of the cast is the type we're trying for then we can
79 // just return the source. There's no need to insert it because it is not
80 // new.
81 if (I->getOperand(0)->getType() == Ty)
82 return I->getOperand(0);
83
84 // Otherwise, must be the same type of cast, so just reinsert a new one.
85 // This also handles the case of zext(trunc(x)) -> zext(x).
86 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
87 Opc == Instruction::SExt);
88 if (auto *Trunc = dyn_cast<TruncInst>(I)) {
89 if (auto *NewTrunc = dyn_cast<TruncInst>(Res)) {
90 if (Trunc->getType()->getScalarSizeInBits() <=
91 Ty->getScalarSizeInBits()) {
92 NewTrunc->setHasNoSignedWrap(Trunc->hasNoSignedWrap());
93 NewTrunc->setHasNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
94 }
95 } else if (auto *NewZExt = dyn_cast<ZExtInst>(Res)) {
96 if (Trunc->hasNoUnsignedWrap())
97 NewZExt->setNonNeg();
98 }
99 }
100 break;
101 case Instruction::Select: {
102 Value *True = EvaluateInDifferentTypeImpl(I->getOperand(1), Ty, isSigned,
103 IC, Processed);
104 Value *False = EvaluateInDifferentTypeImpl(I->getOperand(2), Ty, isSigned,
105 IC, Processed);
106 Res = SelectInst::Create(I->getOperand(0), True, False);
107 break;
108 }
109 case Instruction::PHI: {
110 PHINode *OPN = cast<PHINode>(I);
112 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
114 isSigned, IC, Processed);
115 NPN->addIncoming(V, OPN->getIncomingBlock(i));
116 }
117 Res = NPN;
118 break;
119 }
120 case Instruction::FPToUI:
121 case Instruction::FPToSI:
122 Res = CastInst::Create(static_cast<Instruction::CastOps>(Opc),
123 I->getOperand(0), Ty);
124 break;
125 case Instruction::Call:
127 switch (II->getIntrinsicID()) {
128 default:
129 llvm_unreachable("Unsupported call!");
130 case Intrinsic::vscale: {
132 I->getModule(), Intrinsic::vscale, {Ty});
133 Res = CallInst::Create(Fn->getFunctionType(), Fn);
134 break;
135 }
136 case Intrinsic::umin:
137 case Intrinsic::umax:
138 case Intrinsic::smin:
139 case Intrinsic::smax: {
140 Value *Op0 = EvaluateInDifferentTypeImpl(II->getArgOperand(0), Ty,
141 isSigned, IC, Processed);
142 Value *Op1 = EvaluateInDifferentTypeImpl(II->getArgOperand(1), Ty,
143 isSigned, IC, Processed);
145 I->getModule(), II->getIntrinsicID(), {Ty});
146 Res = CallInst::Create(Fn->getFunctionType(), Fn, {Op0, Op1});
147 break;
148 }
149 case Intrinsic::abs: {
150 Value *Arg = EvaluateInDifferentTypeImpl(II->getArgOperand(0), Ty,
151 isSigned, IC, Processed);
153 I->getModule(), II->getIntrinsicID(), {Ty});
154 Res = CallInst::Create(Fn->getFunctionType(), Fn,
155 {Arg, ConstantInt::getFalse(I->getContext())});
156 break;
157 }
158 }
159 }
160 break;
161 case Instruction::ShuffleVector: {
162 auto *ScalarTy = cast<VectorType>(Ty)->getElementType();
163 auto *VTy = cast<VectorType>(I->getOperand(0)->getType());
164 auto *FixedTy = VectorType::get(ScalarTy, VTy->getElementCount());
165 Value *Op0 = EvaluateInDifferentTypeImpl(I->getOperand(0), FixedTy,
166 isSigned, IC, Processed);
167 Value *Op1 = EvaluateInDifferentTypeImpl(I->getOperand(1), FixedTy,
168 isSigned, IC, Processed);
169 Res = new ShuffleVectorInst(Op0, Op1,
170 cast<ShuffleVectorInst>(I)->getShuffleMask());
171 break;
172 }
173 default:
174 // TODO: Can handle more cases here.
175 llvm_unreachable("Unreachable!");
176 }
177
178 Res->takeName(I);
179 Value *Result = IC.InsertNewInstWith(Res, I->getIterator());
180 // There is no need in keeping track of the old value/new value relationship
181 // when we have only one user, we came have here from that user and no-one
182 // else cares.
183 if (!V->hasOneUse())
184 Processed[V] = Result;
185
186 return Result;
187}
188
189/// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
190/// true for, actually insert the code to evaluate the expression.
192 bool isSigned) {
193 EvaluatedMap Processed;
194 return EvaluateInDifferentTypeImpl(V, Ty, isSigned, *this, Processed);
195}
196
198InstCombinerImpl::isEliminableCastPair(const CastInst *CI1,
199 const CastInst *CI2) {
200 Type *SrcTy = CI1->getSrcTy();
201 Type *MidTy = CI1->getDestTy();
202 Type *DstTy = CI2->getDestTy();
203
204 Instruction::CastOps firstOp = CI1->getOpcode();
205 Instruction::CastOps secondOp = CI2->getOpcode();
206 Type *SrcIntPtrTy =
207 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
208 Type *DstIntPtrTy =
209 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
210 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
211 DstTy, &DL);
212
213 // We don't want to form an inttoptr or ptrtoint that converts to an integer
214 // type that differs from the pointer size.
215 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
216 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
217 Res = 0;
218
219 return Instruction::CastOps(Res);
220}
221
222/// Implement the transforms common to all CastInst visitors.
224 Value *Src = CI.getOperand(0);
225 Type *Ty = CI.getType();
226
227 if (Value *Res =
228 simplifyCastInst(CI.getOpcode(), Src, Ty, SQ.getWithInstruction(&CI)))
229 return replaceInstUsesWith(CI, Res);
230
231 // Try to eliminate a cast of a cast.
232 if (auto *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
233 if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) {
234 // The first cast (CSrc) is eliminable so we need to fix up or replace
235 // the second cast (CI). CSrc will then have a good chance of being dead.
236 auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty);
237 // Point debug users of the dying cast to the new one.
238 if (CSrc->hasOneUse())
239 replaceAllDbgUsesWith(*CSrc, *Res, CI, DT);
240 return Res;
241 }
242 }
243
244 if (auto *Sel = dyn_cast<SelectInst>(Src)) {
245 // We are casting a select. Try to fold the cast into the select if the
246 // select does not have a compare instruction with matching operand types
247 // or the select is likely better done in a narrow type.
248 // Creating a select with operands that are different sizes than its
249 // condition may inhibit other folds and lead to worse codegen.
250 Value *Cond = Sel->getCondition();
252 cast<Instruction>(Cond)->getOperand(0)->getType() != Sel->getType() ||
253 (CI.getOpcode() == Instruction::Trunc &&
254 shouldChangeType(CI.getSrcTy(), CI.getType()))) {
255
256 // If it's a bitcast involving vectors, make sure it has the same number
257 // of elements on both sides.
258 if (CI.getOpcode() != Instruction::BitCast ||
260 if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) {
261 replaceAllDbgUsesWith(*Sel, *NV, CI, DT);
262 return NV;
263 }
264 }
265 }
266 }
267
268 // If we are casting a PHI, then fold the cast into the PHI.
269 if (auto *PN = dyn_cast<PHINode>(Src)) {
270 // Don't do this if it would create a PHI node with an illegal type from a
271 // legal type.
272 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
273 shouldChangeType(CI.getSrcTy(), CI.getType()))
274 if (Instruction *NV = foldOpIntoPhi(CI, PN))
275 return NV;
276 }
277
278 // Canonicalize a unary shuffle after the cast if neither operation changes
279 // the size or element size of the input vector.
280 // TODO: We could allow size-changing ops if that doesn't harm codegen.
281 // cast (shuffle X, Mask) --> shuffle (cast X), Mask
282 Value *X;
283 ArrayRef<int> Mask;
284 if (match(Src, m_OneUse(m_Shuffle(m_Value(X), m_Poison(), m_Mask(Mask))))) {
285 // TODO: Allow scalable vectors?
286 auto *SrcTy = dyn_cast<FixedVectorType>(X->getType());
287 auto *DestTy = dyn_cast<FixedVectorType>(Ty);
288 if (SrcTy && DestTy &&
289 SrcTy->getNumElements() == DestTy->getNumElements() &&
290 SrcTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
291 Value *CastX = Builder.CreateCast(CI.getOpcode(), X, DestTy);
292 return new ShuffleVectorInst(CastX, Mask);
293 }
294 }
295
296 return nullptr;
297}
298
299namespace {
300
301/// Helper class for evaluating whether a value can be computed in a different
302/// type without changing its value. Used by cast simplification transforms.
303class TypeEvaluationHelper {
304public:
305 /// Return true if we can evaluate the specified expression tree as type Ty
306 /// instead of its larger type, and arrive with the same value.
307 /// This is used by code that tries to eliminate truncates.
308 [[nodiscard]] static bool canEvaluateTruncated(Value *V, Type *Ty,
310 Instruction *CxtI);
311
312 /// Determine if the specified value can be computed in the specified wider
313 /// type and produce the same low bits. If not, return false.
314 [[nodiscard]] static bool canEvaluateZExtd(Value *V, Type *Ty,
315 unsigned &BitsToClear,
317 Instruction *CxtI);
318
319 /// Return true if we can take the specified value and return it as type Ty
320 /// without inserting any new casts and without changing the value of the
321 /// common low bits.
322 [[nodiscard]] static bool canEvaluateSExtd(Value *V, Type *Ty);
323
324private:
325 /// Constants and extensions/truncates from the destination type are always
326 /// free to be evaluated in that type.
327 [[nodiscard]] static bool canAlwaysEvaluateInType(Value *V, Type *Ty);
328
329 /// Check if we traversed all the users of the multi-use values we've seen.
330 [[nodiscard]] bool allPendingVisited() const {
331 return llvm::all_of(Pending,
332 [this](Value *V) { return Visited.contains(V); });
333 }
334
335 /// A generic wrapper for canEvaluate* recursions to inject visitation
336 /// tracking and enforce correct multi-use value evaluations.
337 [[nodiscard]] bool
338 canEvaluate(Value *V, Type *Ty,
339 llvm::function_ref<bool(Value *, Type *Type)> Pred) {
340 if (canAlwaysEvaluateInType(V, Ty))
341 return true;
342
343 auto *I = dyn_cast<Instruction>(V);
344
345 if (I == nullptr)
346 return false;
347
348 // We insert false by default to return false when we encounter user loops.
349 const auto [It, Inserted] = Visited.insert({V, false});
350
351 // There are three possible cases for us having information on this value
352 // in the Visited map:
353 // 1. We properly checked it and concluded that we can evaluate it (true)
354 // 2. We properly checked it and concluded that we can't (false)
355 // 3. We started to check it, but during the recursive traversal we came
356 // back to it.
357 //
358 // For cases 1 and 2, we can safely return the stored result. For case 3, we
359 // can potentially have a situation where we can evaluate recursive user
360 // chains, but that can be quite tricky to do properly and isntead, we
361 // return false.
362 //
363 // In any case, we should return whatever was there in the map to begin
364 // with.
365 if (!Inserted)
366 return It->getSecond();
367
368 // We can easily make a decision about single-user values whether they can
369 // be evaluated in a different type or not, we came from that user. This is
370 // not as simple for multi-user values.
371 //
372 // In general, we have the following case (inverted control-flow, users are
373 // at the top):
374 //
375 // Cast %A
376 // ____|
377 // /
378 // %A = Use %B, %C
379 // ________| |
380 // / |
381 // %B = Use %D |
382 // ________| |
383 // / |
384 // %D = Use %C |
385 // ________|___|
386 // /
387 // %C = ...
388 //
389 // In this case, when we check %A, %B and %D, we are confident that we can
390 // make the decision here and now, since we came from their only users.
391 //
392 // For %C, it is harder. We come there twice, and when we come the first
393 // time, it's hard to tell if we will visit the second user (technically
394 // it's not hard, but we might need a lot of repetitive checks with non-zero
395 // cost).
396 //
397 // In the case above, we are allowed to evaluate %C in different type
398 // because all of it users were part of the traversal.
399 //
400 // In the following case, however, we can't make this conclusion:
401 //
402 // Cast %A
403 // ____|
404 // /
405 // %A = Use %B, %C
406 // ________| |
407 // / |
408 // %B = Use %D |
409 // ________| |
410 // / |
411 // %D = Use %C |
412 // | |
413 // foo(%C) | | <- never traversing foo(%C)
414 // ________|___|
415 // /
416 // %C = ...
417 //
418 // In this case, we still can evaluate %C in a different type, but we'd need
419 // to create a copy of the original %C to be used in foo(%C). Such
420 // duplication might be not profitable.
421 //
422 // For this reason, we collect all users of the mult-user values and mark
423 // them as "pending" and defer this decision to the very end. When we are
424 // done and and ready to have a positive verdict, we should double-check all
425 // of the pending users and ensure that we visited them. allPendingVisited
426 // predicate checks exactly that.
427 if (!I->hasOneUse()) {
428 for (Use &U : I->uses()) {
429 // For most instructions, evaluating them in a different type will
430 // change the type of all operands. This is not the case for select
431 // conditions. Make sure we don't retain an extra use via the select
432 // condition.
433 if (isa<SelectInst>(U.getUser()) && U.getOperandNo() == 0)
434 return false;
435
436 Pending.push_back(U.getUser());
437 }
438 }
439
440 const bool Result = Pred(V, Ty);
441 // We have to set result this way and not via It because Pred is recursive
442 // and it is very likely that we grew Visited and invalidated It.
443 Visited[V] = Result;
444 return Result;
445 }
446
447 /// Filter out values that we can not evaluate in the destination type for
448 /// free.
449 [[nodiscard]] bool canNotEvaluateInType(Value *V, Type *Ty);
450
451 [[nodiscard]] bool canEvaluateTruncatedImpl(Value *V, Type *Ty,
452 InstCombinerImpl &IC,
453 Instruction *CxtI);
454 [[nodiscard]] bool canEvaluateTruncatedPred(Value *V, Type *Ty,
455 InstCombinerImpl &IC,
456 Instruction *CxtI);
457 [[nodiscard]] bool canEvaluateZExtdImpl(Value *V, Type *Ty,
458 unsigned &BitsToClear,
459 InstCombinerImpl &IC,
460 Instruction *CxtI);
461 [[nodiscard]] bool canEvaluateSExtdImpl(Value *V, Type *Ty);
462 [[nodiscard]] bool canEvaluateSExtdPred(Value *V, Type *Ty);
463
464 /// A bookkeeping map to memorize an already made decision for a traversed
465 /// value.
466 SmallDenseMap<Value *, bool, 8> Visited;
467
468 /// A list of pending values to check in the end.
469 SmallVector<Value *, 8> Pending;
470};
471
472} // anonymous namespace
473
474/// Constants and extensions/truncates from the destination type are always
475/// free to be evaluated in that type. This is a helper for canEvaluate*.
476bool TypeEvaluationHelper::canAlwaysEvaluateInType(Value *V, Type *Ty) {
477 if (isa<Constant>(V))
478 return match(V, m_ImmConstant());
479
480 Value *X;
481 if (match(V, m_ZExtOrSExt(m_SpecificType(Ty, X))) ||
482 match(V, m_Trunc(m_SpecificType(Ty, X))))
483 return true;
484
485 return false;
486}
487
488/// Filter out values that we can not evaluate in the destination type for free.
489/// This is a helper for canEvaluate*.
490bool TypeEvaluationHelper::canNotEvaluateInType(Value *V, Type *Ty) {
491 if (!isa<Instruction>(V))
492 return true;
493 // We don't extend or shrink something that has multiple uses -- doing so
494 // would require duplicating the instruction which isn't profitable.
495 if (!V->hasOneUse())
496 return true;
497
498 return false;
499}
500
501/// Return true if we can evaluate the specified expression tree as type Ty
502/// instead of its larger type, and arrive with the same value.
503/// This is used by code that tries to eliminate truncates.
504///
505/// Ty will always be a type smaller than V. We should return true if trunc(V)
506/// can be computed by computing V in the smaller type. If V is an instruction,
507/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
508/// makes sense if x and y can be efficiently truncated.
509///
510/// This function works on both vectors and scalars.
511///
512bool TypeEvaluationHelper::canEvaluateTruncated(Value *V, Type *Ty,
514 Instruction *CxtI) {
515 TypeEvaluationHelper TYH;
516 return TYH.canEvaluateTruncatedImpl(V, Ty, IC, CxtI) &&
517 // We need to check whether we visited all users of multi-user values,
518 // and we have to do it at the very end, outside of the recursion.
519 TYH.allPendingVisited();
520}
521
522bool TypeEvaluationHelper::canEvaluateTruncatedImpl(Value *V, Type *Ty,
524 Instruction *CxtI) {
525 return canEvaluate(V, Ty, [this, &IC, CxtI](Value *V, Type *Ty) {
526 return canEvaluateTruncatedPred(V, Ty, IC, CxtI);
527 });
528}
529
530bool TypeEvaluationHelper::canEvaluateTruncatedPred(Value *V, Type *Ty,
532 Instruction *CxtI) {
533 auto *I = cast<Instruction>(V);
534 Type *OrigTy = V->getType();
535 switch (I->getOpcode()) {
536 case Instruction::Add:
537 case Instruction::Sub:
538 case Instruction::Mul:
539 case Instruction::And:
540 case Instruction::Or:
541 case Instruction::Xor:
542 // These operators can all arbitrarily be extended or truncated.
543 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
544 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
545
546 case Instruction::UDiv:
547 case Instruction::URem: {
548 // UDiv and URem can be truncated if all the truncated bits are zero.
549 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
550 uint32_t BitWidth = Ty->getScalarSizeInBits();
551 assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!");
552 APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
553 // Do not preserve the original context instruction. Simplifying div/rem
554 // based on later context may introduce a trap.
555 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, I) &&
556 IC.MaskedValueIsZero(I->getOperand(1), Mask, I)) {
557 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
558 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
559 }
560 break;
561 }
562 case Instruction::Shl: {
563 // If we are truncating the result of this SHL, and if it's a shift of an
564 // inrange amount, we can always perform a SHL in a smaller type.
565 uint32_t BitWidth = Ty->getScalarSizeInBits();
566 KnownBits AmtKnownBits =
567 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
568 if (AmtKnownBits.getMaxValue().ult(BitWidth))
569 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
570 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
571 break;
572 }
573 case Instruction::LShr: {
574 // If this is a truncate of a logical shr, we can truncate it to a smaller
575 // lshr iff we know that the bits we would otherwise be shifting in are
576 // already zeros.
577 // TODO: It is enough to check that the bits we would be shifting in are
578 // zero - use AmtKnownBits.getMaxValue().
579 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
580 uint32_t BitWidth = Ty->getScalarSizeInBits();
581 KnownBits AmtKnownBits = IC.computeKnownBits(I->getOperand(1), CxtI);
582 APInt MaxShiftAmt = AmtKnownBits.getMaxValue();
583 APInt ShiftedBits = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
584 if (MaxShiftAmt.ult(BitWidth)) {
585 // If the only user is a trunc then we can narrow the shift if any new
586 // MSBs are not going to be used.
587 if (auto *Trunc = dyn_cast<TruncInst>(V->user_back())) {
588 auto DemandedBits = Trunc->getType()->getScalarSizeInBits();
589 if ((MaxShiftAmt + DemandedBits).ule(BitWidth))
590 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
591 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
592 }
593 if (IC.MaskedValueIsZero(I->getOperand(0), ShiftedBits, CxtI))
594 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
595 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
596 }
597 break;
598 }
599 case Instruction::AShr: {
600 // If this is a truncate of an arithmetic shr, we can truncate it to a
601 // smaller ashr iff we know that all the bits from the sign bit of the
602 // original type and the sign bit of the truncate type are similar.
603 // TODO: It is enough to check that the bits we would be shifting in are
604 // similar to sign bit of the truncate type.
605 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
606 uint32_t BitWidth = Ty->getScalarSizeInBits();
607 KnownBits AmtKnownBits =
608 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
609 unsigned ShiftedBits = OrigBitWidth - BitWidth;
610 if (AmtKnownBits.getMaxValue().ult(BitWidth) &&
611 ShiftedBits < IC.ComputeNumSignBits(I->getOperand(0), CxtI))
612 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
613 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
614 break;
615 }
616 case Instruction::Trunc:
617 // trunc(trunc(x)) -> trunc(x)
618 return true;
619 case Instruction::ZExt:
620 case Instruction::SExt:
621 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
622 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
623 return true;
624 case Instruction::Select: {
626 return canEvaluateTruncatedImpl(SI->getTrueValue(), Ty, IC, CxtI) &&
627 canEvaluateTruncatedImpl(SI->getFalseValue(), Ty, IC, CxtI);
628 }
629 case Instruction::PHI: {
630 // We can change a phi if we can change all operands. Note that we never
631 // get into trouble with cyclic PHIs here because canEvaluate handles use
632 // chain loops.
633 PHINode *PN = cast<PHINode>(I);
634 return llvm::all_of(
635 PN->incoming_values(), [this, Ty, &IC, CxtI](Value *IncValue) {
636 return canEvaluateTruncatedImpl(IncValue, Ty, IC, CxtI);
637 });
638 }
639 case Instruction::FPToUI:
640 case Instruction::FPToSI: {
641 // If the integer type can hold the max FP value, it is safe to cast
642 // directly to that type. Otherwise, we may create poison via overflow
643 // that did not exist in the original code.
644 Type *InputTy = I->getOperand(0)->getType()->getScalarType();
645 const fltSemantics &Semantics = InputTy->getFltSemantics();
646 uint32_t MinBitWidth = APFloatBase::semanticsIntSizeInBits(
647 Semantics, I->getOpcode() == Instruction::FPToSI);
648 return Ty->getScalarSizeInBits() >= MinBitWidth;
649 }
650 case Instruction::ShuffleVector:
651 return canEvaluateTruncatedImpl(I->getOperand(0), Ty, IC, CxtI) &&
652 canEvaluateTruncatedImpl(I->getOperand(1), Ty, IC, CxtI);
653
654 case Instruction::Call: {
655 Value *AbsOp;
657 if (IC.ComputeMaxSignificantBits(AbsOp, CxtI) > Ty->getScalarSizeInBits())
658 return false;
659 return canEvaluateTruncatedImpl(AbsOp, Ty, IC, CxtI);
660 }
661 auto *MM = dyn_cast<MinMaxIntrinsic>(I);
662 if (!MM)
663 return false;
664 // The min/max can be performed in the narrow type when each operand has
665 // zero high bits (for umin/umax) or enough sign bits (for smin/smax).
666 Value *Op0 = MM->getLHS();
667 Value *Op1 = MM->getRHS();
668 uint32_t BitWidth = Ty->getScalarSizeInBits();
669 if (MM->isSigned()) {
670 if (IC.ComputeMaxSignificantBits(Op0, CxtI) > BitWidth ||
671 IC.ComputeMaxSignificantBits(Op1, CxtI) > BitWidth)
672 break;
673 } else {
674 APInt Mask =
676 if (!IC.MaskedValueIsZero(Op0, Mask, CxtI) ||
677 !IC.MaskedValueIsZero(Op1, Mask, CxtI))
678 break;
679 }
680 return canEvaluateTruncatedImpl(Op0, Ty, IC, CxtI) &&
681 canEvaluateTruncatedImpl(Op1, Ty, IC, CxtI);
682 }
683 default:
684 // TODO: Can handle more cases here.
685 break;
686 }
687
688 return false;
689}
690
691/// Given a vector that is bitcast to an integer, optionally logically
692/// right-shifted, and truncated, convert it to an extractelement.
693/// Example (big endian):
694/// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
695/// --->
696/// extractelement <4 x i32> %X, 1
698 InstCombinerImpl &IC) {
699 Value *TruncOp = Trunc.getOperand(0);
700 Type *DestType = Trunc.getType();
701 if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
702 return nullptr;
703
704 Value *VecInput = nullptr;
705 ConstantInt *ShiftVal = nullptr;
706 if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
707 m_LShr(m_BitCast(m_Value(VecInput)),
708 m_ConstantInt(ShiftVal)))) ||
709 !isa<VectorType>(VecInput->getType()))
710 return nullptr;
711
712 VectorType *VecType = cast<VectorType>(VecInput->getType());
713 unsigned VecWidth = VecType->getPrimitiveSizeInBits();
714 unsigned DestWidth = DestType->getPrimitiveSizeInBits();
715 unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
716
717 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
718 return nullptr;
719
720 // If the element type of the vector doesn't match the result type,
721 // bitcast it to a vector type that we can extract from.
722 unsigned NumVecElts = VecWidth / DestWidth;
723 if (VecType->getElementType() != DestType) {
724 VecType = FixedVectorType::get(DestType, NumVecElts);
725 VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc");
726 }
727
728 unsigned Elt = ShiftAmount / DestWidth;
729 if (IC.getDataLayout().isBigEndian())
730 Elt = NumVecElts - 1 - Elt;
731
732 return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt));
733}
734
735/// Whenever an element is extracted from a vector, optionally shifted down, and
736/// then truncated, canonicalize by converting it to a bitcast followed by an
737/// extractelement.
738///
739/// Examples (little endian):
740/// trunc (extractelement <4 x i64> %X, 0) to i32
741/// --->
742/// extractelement <8 x i32> (bitcast <4 x i64> %X to <8 x i32>), i32 0
743///
744/// trunc (lshr (extractelement <4 x i32> %X, 0), 8) to i8
745/// --->
746/// extractelement <16 x i8> (bitcast <4 x i32> %X to <16 x i8>), i32 1
748 InstCombinerImpl &IC) {
749 Value *Src = Trunc.getOperand(0);
750 Type *SrcType = Src->getType();
751 Type *DstType = Trunc.getType();
752
753 // Only attempt this if we have simple aliasing of the vector elements.
754 // A badly fit destination size would result in an invalid cast.
755 unsigned SrcBits = SrcType->getScalarSizeInBits();
756 unsigned DstBits = DstType->getScalarSizeInBits();
757 unsigned TruncRatio = SrcBits / DstBits;
758 if ((SrcBits % DstBits) != 0)
759 return nullptr;
760
761 Value *VecOp;
762 ConstantInt *Cst;
763 const APInt *ShiftAmount = nullptr;
764 if (!match(Src, m_OneUse(m_ExtractElt(m_Value(VecOp), m_ConstantInt(Cst)))) &&
765 !match(Src,
767 m_APInt(ShiftAmount)))))
768 return nullptr;
769
770 auto *VecOpTy = cast<VectorType>(VecOp->getType());
771 auto VecElts = VecOpTy->getElementCount();
772
773 uint64_t BitCastNumElts = VecElts.getKnownMinValue() * TruncRatio;
774 // Make sure we don't overflow in the calculation of the new index.
775 // (VecOpIdx + 1) * TruncRatio should not overflow.
776 if (Cst->uge(std::numeric_limits<uint64_t>::max() / TruncRatio))
777 return nullptr;
778 uint64_t VecOpIdx = Cst->getZExtValue();
779 uint64_t NewIdx = IC.getDataLayout().isBigEndian()
780 ? (VecOpIdx + 1) * TruncRatio - 1
781 : VecOpIdx * TruncRatio;
782
783 // Adjust index by the whole number of truncated elements.
784 if (ShiftAmount) {
785 // Check shift amount is in range and shifts a whole number of truncated
786 // elements.
787 if (ShiftAmount->uge(SrcBits) || ShiftAmount->urem(DstBits) != 0)
788 return nullptr;
789
790 uint64_t IdxOfs = ShiftAmount->udiv(DstBits).getZExtValue();
791 // IdxOfs is guaranteed to be less than TruncRatio, so we won't overflow in
792 // the adjustment.
793 assert(IdxOfs < TruncRatio &&
794 "IdxOfs is expected to be less than TruncRatio.");
795 NewIdx = IC.getDataLayout().isBigEndian() ? (NewIdx - IdxOfs)
796 : (NewIdx + IdxOfs);
797 }
798
799 assert(BitCastNumElts <= std::numeric_limits<uint32_t>::max() &&
800 "overflow 32-bits");
801
802 auto *BitCastTo =
803 VectorType::get(DstType, BitCastNumElts, VecElts.isScalable());
804 Value *BitCast = IC.Builder.CreateBitCast(VecOp, BitCastTo);
805 return ExtractElementInst::Create(BitCast, IC.Builder.getInt64(NewIdx));
806}
807
808/// Funnel/Rotate left/right may occur in a wider type than necessary because of
809/// type promotion rules. Try to narrow the inputs and convert to funnel shift.
810Instruction *InstCombinerImpl::narrowFunnelShift(TruncInst &Trunc) {
811 assert((isa<VectorType>(Trunc.getSrcTy()) ||
812 shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) &&
813 "Don't narrow to an illegal scalar type");
814
815 // Bail out on strange types. It is possible to handle some of these patterns
816 // even with non-power-of-2 sizes, but it is not a likely scenario.
817 Type *DestTy = Trunc.getType();
818 unsigned NarrowWidth = DestTy->getScalarSizeInBits();
819 unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits();
820 if (!isPowerOf2_32(NarrowWidth))
821 return nullptr;
822
823 // First, find an or'd pair of opposite shifts:
824 // trunc (or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1))
825 BinaryOperator *Or0, *Or1;
826 if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
827 return nullptr;
828
829 Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
830 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
831 !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
832 Or0->getOpcode() == Or1->getOpcode())
833 return nullptr;
834
835 // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
836 if (Or0->getOpcode() == BinaryOperator::LShr) {
837 std::swap(Or0, Or1);
838 std::swap(ShVal0, ShVal1);
839 std::swap(ShAmt0, ShAmt1);
840 }
841 assert(Or0->getOpcode() == BinaryOperator::Shl &&
842 Or1->getOpcode() == BinaryOperator::LShr &&
843 "Illegal or(shift,shift) pair");
844
845 // Match the shift amount operands for a funnel/rotate pattern. This always
846 // matches a subtraction on the R operand.
847 auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
848 // The shift amounts may add up to the narrow bit width:
849 // (shl ShVal0, L) | (lshr ShVal1, Width - L)
850 // If this is a funnel shift (different operands are shifted), then the
851 // shift amount can not over-shift (create poison) in the narrow type.
852 unsigned MaxShiftAmountWidth = Log2_32(NarrowWidth);
853 APInt HiBitMask = ~APInt::getLowBitsSet(WideWidth, MaxShiftAmountWidth);
854 if (ShVal0 == ShVal1 || MaskedValueIsZero(L, HiBitMask))
855 if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L)))))
856 return L;
857
858 // The following patterns currently only work for rotation patterns.
859 // TODO: Add more general funnel-shift compatible patterns.
860 if (ShVal0 != ShVal1)
861 return nullptr;
862
863 // The shift amount may be masked with negation:
864 // (shl ShVal0, (X & (Width - 1))) | (lshr ShVal1, ((-X) & (Width - 1)))
865 Value *X;
866 unsigned Mask = Width - 1;
867 if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
869 return X;
870
871 // Same as above, but the shift amount may be extended after masking:
872 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
874 return X;
875
876 return nullptr;
877 };
878
879 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth);
880 bool IsFshl = true; // Sub on LSHR.
881 if (!ShAmt) {
882 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth);
883 IsFshl = false; // Sub on SHL.
884 }
885 if (!ShAmt)
886 return nullptr;
887
888 // The right-shifted value must have high zeros in the wide type (for example
889 // from 'zext', 'and' or 'shift'). High bits of the left-shifted value are
890 // truncated, so those do not matter.
891 APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth);
892 if (!MaskedValueIsZero(ShVal1, HiBitMask, &Trunc))
893 return nullptr;
894
895 // Adjust the width of ShAmt for narrowed funnel shift operation:
896 // - Zero-extend if ShAmt is narrower than the destination type.
897 // - Truncate if ShAmt is wider, discarding non-significant high-order bits.
898 // This prepares ShAmt for llvm.fshl.i8(trunc(ShVal), trunc(ShVal),
899 // zext/trunc(ShAmt)).
900 Value *NarrowShAmt = Builder.CreateZExtOrTrunc(ShAmt, DestTy);
901
902 Value *X, *Y;
903 X = Y = Builder.CreateTrunc(ShVal0, DestTy);
904 if (ShVal0 != ShVal1)
905 Y = Builder.CreateTrunc(ShVal1, DestTy);
906 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
907 Function *F =
908 Intrinsic::getOrInsertDeclaration(Trunc.getModule(), IID, DestTy);
909 return CallInst::Create(F, {X, Y, NarrowShAmt});
910}
911
912/// Try to narrow the width of math or bitwise logic instructions by pulling a
913/// truncate ahead of binary operators.
914Instruction *InstCombinerImpl::narrowBinOp(TruncInst &Trunc) {
915 Type *SrcTy = Trunc.getSrcTy();
916 Type *DestTy = Trunc.getType();
917 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
918 unsigned DestWidth = DestTy->getScalarSizeInBits();
919
920 if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy))
921 return nullptr;
922
923 BinaryOperator *BinOp;
924 if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp))))
925 return nullptr;
926
927 Value *BinOp0 = BinOp->getOperand(0);
928 Value *BinOp1 = BinOp->getOperand(1);
929 switch (BinOp->getOpcode()) {
930 case Instruction::And:
931 case Instruction::Or:
932 case Instruction::Xor:
933 case Instruction::Add:
934 case Instruction::Sub:
935 case Instruction::Mul: {
936 Constant *C;
937 if (match(BinOp0, m_Constant(C))) {
938 // trunc (binop C, X) --> binop (trunc C', X)
939 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
940 Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
941 return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX);
942 }
943 if (match(BinOp1, m_Constant(C))) {
944 // trunc (binop X, C) --> binop (trunc X, C')
945 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
946 Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
947 return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC);
948 }
949 Value *X;
950 if (match(BinOp0, m_ZExtOrSExt(m_SpecificType(DestTy, X)))) {
951 // trunc (binop (ext X), Y) --> binop X, (trunc Y)
952 Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
953 return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1);
954 }
955 if (match(BinOp1, m_ZExtOrSExt(m_SpecificType(DestTy, X)))) {
956 // trunc (binop Y, (ext X)) --> binop (trunc Y), X
957 Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
958 return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X);
959 }
960 break;
961 }
962 case Instruction::LShr:
963 case Instruction::AShr: {
964 // trunc (*shr (trunc A), C) --> trunc(*shr A, C)
965 Value *A;
966 Constant *C;
967 if (match(BinOp0, m_Trunc(m_Value(A))) && match(BinOp1, m_Constant(C))) {
968 unsigned MaxShiftAmt = SrcWidth - DestWidth;
969 // If the shift is small enough, all zero/sign bits created by the shift
970 // are removed by the trunc.
972 APInt(SrcWidth, MaxShiftAmt)))) {
973 auto *OldShift = cast<Instruction>(Trunc.getOperand(0));
974 bool IsExact = OldShift->isExact();
975 if (Constant *ShAmt = ConstantFoldIntegerCast(C, A->getType(),
976 /*IsSigned*/ true, DL)) {
977 ShAmt = Constant::mergeUndefsWith(ShAmt, C);
978 Value *Shift =
979 OldShift->getOpcode() == Instruction::AShr
980 ? Builder.CreateAShr(A, ShAmt, OldShift->getName(), IsExact)
981 : Builder.CreateLShr(A, ShAmt, OldShift->getName(), IsExact);
982 return CastInst::CreateTruncOrBitCast(Shift, DestTy);
983 }
984 }
985 }
986 break;
987 }
988 default: break;
989 }
990
991 if (Instruction *NarrowOr = narrowFunnelShift(Trunc))
992 return NarrowOr;
993
994 return nullptr;
995}
996
997/// Try to narrow the width of a splat shuffle. This could be generalized to any
998/// shuffle with a constant operand, but we limit the transform to avoid
999/// creating a shuffle type that targets may not be able to lower effectively.
1001 InstCombiner::BuilderTy &Builder) {
1002 Value *Shuf = Trunc.getOperand(0), *ShufVec;
1003 ArrayRef<int> SplatMask;
1004 if (match(Shuf, m_OneUse(m_Shuffle(m_Value(ShufVec), m_Poison(),
1005 m_Mask(SplatMask)))) &&
1006 match(SplatMask, m_SplatMask()) &&
1008 cast<VectorType>(Shuf->getType())->getElementCount(),
1009 cast<VectorType>(ShufVec->getType())->getElementCount())) {
1010 // trunc (shuf X, poison, SplatMask) --> shuf (trunc X), poison, SplatMask
1011 Type *NewTruncTy =
1012 ShufVec->getType()->getWithNewType(Trunc.getType()->getScalarType());
1013 Value *NarrowOp = Builder.CreateTrunc(ShufVec, NewTruncTy);
1014 return new ShuffleVectorInst(NarrowOp, SplatMask);
1015 }
1016
1017 return nullptr;
1018}
1019
1020/// Try to narrow the width of an insert element. This could be generalized for
1021/// any vector constant, but we limit the transform to insertion into poison to
1022/// avoid potential backend problems from unsupported insertion widths. This
1023/// could also be extended to handle the case of inserting a scalar constant
1024/// into a vector variable.
1026 InstCombiner::BuilderTy &Builder) {
1027 Instruction::CastOps Opcode = Trunc.getOpcode();
1028 assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
1029 "Unexpected instruction for shrinking");
1030
1031 Value *Elt, *Index;
1032 if (match(Trunc.getOperand(0),
1033 m_OneUse(m_InsertElt(m_Poison(), m_Value(Elt), m_Value(Index))))) {
1034 // trunc (inselt poison, X, Index) --> inselt poison, (trunc X), Index
1035 // fptrunc (inselt poison, X, Index) --> inselt poison, (fptrunc X), Index
1036 auto *NarrowPoison = PoisonValue::get(Trunc.getType());
1037 Value *NarrowOp =
1038 Builder.CreateCast(Opcode, Elt, Trunc.getType()->getScalarType());
1039 return InsertElementInst::Create(NarrowPoison, NarrowOp, Index);
1040 }
1041
1042 return nullptr;
1043}
1044
1046 if (Instruction *Result = commonCastTransforms(Trunc))
1047 return Result;
1048
1049 Value *Src = Trunc.getOperand(0);
1050 Type *DestTy = Trunc.getType(), *SrcTy = Src->getType();
1051 unsigned DestWidth = DestTy->getScalarSizeInBits();
1052 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
1053
1054 // Attempt to truncate the entire input expression tree to the destination
1055 // type. Only do this if the dest type is a simple type, don't convert the
1056 // expression tree to something weird like i93 unless the source is also
1057 // strange.
1058 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
1059 TypeEvaluationHelper::canEvaluateTruncated(Src, DestTy, *this, &Trunc)) {
1060
1061 // If this cast is a truncate, evaluting in a different type always
1062 // eliminates the cast, so it is always a win.
1063 LLVM_DEBUG(
1064 dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1065 " to avoid cast: "
1066 << Trunc << '\n');
1067 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
1068 assert(Res->getType() == DestTy);
1069 return replaceInstUsesWith(Trunc, Res);
1070 }
1071
1072 // For integer types, check if we can shorten the entire input expression to
1073 // DestWidth * 2, which won't allow removing the truncate, but reducing the
1074 // width may enable further optimizations, e.g. allowing for larger
1075 // vectorization factors.
1076 if (auto *DestITy = dyn_cast<IntegerType>(DestTy)) {
1077 if (DestWidth * 2 < SrcWidth) {
1078 auto *NewDestTy = DestITy->getExtendedType();
1079 if (shouldChangeType(SrcTy, NewDestTy) &&
1080 TypeEvaluationHelper::canEvaluateTruncated(Src, NewDestTy, *this,
1081 &Trunc)) {
1082 LLVM_DEBUG(
1083 dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1084 " to reduce the width of operand of"
1085 << Trunc << '\n');
1086 Value *Res = EvaluateInDifferentType(Src, NewDestTy, false);
1087 return new TruncInst(Res, DestTy);
1088 }
1089 }
1090 }
1091 Value *X;
1092 if (DestWidth == 1 &&
1093 (Trunc.hasNoUnsignedWrap() || Trunc.hasNoSignedWrap()) &&
1094 match(Src, m_Exact(m_Shr(m_Value(X), m_Value()))))
1096
1097 // See if we can simplify any instructions used by the input whose sole
1098 // purpose is to compute bits we don't care about.
1100 return &Trunc;
1101
1102 if (DestWidth == 1) {
1103 Value *Zero = Constant::getNullValue(SrcTy);
1104
1105 const APInt *C1;
1106 Constant *C2;
1107 if (match(Src, m_OneUse(m_Shr(m_Shl(m_Power2(C1), m_Value(X)),
1108 m_ImmConstant(C2))))) {
1109 // trunc ((C1 << X) >> C2) to i1 --> X == (C2-cttz(C1)), where C1 is pow2
1110 Constant *Log2C1 = ConstantInt::get(SrcTy, C1->exactLogBase2());
1111 Constant *CmpC = ConstantExpr::getSub(C2, Log2C1);
1112 return new ICmpInst(ICmpInst::ICMP_EQ, X, CmpC);
1113 }
1114
1115 if (match(Src, m_Shr(m_Value(X), m_SpecificInt(SrcWidth - 1)))) {
1116 // trunc (ashr X, BW-1) to i1 --> icmp slt X, 0
1117 // trunc (lshr X, BW-1) to i1 --> icmp slt X, 0
1118 return new ICmpInst(ICmpInst::ICMP_SLT, X, Zero);
1119 }
1120
1121 Constant *C;
1122 if (match(Src, m_OneUse(m_LShr(m_Value(X), m_ImmConstant(C))))) {
1123 // trunc (lshr X, C) to i1 --> icmp ne (and X, C'), 0
1124 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
1125 Value *MaskC = Builder.CreateShl(One, C);
1126 Value *And = Builder.CreateAnd(X, MaskC);
1127 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
1128 }
1130 m_Deferred(X))))) {
1131 // trunc (or (lshr X, C), X) to i1 --> icmp ne (and X, C'), 0
1132 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
1133 Value *MaskC = Builder.CreateShl(One, C);
1134 Value *And = Builder.CreateAnd(X, Builder.CreateOr(MaskC, One));
1135 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
1136 }
1137
1138 {
1139 const APInt *C;
1140 if (match(Src, m_Shl(m_APInt(C), m_Value(X))) && (*C)[0] == 1) {
1141 // trunc (C << X) to i1 --> X == 0, where C is odd
1142 return new ICmpInst(ICmpInst::Predicate::ICMP_EQ, X, Zero);
1143 }
1144 }
1145
1146 if (Trunc.hasNoUnsignedWrap() || Trunc.hasNoSignedWrap()) {
1147 Value *X, *Y;
1148 if (match(Src, m_Xor(m_Value(X), m_Value(Y))))
1149 return new ICmpInst(ICmpInst::ICMP_NE, X, Y);
1150 }
1151
1152 if (match(Src,
1154 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1156 }
1157
1158 Value *A, *B;
1159 Constant *C;
1160
1161 // trunc(u/smin(zext(a) + zext(b), MAX)) --> uadd.sat(a, b)
1162 if (match(Src, m_OneUse(m_CombineOr(
1164 m_ZExt(m_SpecificType(DestTy, B)))),
1165 m_SpecificInt(APInt::getMaxValue(DestWidth))),
1167 m_ZExt(m_SpecificType(DestTy, B)))),
1168 m_SpecificInt(APInt::getMaxValue(DestWidth))))))) {
1169 return replaceInstUsesWith(
1170 Trunc, Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, A, B));
1171 }
1172
1173 // trunc(smax(zext(a) - zext(b), 0)) --> usub.sat(a, b)
1174 if (match(Src,
1176 m_ZExt(m_SpecificType(DestTy, B)))),
1177 m_Zero())))) {
1178 return replaceInstUsesWith(
1179 Trunc, Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B));
1180 }
1181
1182 if (match(Src, m_LShr(m_SExt(m_Value(A)), m_Constant(C)))) {
1183 unsigned AWidth = A->getType()->getScalarSizeInBits();
1184 unsigned MaxShiftAmt = SrcWidth - std::max(DestWidth, AWidth);
1185 auto *OldSh = cast<Instruction>(Src);
1186 bool IsExact = OldSh->isExact();
1187
1188 // If the shift is small enough, all zero bits created by the shift are
1189 // removed by the trunc.
1191 APInt(SrcWidth, MaxShiftAmt)))) {
1192 auto GetNewShAmt = [&](unsigned Width) {
1193 Constant *MaxAmt = ConstantInt::get(SrcTy, Width - 1, false);
1194 Constant *Cmp =
1196 Constant *ShAmt = ConstantFoldSelectInstruction(Cmp, C, MaxAmt);
1197 return ConstantFoldCastOperand(Instruction::Trunc, ShAmt, A->getType(),
1198 DL);
1199 };
1200
1201 // trunc (lshr (sext A), C) --> ashr A, C
1202 if (A->getType() == DestTy) {
1203 Constant *ShAmt = GetNewShAmt(DestWidth);
1204 ShAmt = Constant::mergeUndefsWith(ShAmt, C);
1205 return IsExact ? BinaryOperator::CreateExactAShr(A, ShAmt)
1206 : BinaryOperator::CreateAShr(A, ShAmt);
1207 }
1208 // The types are mismatched, so create a cast after shifting:
1209 // trunc (lshr (sext A), C) --> sext/trunc (ashr A, C)
1210 if (Src->hasOneUse()) {
1211 Constant *ShAmt = GetNewShAmt(AWidth);
1212 Value *Shift = Builder.CreateAShr(A, ShAmt, "", IsExact);
1213 return CastInst::CreateIntegerCast(Shift, DestTy, true);
1214 }
1215 }
1216 // TODO: Mask high bits with 'and'.
1217 }
1218
1219 if (Instruction *I = narrowBinOp(Trunc))
1220 return I;
1221
1222 if (Instruction *I = shrinkSplatShuffle(Trunc, Builder))
1223 return I;
1224
1225 if (Instruction *I = shrinkInsertElt(Trunc, Builder))
1226 return I;
1227
1228 if (Src->hasOneUse() &&
1229 (isa<VectorType>(SrcTy) || shouldChangeType(SrcTy, DestTy))) {
1230 // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the
1231 // dest type is native and cst < dest size.
1232 if (match(Src, m_Shl(m_Value(A), m_Constant(C))) &&
1233 !match(A, m_Shr(m_Value(), m_Constant()))) {
1234 // Skip shifts of shift by constants. It undoes a combine in
1235 // FoldShiftByConstant and is the extend in reg pattern.
1236 APInt Threshold = APInt(C->getType()->getScalarSizeInBits(), DestWidth);
1237 if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold))) {
1238 // If neither the wide shift nor the truncate wrap, propagate the wrap
1239 // flags on the new truncate.
1240 auto *WideShl = cast<OverflowingBinaryOperator>(Src);
1241 bool NUW = Trunc.hasNoUnsignedWrap() && WideShl->hasNoUnsignedWrap();
1242 bool NSW = Trunc.hasNoSignedWrap() && WideShl->hasNoSignedWrap();
1243 Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr",
1244 /*IsNUW=*/NUW, /*IsNSW=*/NSW);
1245 // The original flags from the truncate can be propagated directly to
1246 // the shift.
1247 auto *NewShl = BinaryOperator::Create(
1248 Instruction::Shl, NewTrunc, ConstantExpr::getTrunc(C, DestTy));
1249 NewShl->setHasNoUnsignedWrap(Trunc.hasNoUnsignedWrap());
1250 NewShl->setHasNoSignedWrap(Trunc.hasNoSignedWrap());
1251 return NewShl;
1252 }
1253 }
1254 }
1255
1256 // trunc (select(icmp_ult(A, DestTy_umax+1), A, sext(icmp_sgt(A, 0)))) -->
1257 // trunc (smin(smax(0, A), DestTy_umax))
1258 if (SrcTy->isIntegerTy() && isPowerOf2_64(SrcTy->getPrimitiveSizeInBits()) &&
1260 match(Src, m_OneUse(m_Select(
1262 m_Constant(C))),
1263 m_Deferred(A),
1265 ICmpInst::ICMP_SGT, m_Deferred(A), m_Zero())))))))) {
1266 APInt UpperBound = C->getUniqueInteger();
1267 APInt TruncatedMax = APInt::getAllOnes(DestTy->getIntegerBitWidth());
1268 TruncatedMax = TruncatedMax.zext(UpperBound.getBitWidth());
1269 if (!UpperBound.isZero() && UpperBound - 1 == TruncatedMax) {
1270 Value *SMax = Builder.CreateIntrinsic(Intrinsic::smax, {SrcTy},
1271 {ConstantInt::get(SrcTy, 0), A});
1272 Value *SMin = Builder.CreateIntrinsic(
1273 Intrinsic::smin, {SrcTy},
1274 {SMax, ConstantInt::get(SrcTy, TruncatedMax)});
1275 return new TruncInst(SMin, DestTy);
1276 }
1277 }
1278
1279 if (Instruction *I = foldVecTruncToExtElt(Trunc, *this))
1280 return I;
1281
1282 if (Instruction *I = foldVecExtTruncToExtElt(Trunc, *this))
1283 return I;
1284
1285 // trunc (ctlz_i32(zext(A), B) --> add(ctlz_i16(A, B), C)
1286 if (match(Src, m_OneUse(m_Ctlz(m_ZExt(m_Value(A)), m_Value(B))))) {
1287 unsigned AWidth = A->getType()->getScalarSizeInBits();
1288 if (AWidth == DestWidth && AWidth > Log2_32(SrcWidth)) {
1289 Value *WidthDiff = ConstantInt::get(A->getType(), SrcWidth - AWidth);
1290 Value *NarrowCtlz =
1291 Builder.CreateIntrinsic(Intrinsic::ctlz, {Trunc.getType()}, {A, B});
1292 return BinaryOperator::CreateAdd(NarrowCtlz, WidthDiff);
1293 }
1294 }
1295
1296 if (match(Src, m_VScale())) {
1297 if (Trunc.getFunction() &&
1298 Trunc.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
1299 Attribute Attr =
1300 Trunc.getFunction()->getFnAttribute(Attribute::VScaleRange);
1301 if (std::optional<unsigned> MaxVScale = Attr.getVScaleRangeMax())
1302 if (Log2_32(*MaxVScale) < DestWidth)
1303 return replaceInstUsesWith(Trunc, Builder.CreateVScale(DestTy));
1304 }
1305 }
1306
1307 // trunc(scmp(x, y)) -> scmp(x, y) with a narrower result type.
1308 // trunc(ucmp(x, y)) -> ucmp(x, y) with a narrower result type.
1309 // scmp/ucmp produce only -1, 0, or 1, so any result type with at least 2
1310 // bits can represent every possible value and the truncation is lossless.
1311 if (DestWidth >= 2)
1312 if (auto *CI = dyn_cast<CmpIntrinsic>(Src); CI && CI->hasOneUse())
1313 return replaceInstUsesWith(
1314 Trunc, Builder.CreateIntrinsic(DestTy, CI->getIntrinsicID(),
1315 {CI->getLHS(), CI->getRHS()}));
1316
1317 if (DestWidth == 1 &&
1318 (Trunc.hasNoUnsignedWrap() || Trunc.hasNoSignedWrap()) &&
1319 isKnownNonZero(Src, SQ.getWithInstruction(&Trunc)))
1320 return replaceInstUsesWith(Trunc, ConstantInt::getTrue(DestTy));
1321
1322 bool Changed = false;
1323 if (!Trunc.hasNoSignedWrap() &&
1324 ComputeMaxSignificantBits(Src, &Trunc) <= DestWidth) {
1325 Trunc.setHasNoSignedWrap(true);
1326 Changed = true;
1327 }
1328 if (!Trunc.hasNoUnsignedWrap() &&
1329 MaskedValueIsZero(Src, APInt::getBitsSetFrom(SrcWidth, DestWidth),
1330 &Trunc)) {
1331 Trunc.setHasNoUnsignedWrap(true);
1332 Changed = true;
1333 }
1334
1335 const APInt *C1;
1336 Value *V1;
1337 // OP = { lshr, ashr }
1338 // trunc ( OP i8 C1, V1) to i1 -> icmp eq V1, log_2(C1) iff C1 is power of 2
1339 if (DestWidth == 1 && match(Src, m_Shr(m_Power2(C1), m_Value(V1)))) {
1340 Value *Right = ConstantInt::get(V1->getType(), C1->countr_zero());
1341 return new ICmpInst(ICmpInst::ICMP_EQ, V1, Right);
1342 }
1343
1344 // OP = { lshr, ashr }
1345 // trunc ( OP i8 C1, V1) to i1 -> icmp ult V1, log_2(C1 + 1) iff (C1 + 1) is
1346 // power of 2
1347 if (DestWidth == 1 && match(Src, m_Shr(m_LowBitMask(C1), m_Value(V1)))) {
1348 Value *Right = ConstantInt::get(V1->getType(), C1->countr_one());
1349 return new ICmpInst(ICmpInst::ICMP_ULT, V1, Right);
1350 }
1351
1352 // OP = { lshr, ashr }
1353 // trunc ( OP i8 C1, V1) to i1 -> icmp ugt V1, cttz(C1) - 1 iff (C1) is
1354 // negative power of 2
1355 if (DestWidth == 1 && match(Src, m_Shr(m_NegatedPower2(C1), m_Value(V1)))) {
1356 Value *Right = ConstantInt::get(V1->getType(), C1->countr_zero());
1357 return new ICmpInst(ICmpInst::ICMP_UGE, V1, Right);
1358 }
1359
1360 return Changed ? &Trunc : nullptr;
1361}
1362
1363Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp,
1364 ZExtInst &Zext) {
1365 // If we are just checking for a icmp eq of a single bit and zext'ing it
1366 // to an integer, then shift the bit to the appropriate place and then
1367 // cast to integer to avoid the comparison.
1368
1369 // FIXME: This set of transforms does not check for extra uses and/or creates
1370 // an extra instruction (an optional final cast is not included
1371 // in the transform comments). We may also want to favor icmp over
1372 // shifts in cases of equal instructions because icmp has better
1373 // analysis in general (invert the transform).
1374
1375 const APInt *Op1CV;
1376 if (match(Cmp->getOperand(1), m_APInt(Op1CV))) {
1377
1378 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
1379 if (Cmp->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isZero()) {
1380 Value *In = Cmp->getOperand(0);
1381 Value *Sh = ConstantInt::get(In->getType(),
1382 In->getType()->getScalarSizeInBits() - 1);
1383 In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit");
1384 if (In->getType() != Zext.getType())
1385 In = Builder.CreateIntCast(In, Zext.getType(), false /*ZExt*/);
1386
1387 return replaceInstUsesWith(Zext, In);
1388 }
1389
1390 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
1391 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
1392 // zext (X != 0) to i32 --> X iff X has only the low bit set.
1393 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
1394
1395 if (Op1CV->isZero() && Cmp->isEquality()) {
1396 // Exactly 1 possible 1? But not the high-bit because that is
1397 // canonicalized to this form.
1398 KnownBits Known = computeKnownBits(Cmp->getOperand(0), &Zext);
1399 APInt KnownZeroMask(~Known.Zero);
1400 uint32_t ShAmt = KnownZeroMask.logBase2();
1401 bool IsExpectShAmt = KnownZeroMask.isPowerOf2() &&
1402 (Zext.getType()->getScalarSizeInBits() != ShAmt + 1);
1403 if (IsExpectShAmt &&
1404 (Cmp->getOperand(0)->getType() == Zext.getType() ||
1405 Cmp->getPredicate() == ICmpInst::ICMP_NE || ShAmt == 0)) {
1406 Value *In = Cmp->getOperand(0);
1407 if (ShAmt) {
1408 // Perform a logical shr by shiftamt.
1409 // Insert the shift to put the result in the low bit.
1410 In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
1411 In->getName() + ".lobit");
1412 }
1413
1414 // Toggle the low bit for "X == 0".
1415 if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
1416 In = Builder.CreateXor(In, ConstantInt::get(In->getType(), 1));
1417
1418 if (Zext.getType() == In->getType())
1419 return replaceInstUsesWith(Zext, In);
1420
1421 Value *IntCast = Builder.CreateIntCast(In, Zext.getType(), false);
1422 return replaceInstUsesWith(Zext, IntCast);
1423 }
1424 }
1425 }
1426
1427 if (Cmp->isEquality()) {
1428 // Test if a bit is clear/set using a shifted-one mask:
1429 // zext (icmp eq (and X, (1 << ShAmt)), 0) --> and (lshr (not X), ShAmt), 1
1430 // zext (icmp ne (and X, (1 << ShAmt)), 0) --> and (lshr X, ShAmt), 1
1431 Value *X, *ShAmt;
1432 if (Cmp->hasOneUse() && match(Cmp->getOperand(1), m_ZeroInt()) &&
1433 match(Cmp->getOperand(0),
1434 m_OneUse(m_c_And(m_Shl(m_One(), m_Value(ShAmt)), m_Value(X))))) {
1435 auto *And = cast<BinaryOperator>(Cmp->getOperand(0));
1436 Value *Shift = And->getOperand(X == And->getOperand(0) ? 1 : 0);
1437 if (Zext.getType() == And->getType() ||
1438 Cmp->getPredicate() != ICmpInst::ICMP_EQ || Shift->hasOneUse()) {
1439 if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
1440 X = Builder.CreateNot(X);
1441 Value *Lshr = Builder.CreateLShr(X, ShAmt);
1442 Value *And1 =
1443 Builder.CreateAnd(Lshr, ConstantInt::get(X->getType(), 1));
1444 return replaceInstUsesWith(
1445 Zext, Builder.CreateZExtOrTrunc(And1, Zext.getType()));
1446 }
1447 }
1448 }
1449
1450 return nullptr;
1451}
1452
1453/// Determine if the specified value can be computed in the specified wider type
1454/// and produce the same low bits. If not, return false.
1455///
1456/// If this function returns true, it can also return a non-zero number of bits
1457/// (in BitsToClear) which indicates that the value it computes is correct for
1458/// the zero extend, but that the additional BitsToClear bits need to be zero'd
1459/// out. For example, to promote something like:
1460///
1461/// %B = trunc i64 %A to i32
1462/// %C = lshr i32 %B, 8
1463/// %E = zext i32 %C to i64
1464///
1465/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
1466/// set to 8 to indicate that the promoted value needs to have bits 24-31
1467/// cleared in addition to bits 32-63. Since an 'and' will be generated to
1468/// clear the top bits anyway, doing this has no extra cost.
1469///
1470/// This function works on both vectors and scalars.
1471bool TypeEvaluationHelper::canEvaluateZExtd(Value *V, Type *Ty,
1472 unsigned &BitsToClear,
1473 InstCombinerImpl &IC,
1474 Instruction *CxtI) {
1475 TypeEvaluationHelper TYH;
1476 return TYH.canEvaluateZExtdImpl(V, Ty, BitsToClear, IC, CxtI);
1477}
1478bool TypeEvaluationHelper::canEvaluateZExtdImpl(Value *V, Type *Ty,
1479 unsigned &BitsToClear,
1480 InstCombinerImpl &IC,
1481 Instruction *CxtI) {
1482 BitsToClear = 0;
1483 if (canAlwaysEvaluateInType(V, Ty))
1484 return true;
1485 // We stick to the one-user limit for the ZExt transform due to the fact
1486 // that this predicate returns two values: predicate result and BitsToClear.
1487 if (canNotEvaluateInType(V, Ty))
1488 return false;
1489
1490 auto *I = cast<Instruction>(V);
1491 unsigned Tmp;
1492 switch (I->getOpcode()) {
1493 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
1494 case Instruction::SExt: // zext(sext(x)) -> sext(x).
1495 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
1496 return true;
1497 case Instruction::And:
1498 case Instruction::Or:
1499 case Instruction::Xor:
1500 case Instruction::Add:
1501 case Instruction::Sub:
1502 case Instruction::Mul:
1503 if (!canEvaluateZExtdImpl(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
1504 !canEvaluateZExtdImpl(I->getOperand(1), Ty, Tmp, IC, CxtI))
1505 return false;
1506 // These can all be promoted if neither operand has 'bits to clear'.
1507 if (BitsToClear == 0 && Tmp == 0)
1508 return true;
1509
1510 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
1511 // other side, BitsToClear is ok.
1512 if (Tmp == 0 && I->isBitwiseLogicOp()) {
1513 // We use MaskedValueIsZero here for generality, but the case we care
1514 // about the most is constant RHS.
1515 unsigned VSize = V->getType()->getScalarSizeInBits();
1516 if (IC.MaskedValueIsZero(I->getOperand(1),
1517 APInt::getHighBitsSet(VSize, BitsToClear),
1518 CxtI)) {
1519 // If this is an And instruction and all of the BitsToClear are
1520 // known to be zero we can reset BitsToClear.
1521 if (I->getOpcode() == Instruction::And)
1522 BitsToClear = 0;
1523 return true;
1524 }
1525 }
1526
1527 // Otherwise, we don't know how to analyze this BitsToClear case yet.
1528 return false;
1529
1530 case Instruction::Shl: {
1531 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
1532 // upper bits we can reduce BitsToClear by the shift amount.
1533 uint64_t ShiftAmt;
1534 if (match(I->getOperand(1), m_ConstantInt(ShiftAmt))) {
1535 if (!canEvaluateZExtdImpl(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1536 return false;
1537 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
1538 return true;
1539 }
1540 return false;
1541 }
1542 case Instruction::LShr: {
1543 // We can promote lshr(x, cst) if we can promote x. This requires the
1544 // ultimate 'and' to clear out the high zero bits we're clearing out though.
1545 uint64_t ShiftAmt;
1546 if (match(I->getOperand(1), m_ConstantInt(ShiftAmt))) {
1547 if (!canEvaluateZExtdImpl(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1548 return false;
1549 BitsToClear += ShiftAmt;
1550 if (BitsToClear > V->getType()->getScalarSizeInBits())
1551 BitsToClear = V->getType()->getScalarSizeInBits();
1552 return true;
1553 }
1554 // Cannot promote variable LSHR.
1555 return false;
1556 }
1557 case Instruction::Select:
1558 if (!canEvaluateZExtdImpl(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
1559 !canEvaluateZExtdImpl(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
1560 // TODO: If important, we could handle the case when the BitsToClear are
1561 // known zero in the disagreeing side.
1562 Tmp != BitsToClear)
1563 return false;
1564 return true;
1565
1566 case Instruction::PHI: {
1567 // We can change a phi if we can change all operands. Note that we never
1568 // get into trouble with cyclic PHIs here because we only consider
1569 // instructions with a single use.
1570 PHINode *PN = cast<PHINode>(I);
1571 if (!canEvaluateZExtdImpl(PN->getIncomingValue(0), Ty, BitsToClear, IC,
1572 CxtI))
1573 return false;
1574 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
1575 if (!canEvaluateZExtdImpl(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
1576 // TODO: If important, we could handle the case when the BitsToClear
1577 // are known zero in the disagreeing input.
1578 Tmp != BitsToClear)
1579 return false;
1580 return true;
1581 }
1582 case Instruction::Call:
1583 // llvm.vscale() can always be executed in larger type, because the
1584 // value is automatically zero-extended.
1586 if (II->getIntrinsicID() == Intrinsic::vscale)
1587 return true;
1588 return false;
1589 default:
1590 // TODO: Can handle more cases here.
1591 return false;
1592 }
1593}
1594
1596 // If this zero extend is only used by a truncate, let the truncate be
1597 // eliminated before we try to optimize this zext.
1598 if (Zext.hasOneUse() && isa<TruncInst>(Zext.user_back()) &&
1599 !isa<Constant>(Zext.getOperand(0)))
1600 return nullptr;
1601
1602 // If one of the common conversion will work, do it.
1603 if (Instruction *Result = commonCastTransforms(Zext))
1604 return Result;
1605
1606 if (auto *NewI = foldExtractionOfVectorDeinterleave(Zext))
1607 return NewI;
1608
1609 Value *Src = Zext.getOperand(0);
1610 Type *SrcTy = Src->getType(), *DestTy = Zext.getType();
1611
1612 // zext nneg bool x -> 0
1613 if (SrcTy->isIntOrIntVectorTy(1) && Zext.hasNonNeg())
1615
1616 // zext nneg means Src is non-negative and we can treat this as an sext.
1617 // Evaluating as a signed type means that any constant operands will be
1618 // sign-extended instead of zero-extended, which means that, if the
1619 // expression tree contains only no-signed-wrap arithmetic, the sign bits in
1620 // the final result should be enough that we avoid having to clear the high
1621 // bits.
1622 bool EvaluateAsSigned =
1623 Zext.hasNonNeg() && TypeEvaluationHelper::canEvaluateSExtd(Src, DestTy);
1624
1625 // Try to extend the entire expression tree to the wide destination type.
1626 unsigned BitsToClear = 0;
1627 if (shouldChangeType(SrcTy, DestTy) &&
1628 (EvaluateAsSigned || TypeEvaluationHelper::canEvaluateZExtd(
1629 Src, DestTy, BitsToClear, *this, &Zext))) {
1630 assert(BitsToClear <= SrcTy->getScalarSizeInBits() &&
1631 "Can't clear more bits than in SrcTy");
1632
1633 // Okay, we can transform this! Insert the new expression now.
1634 LLVM_DEBUG(
1635 dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1636 " to avoid zero extend: "
1637 << Zext << '\n');
1638 Value *Res = EvaluateInDifferentType(Src, DestTy, EvaluateAsSigned);
1639 assert(Res->getType() == DestTy);
1640
1641 // Preserve debug values referring to Src if the zext is its last use.
1642 if (auto *SrcOp = dyn_cast<Instruction>(Src))
1643 if (SrcOp->hasOneUse())
1644 replaceAllDbgUsesWith(*SrcOp, *Res, Zext, DT);
1645
1646 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits() - BitsToClear;
1647 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1648
1649 // If the high bits are already filled with zeros, just replace this
1650 // cast with the result. If we've evaluated as a signed expressions then
1651 // instead check that the high bits are the sign bit, which we know is zero.
1652 if (EvaluateAsSigned
1653 ? (ComputeNumSignBits(Res, &Zext) > DestBitSize - SrcBitsKept)
1655 Res,
1656 APInt::getHighBitsSet(DestBitSize, DestBitSize - SrcBitsKept),
1657 &Zext))
1658 return replaceInstUsesWith(Zext, Res);
1659
1660 // We need to emit an AND to clear the high bits.
1661 Constant *C = ConstantInt::get(Res->getType(),
1662 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
1663 return BinaryOperator::CreateAnd(Res, C);
1664 }
1665
1666 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
1667 // types and if the sizes are just right we can convert this into a logical
1668 // 'and' which will be much cheaper than the pair of casts.
1669 if (auto *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
1670 // TODO: Subsume this into EvaluateInDifferentType.
1671
1672 // Get the sizes of the types involved. We know that the intermediate type
1673 // will be smaller than A or C, but don't know the relation between A and C.
1674 Value *A = CSrc->getOperand(0);
1675 unsigned SrcSize = A->getType()->getScalarSizeInBits();
1676 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
1677 unsigned DstSize = DestTy->getScalarSizeInBits();
1678 // If we're actually extending zero bits, then if
1679 // SrcSize < DstSize: zext(a & mask)
1680 // SrcSize == DstSize: a & mask
1681 // SrcSize > DstSize: trunc(a) & mask
1682 if (SrcSize < DstSize) {
1683 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1684 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
1685 Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask");
1686 return new ZExtInst(And, DestTy);
1687 }
1688
1689 if (SrcSize == DstSize) {
1690 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1691 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
1692 AndValue));
1693 }
1694 if (SrcSize > DstSize) {
1695 Value *Trunc = Builder.CreateTrunc(A, DestTy);
1696 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
1697 return BinaryOperator::CreateAnd(Trunc,
1698 ConstantInt::get(Trunc->getType(),
1699 AndValue));
1700 }
1701 }
1702
1703 if (auto *Cmp = dyn_cast<ICmpInst>(Src))
1704 return transformZExtICmp(Cmp, Zext);
1705
1706 Constant *C;
1707 Value *X;
1708 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
1709 Value *And;
1710 if (match(Src, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
1712 m_Specific(C))))) {
1713 Value *ZC = Builder.CreateZExt(C, DestTy);
1714 return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
1715 }
1716
1717 // zext(sub(0, trunc(X))) -> and(sub(0, X), mask)
1718 if (match(Src, m_Sub(m_Zero(), m_Trunc(m_SpecificType(DestTy, X))))) {
1720 SrcTy->getScalarSizeInBits());
1721 Value *Neg = Builder.CreateSub(ConstantInt::get(DestTy, 0), X);
1722 return BinaryOperator::CreateAnd(Neg, ConstantInt::get(DestTy, Mask));
1723 }
1724
1725 // If we are truncating, masking, and then zexting back to the original type,
1726 // that's just a mask. This is not handled by canEvaluateZextd if the
1727 // intermediate values have extra uses. This could be generalized further for
1728 // a non-constant mask operand.
1729 // zext (and (trunc X), C) --> and X, (zext C)
1730 if (match(Src, m_And(m_Trunc(m_SpecificType(DestTy, X)), m_Constant(C)))) {
1731 Value *ZextC = Builder.CreateZExt(C, DestTy);
1732 return BinaryOperator::CreateAnd(X, ZextC);
1733 }
1734
1735 Value *Y;
1737 m_NUWTrunc(m_SpecificType(DestTy, X)), m_Value(Y))))) {
1738 Value *ZextY = Builder.CreateZExt(Y, DestTy);
1739 return BinaryOperator::Create(cast<BinaryOperator>(Src)->getOpcode(), X,
1740 ZextY);
1741 }
1742
1743 if (match(Src, m_VScale())) {
1744 if (Zext.getFunction() &&
1745 Zext.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
1746 Attribute Attr =
1747 Zext.getFunction()->getFnAttribute(Attribute::VScaleRange);
1748 if (std::optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
1749 unsigned TypeWidth = Src->getType()->getScalarSizeInBits();
1750 if (Log2_32(*MaxVScale) < TypeWidth)
1751 return replaceInstUsesWith(Zext, Builder.CreateVScale(DestTy));
1752 }
1753 }
1754 }
1755
1756 if (!Zext.hasNonNeg()) {
1757 // If this zero extend is only used by a shift, add nneg flag.
1758 if (Zext.hasOneUse() &&
1759 SrcTy->getScalarSizeInBits() >
1760 Log2_64_Ceil(DestTy->getScalarSizeInBits()) &&
1761 match(Zext.user_back(), m_Shift(m_Value(), m_Specific(&Zext)))) {
1762 Zext.setNonNeg();
1763 return &Zext;
1764 }
1765
1766 if (isKnownNonNegative(Src, SQ.getWithInstruction(&Zext))) {
1767 Zext.setNonNeg();
1768 return &Zext;
1769 }
1770 }
1771
1772 return nullptr;
1773}
1774
1775/// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
1776Instruction *InstCombinerImpl::transformSExtICmp(ICmpInst *Cmp,
1777 SExtInst &Sext) {
1778 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1779 ICmpInst::Predicate Pred = Cmp->getPredicate();
1780
1781 // Don't bother if Op1 isn't of vector or integer type.
1782 if (!Op1->getType()->isIntOrIntVectorTy())
1783 return nullptr;
1784
1785 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_ZeroInt())) {
1786 // sext (x <s 0) --> ashr x, 31 (all ones if negative)
1787 Value *Sh = ConstantInt::get(Op0->getType(),
1788 Op0->getType()->getScalarSizeInBits() - 1);
1789 Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit");
1790 if (In->getType() != Sext.getType())
1791 In = Builder.CreateIntCast(In, Sext.getType(), true /*SExt*/);
1792
1793 return replaceInstUsesWith(Sext, In);
1794 }
1795
1796 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1797 // If we know that only one bit of the LHS of the icmp can be set and we
1798 // have an equality comparison with zero or a power of 2, we can transform
1799 // the icmp and sext into bitwise/integer operations.
1800 if (Cmp->hasOneUse() &&
1801 Cmp->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
1802 KnownBits Known = computeKnownBits(Op0, &Sext);
1803
1804 APInt KnownZeroMask(~Known.Zero);
1805 if (KnownZeroMask.isPowerOf2()) {
1806 Value *In = Cmp->getOperand(0);
1807
1808 // If the icmp tests for a known zero bit we can constant fold it.
1809 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
1810 Value *V = Pred == ICmpInst::ICMP_NE ?
1812 ConstantInt::getNullValue(Sext.getType());
1813 return replaceInstUsesWith(Sext, V);
1814 }
1815
1816 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1817 // sext ((x & 2^n) == 0) -> (x >> n) - 1
1818 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1819 unsigned ShiftAmt = KnownZeroMask.countr_zero();
1820 // Perform a right shift to place the desired bit in the LSB.
1821 if (ShiftAmt)
1822 In = Builder.CreateLShr(In,
1823 ConstantInt::get(In->getType(), ShiftAmt));
1824
1825 // At this point "In" is either 1 or 0. Subtract 1 to turn
1826 // {1, 0} -> {0, -1}.
1827 In = Builder.CreateAdd(In,
1828 ConstantInt::getAllOnesValue(In->getType()),
1829 "sext");
1830 } else {
1831 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
1832 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1833 unsigned ShiftAmt = KnownZeroMask.countl_zero();
1834 // Perform a left shift to place the desired bit in the MSB.
1835 if (ShiftAmt)
1836 In = Builder.CreateShl(In,
1837 ConstantInt::get(In->getType(), ShiftAmt));
1838
1839 // Distribute the bit over the whole bit width.
1840 In = Builder.CreateAShr(In, ConstantInt::get(In->getType(),
1841 KnownZeroMask.getBitWidth() - 1), "sext");
1842 }
1843
1844 if (Sext.getType() == In->getType())
1845 return replaceInstUsesWith(Sext, In);
1846 return CastInst::CreateIntegerCast(In, Sext.getType(), true/*SExt*/);
1847 }
1848 }
1849 }
1850
1851 return nullptr;
1852}
1853
1854/// Return true if we can take the specified value and return it as type Ty
1855/// without inserting any new casts and without changing the value of the common
1856/// low bits. This is used by code that tries to promote integer operations to
1857/// a wider types will allow us to eliminate the extension.
1858///
1859/// This function works on both vectors and scalars.
1860///
1861bool TypeEvaluationHelper::canEvaluateSExtd(Value *V, Type *Ty) {
1862 TypeEvaluationHelper TYH;
1863 return TYH.canEvaluateSExtdImpl(V, Ty) && TYH.allPendingVisited();
1864}
1865
1866bool TypeEvaluationHelper::canEvaluateSExtdImpl(Value *V, Type *Ty) {
1867 return canEvaluate(V, Ty, [this](Value *V, Type *Ty) {
1868 return canEvaluateSExtdPred(V, Ty);
1869 });
1870}
1871
1872bool TypeEvaluationHelper::canEvaluateSExtdPred(Value *V, Type *Ty) {
1873 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1874 "Can't sign extend type to a smaller type");
1875
1876 auto *I = cast<Instruction>(V);
1877 switch (I->getOpcode()) {
1878 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1879 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1880 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1881 return true;
1882 case Instruction::And:
1883 case Instruction::Or:
1884 case Instruction::Xor:
1885 case Instruction::Add:
1886 case Instruction::Sub:
1887 case Instruction::Mul:
1888 // These operators can all arbitrarily be extended if their inputs can.
1889 return canEvaluateSExtdImpl(I->getOperand(0), Ty) &&
1890 canEvaluateSExtdImpl(I->getOperand(1), Ty);
1891
1892 // case Instruction::Shl: TODO
1893 // case Instruction::LShr: TODO
1894
1895 case Instruction::Select:
1896 return canEvaluateSExtdImpl(I->getOperand(1), Ty) &&
1897 canEvaluateSExtdImpl(I->getOperand(2), Ty);
1898
1899 case Instruction::PHI: {
1900 // We can change a phi if we can change all operands. Note that we never
1901 // get into trouble with cyclic PHIs here because canEvaluate handles use
1902 // chain loops.
1903 PHINode *PN = cast<PHINode>(I);
1904 for (Value *IncValue : PN->incoming_values())
1905 if (!canEvaluateSExtdImpl(IncValue, Ty))
1906 return false;
1907 return true;
1908 }
1909 default:
1910 // TODO: Can handle more cases here.
1911 break;
1912 }
1913
1914 return false;
1915}
1916
1918 // If this sign extend is only used by a truncate, let the truncate be
1919 // eliminated before we try to optimize this sext.
1920 if (Sext.hasOneUse() && isa<TruncInst>(Sext.user_back()))
1921 return nullptr;
1922
1923 if (Instruction *I = commonCastTransforms(Sext))
1924 return I;
1925
1926 Value *Src = Sext.getOperand(0);
1927 Type *SrcTy = Src->getType(), *DestTy = Sext.getType();
1928 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1929 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1930
1931 // If the value being extended is zero or positive, use a zext instead.
1932 if (isKnownNonNegative(Src, SQ.getWithInstruction(&Sext))) {
1933 auto CI = CastInst::Create(Instruction::ZExt, Src, DestTy);
1934 CI->setNonNeg(true);
1935 return CI;
1936 }
1937
1938 // Try to extend the entire expression tree to the wide destination type.
1939 bool ShouldExtendExpression = true;
1940 Value *TruncSrc = nullptr;
1941 // It is not desirable to extend expression in the trunc + sext pattern when
1942 // destination type is narrower than original (pre-trunc) type.
1943 if (match(Src, m_Trunc(m_Value(TruncSrc))))
1944 if (TruncSrc->getType()->getScalarSizeInBits() > DestBitSize)
1945 ShouldExtendExpression = false;
1946 if (ShouldExtendExpression && shouldChangeType(SrcTy, DestTy) &&
1947 TypeEvaluationHelper::canEvaluateSExtd(Src, DestTy)) {
1948 // Okay, we can transform this! Insert the new expression now.
1949 LLVM_DEBUG(
1950 dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1951 " to avoid sign extend: "
1952 << Sext << '\n');
1953 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1954 assert(Res->getType() == DestTy);
1955
1956 // If the high bits are already filled with sign bit, just replace this
1957 // cast with the result.
1958 if (ComputeNumSignBits(Res, &Sext) > DestBitSize - SrcBitSize)
1959 return replaceInstUsesWith(Sext, Res);
1960
1961 // We need to emit a shl + ashr to do the sign extend.
1962 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
1963 return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"),
1964 ShAmt);
1965 }
1966
1967 Value *X = TruncSrc;
1968 if (X) {
1969 // If the input has more sign bits than bits truncated, then convert
1970 // directly to final type.
1971 unsigned XBitSize = X->getType()->getScalarSizeInBits();
1972 bool HasNSW = cast<TruncInst>(Src)->hasNoSignedWrap();
1973 if (HasNSW || (ComputeNumSignBits(X, &Sext) > XBitSize - SrcBitSize)) {
1974 auto *Res = CastInst::CreateIntegerCast(X, DestTy, /* isSigned */ true);
1975 if (auto *ResTrunc = dyn_cast<TruncInst>(Res); ResTrunc && HasNSW)
1976 ResTrunc->setHasNoSignedWrap(true);
1977 return Res;
1978 }
1979
1980 // If input is a trunc from the destination type, then convert into shifts.
1981 if (Src->hasOneUse() && X->getType() == DestTy) {
1982 // sext (trunc X) --> ashr (shl X, C), C
1983 Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
1984 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
1985 }
1986
1987 // If we are replacing shifted-in high zero bits with sign bits, convert
1988 // the logic shift to arithmetic shift and eliminate the cast to
1989 // intermediate type:
1990 // sext (trunc (lshr Y, C)) --> sext/trunc (ashr Y, C)
1991 Value *Y;
1992 if (Src->hasOneUse() &&
1994 m_SpecificIntAllowPoison(XBitSize - SrcBitSize)))) {
1995 Value *Ashr = Builder.CreateAShr(Y, XBitSize - SrcBitSize);
1996 return CastInst::CreateIntegerCast(Ashr, DestTy, /* isSigned */ true);
1997 }
1998 }
1999
2000 if (auto *Cmp = dyn_cast<ICmpInst>(Src))
2001 return transformSExtICmp(Cmp, Sext);
2002
2003 // If the input is a shl/ashr pair of a same constant, then this is a sign
2004 // extension from a smaller value. If we could trust arbitrary bitwidth
2005 // integers, we could turn this into a truncate to the smaller bit and then
2006 // use a sext for the whole extension. Since we don't, look deeper and check
2007 // for a truncate. If the source and dest are the same type, eliminate the
2008 // trunc and extend and just do shifts. For example, turn:
2009 // %a = trunc i32 %i to i8
2010 // %b = shl i8 %a, C
2011 // %c = ashr i8 %b, C
2012 // %d = sext i8 %c to i32
2013 // into:
2014 // %a = shl i32 %i, 32-(8-C)
2015 // %d = ashr i32 %a, 32-(8-C)
2016 Value *A = nullptr;
2017 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
2018 Constant *BA = nullptr, *CA = nullptr;
2019 if (match(Src,
2021 m_ImmConstant(CA))) &&
2022 BA->isElementWiseEqual(CA)) {
2023 Constant *WideCurrShAmt =
2024 ConstantFoldCastOperand(Instruction::SExt, CA, DestTy, DL);
2025 assert(WideCurrShAmt && "Constant folding of ImmConstant cannot fail");
2026 Constant *NumLowbitsLeft = ConstantExpr::getSub(
2027 ConstantInt::get(DestTy, SrcTy->getScalarSizeInBits()), WideCurrShAmt);
2028 Constant *NewShAmt = ConstantExpr::getSub(
2029 ConstantInt::get(DestTy, DestTy->getScalarSizeInBits()),
2030 NumLowbitsLeft);
2031 NewShAmt =
2033 A = Builder.CreateShl(A, NewShAmt, Sext.getName());
2034 return BinaryOperator::CreateAShr(A, NewShAmt);
2035 }
2036
2037 // Splatting a bit of constant-index across a value:
2038 // sext (ashr (trunc iN X to iM), M-1) to iN --> ashr (shl X, N-M), N-1
2039 // If the dest type is different, use a cast (adjust use check).
2040 if (match(Src, m_OneUse(m_AShr(m_Trunc(m_Value(X)),
2041 m_SpecificInt(SrcBitSize - 1))))) {
2042 Type *XTy = X->getType();
2043 unsigned XBitSize = XTy->getScalarSizeInBits();
2044 Constant *ShlAmtC = ConstantInt::get(XTy, XBitSize - SrcBitSize);
2045 Constant *AshrAmtC = ConstantInt::get(XTy, XBitSize - 1);
2046 if (XTy == DestTy)
2047 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShlAmtC),
2048 AshrAmtC);
2049 if (cast<BinaryOperator>(Src)->getOperand(0)->hasOneUse()) {
2050 Value *Ashr = Builder.CreateAShr(Builder.CreateShl(X, ShlAmtC), AshrAmtC);
2051 return CastInst::CreateIntegerCast(Ashr, DestTy, /* isSigned */ true);
2052 }
2053 }
2054
2055 if (match(Src, m_VScale())) {
2056 if (Sext.getFunction() &&
2057 Sext.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
2058 Attribute Attr =
2059 Sext.getFunction()->getFnAttribute(Attribute::VScaleRange);
2060 if (std::optional<unsigned> MaxVScale = Attr.getVScaleRangeMax())
2061 if (Log2_32(*MaxVScale) < (SrcBitSize - 1))
2062 return replaceInstUsesWith(Sext, Builder.CreateVScale(DestTy));
2063 }
2064 }
2065
2066 // sext(scmp(x, y)) -> scmp(x, y) with a wider result type.
2067 // sext(ucmp(x, y)) -> ucmp(x, y) with a wider result type.
2068 // scmp/ucmp return only -1, 0, or 1, which sign-extend correctly to any
2069 // wider integer type, so we can sink the extension into the intrinsic.
2070 if (auto *CI = dyn_cast<CmpIntrinsic>(Src); CI && CI->hasOneUse())
2071 return replaceInstUsesWith(
2072 Sext, Builder.CreateIntrinsic(DestTy, CI->getIntrinsicID(),
2073 {CI->getLHS(), CI->getRHS()}));
2074
2075 Value *Y;
2077 m_NSWTrunc(m_SpecificType(DestTy, X)), m_Value(Y))))) {
2078 Value *SextY = Builder.CreateSExt(Y, DestTy);
2079 return BinaryOperator::Create(cast<BinaryOperator>(Src)->getOpcode(), X,
2080 SextY);
2081 }
2082
2083 return nullptr;
2084}
2085
2086/// Return a Constant* for the specified floating-point constant if it fits
2087/// in the specified FP type without changing its value.
2088static bool fitsInFPType(APFloat F, const fltSemantics &Sem) {
2089 bool losesInfo;
2090 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
2091 return !losesInfo;
2092}
2093
2095 bool PreferBFloat) {
2096 // See if the value can be truncated to bfloat and then reextended.
2097 if (PreferBFloat && fitsInFPType(F, APFloat::BFloat()))
2098 return Type::getBFloatTy(Ctx);
2099 // See if the value can be truncated to half and then reextended.
2100 if (!PreferBFloat && fitsInFPType(F, APFloat::IEEEhalf()))
2101 return Type::getHalfTy(Ctx);
2102 // See if the value can be truncated to float and then reextended.
2104 return Type::getFloatTy(Ctx);
2105 if (&F.getSemantics() == &APFloat::IEEEdouble())
2106 return nullptr; // Won't shrink.
2107 // See if the value can be truncated to double and then reextended.
2109 return Type::getDoubleTy(Ctx);
2110 // Don't try to shrink to various long double types.
2111 return nullptr;
2112}
2113
2114static Type *shrinkFPConstant(ConstantFP *CFP, bool PreferBFloat) {
2115 Type *Ty = CFP->getType();
2116 if (Ty->getScalarType()->isPPC_FP128Ty())
2117 return nullptr; // No constant folding of this.
2118
2119 Type *ShrinkTy =
2120 shrinkFPConstant(CFP->getContext(), CFP->getValueAPF(), PreferBFloat);
2121 if (ShrinkTy)
2122 if (auto *VecTy = dyn_cast<VectorType>(Ty))
2123 ShrinkTy = VectorType::get(ShrinkTy, VecTy);
2124
2125 return ShrinkTy;
2126}
2127
2128// Determine if this is a vector of ConstantFPs and if so, return the minimal
2129// type we can safely truncate all elements to.
2130static Type *shrinkFPConstantVector(Value *V, bool PreferBFloat) {
2131 auto *CV = dyn_cast<Constant>(V);
2132 auto *CVVTy = dyn_cast<FixedVectorType>(V->getType());
2133 if (!CV || !CVVTy)
2134 return nullptr;
2135
2136 Type *MinType = nullptr;
2137
2138 unsigned NumElts = CVVTy->getNumElements();
2139
2140 // For fixed-width vectors we find the minimal type by looking
2141 // through the constant values of the vector.
2142 for (unsigned I = 0; I != NumElts; ++I) {
2143 if (match(CV->getAggregateElement(I), m_Poison()))
2144 continue;
2145
2146 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(I));
2147 if (!CFP)
2148 return nullptr;
2149
2150 Type *T = shrinkFPConstant(CFP, PreferBFloat);
2151 if (!T)
2152 return nullptr;
2153
2154 // If we haven't found a type yet or this type has a larger mantissa than
2155 // our previous type, this is our new minimal type.
2156 if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth())
2157 MinType = T;
2158 }
2159
2160 // Make a vector type from the minimal type.
2161 return MinType ? FixedVectorType::get(MinType, NumElts) : nullptr;
2162}
2163
2164/// Find the minimum FP type we can safely truncate to.
2165static Type *getMinimumFPType(Value *V, Type *PreferredTy, InstCombiner &IC) {
2166 if (auto *FPExt = dyn_cast<FPExtInst>(V))
2167 return FPExt->getOperand(0)->getType();
2168
2169 Value *Src;
2170 if (match(V, m_IToFP(m_Value(Src))) &&
2171 IC.canBeCastedExactlyIntToFP(Src, PreferredTy, isa<SIToFPInst>(V),
2173 return PreferredTy;
2174
2175 bool PreferBFloat = PreferredTy->getScalarType()->isBFloatTy();
2176 // If this value is a constant, return the constant in the smallest FP type
2177 // that can accurately represent it. This allows us to turn
2178 // (float)((double)X+2.0) into x+2.0f.
2179 if (auto *CFP = dyn_cast<ConstantFP>(V))
2180 if (Type *T = shrinkFPConstant(CFP, PreferBFloat))
2181 return T;
2182
2183 // Try to shrink scalable and fixed splat vectors.
2184 if (auto *FPC = dyn_cast<Constant>(V))
2185 if (auto *VTy = dyn_cast<VectorType>(V->getType()))
2186 if (auto *Splat = dyn_cast_or_null<ConstantFP>(FPC->getSplatValue()))
2187 if (Type *T = shrinkFPConstant(Splat, PreferBFloat))
2188 return VectorType::get(T, VTy);
2189
2190 // Try to shrink a vector of FP constants. This returns nullptr on scalable
2191 // vectors
2192 if (Type *T = shrinkFPConstantVector(V, PreferBFloat))
2193 return T;
2194
2195 return V->getType();
2196}
2197
2199 bool IsSigned,
2200 const Instruction *CxtI) const {
2201 Type *SrcTy = V->getType();
2202 assert(SrcTy->isIntOrIntVectorTy() && "Expected an integer type");
2203 int SrcSize = (int)SrcTy->getScalarSizeInBits() - IsSigned;
2204 int DestNumSigBits = FPTy->getFPMantissaWidth();
2205
2206 // Easy case - if the source integer type has less bits than the FP mantissa,
2207 // then the cast must be exact.
2208 if (SrcSize <= DestNumSigBits)
2209 return true;
2210
2211 // Cast from FP to integer and back to FP is independent of the intermediate
2212 // integer width because of poison on overflow.
2213 Value *F;
2214 if (match(V, m_FPToI(m_Value(F)))) {
2215 // If this is uitofp (fptosi F), the source needs an extra bit to avoid
2216 // potential rounding of negative FP input values.
2217 int SrcNumSigBits = F->getType()->getFPMantissaWidth();
2218 if (!IsSigned && match(V, m_FPToSI(m_Value())))
2219 SrcNumSigBits++;
2220
2221 // [su]itofp (fpto[su]i F) --> exact if the source type has less or equal
2222 // significant bits than the destination (and make sure neither type is
2223 // weird -- ppc_fp128).
2224 if (SrcNumSigBits > 0 && DestNumSigBits > 0 &&
2225 SrcNumSigBits <= DestNumSigBits)
2226 return true;
2227 }
2228
2229 // Try harder to find if the source integer type has less significant bits.
2230 // Compute number of sign bits or determine trailing zeros.
2231 KnownBits SrcKnown = computeKnownBits(V, CxtI);
2232 int SigBits = (int)SrcTy->getScalarSizeInBits() -
2233 SrcKnown.countMinLeadingZeros() -
2234 SrcKnown.countMinTrailingZeros();
2235 if (SigBits <= DestNumSigBits)
2236 return true;
2237
2238 // For sitofp, the sign maps to the FP sign bit, so only magnitude bits
2239 // (BitWidth - NumSignBits) consume mantissa.
2240 if (IsSigned) {
2241 SigBits = (int)SrcTy->getScalarSizeInBits() - ComputeNumSignBits(V, CxtI);
2242 if (SigBits <= DestNumSigBits)
2243 return true;
2244 }
2245
2246 return false;
2247}
2248
2250 CastInst::CastOps Opcode = I.getOpcode();
2251 assert((Opcode == CastInst::SIToFP || Opcode == CastInst::UIToFP) &&
2252 "Unexpected cast");
2253 Value *Src = I.getOperand(0);
2254 Type *FPTy = I.getType();
2255 return canBeCastedExactlyIntToFP(Src, FPTy, Opcode == CastInst::SIToFP, &I);
2256}
2257
2260 return I;
2261
2262 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
2263 // simplify this expression to avoid one or more of the trunc/extend
2264 // operations if we can do so without changing the numerical results.
2265 //
2266 // The exact manner in which the widths of the operands interact to limit
2267 // what we can and cannot do safely varies from operation to operation, and
2268 // is explained below in the various case statements.
2269 Type *Ty = FPT.getType();
2270 auto *BO = dyn_cast<BinaryOperator>(FPT.getOperand(0));
2271 if (BO && BO->hasOneUse()) {
2272 Type *LHSMinType = getMinimumFPType(BO->getOperand(0), Ty, *this);
2273 Type *RHSMinType = getMinimumFPType(BO->getOperand(1), Ty, *this);
2274 unsigned OpWidth = BO->getType()->getFPMantissaWidth();
2275 unsigned LHSWidth = LHSMinType->getFPMantissaWidth();
2276 unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
2277 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
2278 unsigned DstWidth = Ty->getFPMantissaWidth();
2279
2280 // Narrowing recomputes the binop in a smaller type, which can overflow to
2281 // inf where the wide op was finite. Therefore we can only keep ninf if
2282 // both the binop and the fptrunc have that flag.
2283 FastMathFlags NarrowFMF = BO->getFastMathFlags();
2284 NarrowFMF.setNoInfs(NarrowFMF.noInfs() && FPT.hasNoInfs());
2285
2286 switch (BO->getOpcode()) {
2287 default: break;
2288 case Instruction::FAdd:
2289 case Instruction::FSub:
2290 // For addition and subtraction, the infinitely precise result can
2291 // essentially be arbitrarily wide; proving that double rounding
2292 // will not occur because the result of OpI is exact (as we will for
2293 // FMul, for example) is hopeless. However, we *can* nonetheless
2294 // frequently know that double rounding cannot occur (or that it is
2295 // innocuous) by taking advantage of the specific structure of
2296 // infinitely-precise results that admit double rounding.
2297 //
2298 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
2299 // to represent both sources, we can guarantee that the double
2300 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
2301 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
2302 // for proof of this fact).
2303 //
2304 // Note: Figueroa does not consider the case where DstFormat !=
2305 // SrcFormat. It's possible (likely even!) that this analysis
2306 // could be tightened for those cases, but they are rare (the main
2307 // case of interest here is (float)((double)float + float)).
2308 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
2309 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
2310 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
2311 Instruction *RI = BinaryOperator::Create(BO->getOpcode(), LHS, RHS);
2312 RI->setFastMathFlags(NarrowFMF);
2313 return RI;
2314 }
2315 break;
2316 case Instruction::FMul:
2317 // For multiplication, the infinitely precise result has at most
2318 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
2319 // that such a value can be exactly represented, then no double
2320 // rounding can possibly occur; we can safely perform the operation
2321 // in the destination format if it can represent both sources.
2322 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
2323 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
2324 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
2325 return BinaryOperator::CreateFMulFMF(LHS, RHS, NarrowFMF);
2326 }
2327 break;
2328 case Instruction::FDiv:
2329 // For division, we use again use the bound from Figueroa's
2330 // dissertation. I am entirely certain that this bound can be
2331 // tightened in the unbalanced operand case by an analysis based on
2332 // the diophantine rational approximation bound, but the well-known
2333 // condition used here is a good conservative first pass.
2334 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
2335 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
2336 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
2337 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
2338 return BinaryOperator::CreateFDivFMF(LHS, RHS, NarrowFMF);
2339 }
2340 break;
2341 case Instruction::FRem: {
2342 // Remainder is straightforward. Remainder is always exact, so the
2343 // type of OpI doesn't enter into things at all. We simply evaluate
2344 // in whichever source type is larger, then convert to the
2345 // destination type.
2346 if (SrcWidth == OpWidth)
2347 break;
2348 Value *LHS, *RHS;
2349 if (LHSWidth == SrcWidth) {
2350 LHS = Builder.CreateFPTrunc(BO->getOperand(0), LHSMinType);
2351 RHS = Builder.CreateFPTrunc(BO->getOperand(1), LHSMinType);
2352 } else {
2353 LHS = Builder.CreateFPTrunc(BO->getOperand(0), RHSMinType);
2354 RHS = Builder.CreateFPTrunc(BO->getOperand(1), RHSMinType);
2355 }
2356
2357 Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, BO);
2358 return CastInst::CreateFPCast(ExactResult, Ty);
2359 }
2360 }
2361 }
2362
2363 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
2364 Value *X;
2366 if (Op && Op->hasOneUse()) {
2367 FastMathFlags FMF = FPT.getFastMathFlags();
2368 if (auto *FPMO = dyn_cast<FPMathOperator>(Op))
2369 FMF &= FPMO->getFastMathFlags();
2370
2371 if (match(Op, m_FNeg(m_Value(X)))) {
2372 Value *InnerTrunc = Builder.CreateFPTruncFMF(X, Ty, FMF);
2373 Value *Neg = Builder.CreateFNegFMF(InnerTrunc, FMF);
2374 return replaceInstUsesWith(FPT, Neg);
2375 }
2376
2377 // If we are truncating a select that has an extended operand, we can
2378 // narrow the other operand and do the select as a narrow op.
2379 Value *Cond, *X, *Y;
2381 m_Value(Y)))) {
2382 // fptrunc (select Cond, (fpext X), Y --> select Cond, X, (fptrunc Y)
2383 Value *NarrowY = Builder.CreateFPTruncFMF(Y, Ty, FMF);
2384 Value *Sel =
2385 Builder.CreateSelectFMF(Cond, X, NarrowY, FMF, "narrow.sel", Op);
2386 return replaceInstUsesWith(FPT, Sel);
2387 }
2389 m_FPExt(m_SpecificType(Ty, X))))) {
2390 // fptrunc (select Cond, Y, (fpext X) --> select Cond, (fptrunc Y), X
2391 Value *NarrowY = Builder.CreateFPTruncFMF(Y, Ty, FMF);
2392 Value *Sel =
2393 Builder.CreateSelectFMF(Cond, NarrowY, X, FMF, "narrow.sel", Op);
2394 return replaceInstUsesWith(FPT, Sel);
2395 }
2396 }
2397
2398 if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) {
2399 switch (II->getIntrinsicID()) {
2400 default: break;
2401 case Intrinsic::ceil:
2402 case Intrinsic::fabs:
2403 case Intrinsic::floor:
2404 case Intrinsic::nearbyint:
2405 case Intrinsic::rint:
2406 case Intrinsic::round:
2407 case Intrinsic::roundeven:
2408 case Intrinsic::trunc: {
2409 Value *Src = II->getArgOperand(0);
2410 if (!Src->hasOneUse())
2411 break;
2412
2413 // Except for fabs, this transformation requires the input of the unary FP
2414 // operation to be itself an fpext from the type to which we're
2415 // truncating.
2416 if (II->getIntrinsicID() != Intrinsic::fabs) {
2417 FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src);
2418 if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty)
2419 break;
2420 }
2421
2422 // Do unary FP operation on smaller type.
2423 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
2424 Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
2426 FPT.getModule(), II->getIntrinsicID(), Ty);
2428 II->getOperandBundlesAsDefs(OpBundles);
2429 CallInst *NewCI =
2430 CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName());
2431 // A normal value may be converted to an infinity. It means that we cannot
2432 // propagate ninf from the intrinsic. So we propagate FMF from fptrunc.
2433 NewCI->copyFastMathFlags(&FPT);
2434 return NewCI;
2435 }
2436 }
2437 }
2438
2439 if (Instruction *I = shrinkInsertElt(FPT, Builder))
2440 return I;
2441
2442 Value *Src = FPT.getOperand(0);
2443 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
2444 auto *FPCast = cast<CastInst>(Src);
2445 if (isKnownExactCastIntToFP(*FPCast))
2446 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
2447 }
2448
2449 return nullptr;
2450}
2451
2453 // If the source operand is a cast from integer to FP and known exact, then
2454 // cast the integer operand directly to the destination type.
2455 Type *Ty = FPExt.getType();
2456 Value *Src = FPExt.getOperand(0);
2457 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
2458 auto *FPCast = cast<CastInst>(Src);
2459 if (isKnownExactCastIntToFP(*FPCast))
2460 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
2461 }
2462
2463 return commonCastTransforms(FPExt);
2464}
2465
2466/// fpto{s/u}i[.sat]({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
2467/// This is safe if the intermediate type has enough bits in its mantissa to
2468/// accurately represent all values of X. For example, this won't work with
2469/// i64 -> float -> i64.
2470template <typename FPToIntTy>
2472 constexpr bool IsSaturating = std::is_same_v<FPToIntTy, IntrinsicInst>;
2473
2474 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
2475 return nullptr;
2476
2477 auto *OpI = cast<CastInst>(FI.getOperand(0));
2478 Value *X = OpI->getOperand(0);
2479 Type *XType = X->getType();
2480 Type *DestType = FI.getType();
2481 bool IsInputSigned = isa<SIToFPInst>(OpI);
2482
2483 bool IsOutputSigned;
2484 if constexpr (IsSaturating)
2485 IsOutputSigned = FI.getIntrinsicID() == Intrinsic::fptosi_sat;
2486 else
2487 IsOutputSigned = isa<FPToSIInst>(FI);
2488
2489 // Since we can assume the conversion won't overflow, our decision as to
2490 // whether the input will fit in the float should depend on the minimum
2491 // of the input range and output range.
2492
2493 // This means this is also safe for a signed input and unsigned output, since
2494 // a negative input would lead to undefined behavior.
2495 if (!isKnownExactCastIntToFP(*OpI)) {
2496 if constexpr (!IsSaturating) {
2497 // The first cast may not round exactly based on the source integer width
2498 // and FP width, but the overflow UB rules can still allow this to fold.
2499 // If the destination type is narrow, that means the intermediate FP value
2500 // must be large enough to hold the source value exactly.
2501 //
2502 // For example, (uint8_t)((float)(uint32_t 16777217) is UB.
2503 int OutputSize = (int)DestType->getScalarSizeInBits();
2504 if (OutputSize > OpI->getType()->getFPMantissaWidth())
2505 return nullptr;
2506 } else {
2507 // Sat intrinsics produce a defined saturated value on overflow, so
2508 // the UB-based shortcut is invalid. Require exactness.
2509 return nullptr;
2510 }
2511 }
2512
2513 unsigned SrcWidth = XType->getScalarSizeInBits();
2514 unsigned DestWidth = DestType->getScalarSizeInBits();
2515
2516 if constexpr (IsSaturating) {
2517 // TODO: cross-sign and narrowing cases could be handled with range
2518 // analysis to prove the source fits in the destination.
2519 if (IsInputSigned != IsOutputSigned || DestWidth < SrcWidth)
2520 return nullptr;
2521 }
2522
2523 if (DestWidth > SrcWidth) {
2524 if (IsInputSigned && IsOutputSigned)
2525 return new SExtInst(X, DestType);
2526 return new ZExtInst(X, DestType);
2527 }
2528 if (DestWidth < SrcWidth)
2529 return new TruncInst(X, DestType);
2530
2531 assert(XType == DestType && "Unexpected types for int to FP to int casts");
2532 return replaceInstUsesWith(FI, X);
2533}
2534
2536template Instruction *
2538
2540 // fpto{u/s}i non-norm --> 0
2541 FPClassTest Mask =
2542 FI.getOpcode() == Instruction::FPToUI ? fcPosNormal : fcNormal;
2544 FI.getOperand(0), Mask, IC.getSimplifyQuery().getWithInstruction(&FI));
2545 if (FPClass.isKnownNever(Mask))
2547
2548 // fpto{u/s}i (fdiv ({u/s}itofp X to F), C_fp) --> {u/s}div X, C
2549 //
2550 // F has precision p (significand bits incl. hidden bit); C_fp is the exact FP
2551 // value of the integer constant C. Given N = integer width, this is safe if:
2552 // Unsigned: C > 0 and N <= p.
2553 // Signed: C != 0 and N - 1 <= p, excluding (X == INT_MIN, C == -1) since
2554 // sdiv INT_MIN, -1 is UB while the FP path only yields poison.
2555 // fdiv X, -1 gets transformed to fneg in InstCombine regardless.
2556 //
2557 // The bounds make {u/s}itofp and C_fp exact (every |int| <= 2^p is exact),
2558 // and ensure the rounded quotient never crosses an integer boundary:
2559 // Rounding lemma: for 0 <= A <= 2^p, 1 <= B <= 2^p, q = floor(A/B),
2560 // trunc(R_p(A/B)) = q.
2561 // For r = A - qB > 0, m = q+1, half-gap H(m) <= q/2^p and
2562 // m - A/B = (B-r)/B >= 1/B > q/2^p >= H(m), so R_p(A/B) < m; q = 0 is
2563 // similar (H(1) = 2^(-p-1) < 2^-p <= 1/B).
2564 // Signed case: by symmetry R_p(-z) = -R_p(z), so fptosi yields s*q = sdiv.
2565 bool IsSigned = FI.getOpcode() == Instruction::FPToSI;
2566 Value *X;
2567 const APFloat *APF;
2568 if (IsSigned) {
2569 if (!match(FI.getOperand(0),
2571 return nullptr;
2572 } else {
2573 if (!match(FI.getOperand(0),
2575 return nullptr;
2576 }
2577 Type *IntTy = X->getType();
2578 if (FI.getType() != IntTy)
2579 return nullptr;
2580
2581 unsigned IntWidth = IntTy->getScalarSizeInBits();
2582 unsigned Precision = APFloat::semanticsPrecision(APF->getSemantics());
2583 if (Precision + IsSigned < IntWidth)
2584 return nullptr;
2585
2586 if (!APF->isInteger())
2587 return nullptr;
2588
2589 APSInt Divisor(IntWidth, !IsSigned);
2590 bool IsExact = false;
2591 APF->convertToInteger(Divisor, APFloat::rmTowardZero, &IsExact);
2592 if (!IsExact)
2593 return nullptr;
2594
2595 if (Divisor.isZero())
2596 return nullptr;
2597
2598 // sdiv INT_MIN, -1 is UB, not poison, so this isn't valid if X == INT_MIN.
2599 // fdiv X, -1 gets transformed to fneg anyways, so we do not handle C == -1.
2600 if (IsSigned && Divisor.isAllOnes())
2601 return nullptr;
2602
2603 Constant *C = ConstantInt::get(IntTy, Divisor);
2604 return IsSigned ? BinaryOperator::CreateSDiv(X, C)
2605 : BinaryOperator::CreateUDiv(X, C);
2606}
2607
2609 if (Instruction *I = foldItoFPtoI(FI))
2610 return I;
2611
2612 if (Instruction *I = foldFPtoI(FI, *this))
2613 return I;
2614
2615 return commonCastTransforms(FI);
2616}
2617
2619 if (Instruction *I = foldItoFPtoI(FI))
2620 return I;
2621
2622 if (Instruction *I = foldFPtoI(FI, *this))
2623 return I;
2624
2625 return commonCastTransforms(FI);
2626}
2627
2629 if (Instruction *R = commonCastTransforms(CI))
2630 return R;
2631 if (!CI.hasNonNeg() && isKnownNonNegative(CI.getOperand(0), SQ)) {
2632 CI.setNonNeg();
2633 return &CI;
2634 }
2635 return nullptr;
2636}
2637
2639 if (Instruction *R = commonCastTransforms(CI))
2640 return R;
2641 if (isKnownNonNegative(CI.getOperand(0), SQ)) {
2642 auto *UI =
2643 CastInst::Create(Instruction::UIToFP, CI.getOperand(0), CI.getType());
2644 UI->setNonNeg(true);
2645 return UI;
2646 }
2647 return nullptr;
2648}
2649
2651 // If the source integer type is not the intptr_t type for this target, do a
2652 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
2653 // cast to be exposed to other transforms.
2654 unsigned AS = CI.getAddressSpace();
2655 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
2656 DL.getPointerSizeInBits(AS)) {
2657 Type *Ty = CI.getOperand(0)->getType()->getWithNewType(
2658 DL.getIntPtrType(CI.getContext(), AS));
2659 Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty);
2660 return new IntToPtrInst(P, CI.getType());
2661 }
2662
2663 // Replace (inttoptr (add (ptrtoint %Base), %Offset)) with
2664 // (getelementptr i8, %Base, %Offset) if the pointer is only used as integer
2665 // value.
2666 Value *Base;
2667 Value *Offset;
2668 auto UsesPointerAsInt = [](User *U) {
2670 return true;
2671 if (auto *P = dyn_cast<PHINode>(U))
2672 return P->hasOneUse() && isa<ICmpInst, PtrToIntInst>(*P->user_begin());
2673 return false;
2674 };
2675 if (match(CI.getOperand(0),
2677 m_Value(Offset)))) &&
2679 Base->getType()->getPointerAddressSpace() &&
2680 all_of(CI.users(), UsesPointerAsInt)) {
2681 return GetElementPtrInst::Create(Builder.getInt8Ty(), Base, Offset);
2682 }
2683
2685 return I;
2686
2687 return nullptr;
2688}
2689
2691 // Look through chain of one-use GEPs.
2692 Type *PtrTy = Ptr->getType();
2694 while (true) {
2695 auto *GEP = dyn_cast<GEPOperator>(Ptr);
2696 if (!GEP || !GEP->hasOneUse())
2697 break;
2698 GEPs.push_back(GEP);
2699 Ptr = GEP->getPointerOperand();
2700 }
2701
2702 // Don't handle case where GEP converts from pointer to vector.
2703 if (GEPs.empty() || PtrTy != Ptr->getType())
2704 return nullptr;
2705
2706 // Check whether we know the integer value of the base pointer.
2707 Value *Res;
2708 Type *IdxTy = DL.getIndexType(PtrTy);
2709 if (match(Ptr, m_OneUse(m_IntToPtr(m_Value(Res)))) &&
2710 Res->getType() == IntTy && IntTy == IdxTy) {
2711 // pass
2712 } else if (isa<ConstantPointerNull>(Ptr)) {
2713 Res = Constant::getNullValue(IdxTy);
2714 } else {
2715 return nullptr;
2716 }
2717
2718 // Perform the entire operation on integers instead.
2719 for (GEPOperator *GEP : reverse(GEPs)) {
2720 Value *Offset = EmitGEPOffset(GEP);
2721 Res = Builder.CreateAdd(Res, Offset, "", GEP->hasNoUnsignedWrap());
2722 }
2723 return Builder.CreateZExtOrTrunc(Res, IntTy);
2724}
2725
2727 // If the destination integer type is not the intptr_t type for this target,
2728 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
2729 // to be exposed to other transforms.
2731 Type *SrcTy = SrcOp->getType();
2732 Type *Ty = CI.getType();
2733 unsigned AS = CI.getPointerAddressSpace();
2734 unsigned TySize = Ty->getScalarSizeInBits();
2735 unsigned PtrSize = DL.getPointerSizeInBits(AS);
2736 if (TySize != PtrSize) {
2737 Type *IntPtrTy =
2738 SrcTy->getWithNewType(DL.getIntPtrType(CI.getContext(), AS));
2739 Value *P = Builder.CreatePtrToInt(SrcOp, IntPtrTy);
2740 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
2741 }
2742
2743 // (ptrtoint (ptrmask P, M))
2744 // -> (and (ptrtoint P), M)
2745 // This is generally beneficial as `and` is better supported than `ptrmask`.
2746 Value *Ptr, *Mask;
2748 m_Value(Ptr), m_SpecificType(Ty, Mask)))))
2749 return BinaryOperator::CreateAnd(Builder.CreatePtrToInt(Ptr, Ty), Mask);
2750
2751 if (Value *V = foldPtrToIntOrAddrOfGEP(Ty, SrcOp))
2752 return replaceInstUsesWith(CI, V);
2753
2754 Value *Vec, *Scalar, *Index;
2756 m_Value(Scalar), m_Value(Index))))) {
2757 assert(Vec->getType()->getScalarSizeInBits() == PtrSize && "Wrong type");
2758 // Convert the scalar to int followed by insert to eliminate one cast:
2759 // p2i (ins (i2p Vec), Scalar, Index --> ins Vec, (p2i Scalar), Index
2760 Value *NewCast = Builder.CreatePtrToInt(Scalar, Ty->getScalarType());
2761 return InsertElementInst::Create(Vec, NewCast, Index);
2762 }
2763
2764 return commonCastTransforms(CI);
2765}
2766
2769 Type *Ty = CI.getType();
2770
2771 // (ptrtoaddr (ptrmask P, M))
2772 // -> (and (ptrtoaddr P), M)
2773 // This is generally beneficial as `and` is better supported than `ptrmask`.
2774 Value *Ptr, *Mask;
2776 m_Value(Ptr), m_SpecificType(Ty, Mask)))))
2777 return BinaryOperator::CreateAnd(Builder.CreatePtrToAddr(Ptr), Mask);
2778
2779 if (Value *V = foldPtrToIntOrAddrOfGEP(Ty, SrcOp))
2780 return replaceInstUsesWith(CI, V);
2781
2782 // FIXME: Implement variants of ptrtoint folds.
2783 return commonCastTransforms(CI);
2784}
2785
2786/// This input value (which is known to have vector type) is being zero extended
2787/// or truncated to the specified vector type. Since the zext/trunc is done
2788/// using an integer type, we have a (bitcast(cast(bitcast))) pattern,
2789/// endianness will impact which end of the vector that is extended or
2790/// truncated.
2791///
2792/// A vector is always stored with index 0 at the lowest address, which
2793/// corresponds to the most significant bits for a big endian stored integer and
2794/// the least significant bits for little endian. A trunc/zext of an integer
2795/// impacts the big end of the integer. Thus, we need to add/remove elements at
2796/// the front of the vector for big endian targets, and the back of the vector
2797/// for little endian targets.
2798///
2799/// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
2800///
2801/// The source and destination vector types may have different element types.
2802static Instruction *
2804 InstCombinerImpl &IC) {
2805 // We can only do this optimization if the output is a multiple of the input
2806 // element size, or the input is a multiple of the output element size.
2807 // Convert the input type to have the same element type as the output.
2808 VectorType *SrcTy = cast<VectorType>(InVal->getType());
2809
2810 if (SrcTy->getElementType() != DestTy->getElementType()) {
2811 // The input types don't need to be identical, but for now they must be the
2812 // same size. There is no specific reason we couldn't handle things like
2813 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
2814 // there yet.
2815 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
2816 DestTy->getElementType()->getPrimitiveSizeInBits())
2817 return nullptr;
2818
2819 SrcTy =
2820 FixedVectorType::get(DestTy->getElementType(),
2821 cast<FixedVectorType>(SrcTy)->getNumElements());
2822 InVal = IC.Builder.CreateBitCast(InVal, SrcTy);
2823 }
2824
2825 bool IsBigEndian = IC.getDataLayout().isBigEndian();
2826 unsigned SrcElts = cast<FixedVectorType>(SrcTy)->getNumElements();
2827 unsigned DestElts = cast<FixedVectorType>(DestTy)->getNumElements();
2828
2829 assert(SrcElts != DestElts && "Element counts should be different.");
2830
2831 // Now that the element types match, get the shuffle mask and RHS of the
2832 // shuffle to use, which depends on whether we're increasing or decreasing the
2833 // size of the input.
2834 auto ShuffleMaskStorage = llvm::to_vector<16>(llvm::seq<int>(0, SrcElts));
2835 ArrayRef<int> ShuffleMask;
2836 Value *V2;
2837
2838 if (SrcElts > DestElts) {
2839 // If we're shrinking the number of elements (rewriting an integer
2840 // truncate), just shuffle in the elements corresponding to the least
2841 // significant bits from the input and use poison as the second shuffle
2842 // input.
2843 V2 = PoisonValue::get(SrcTy);
2844 // Make sure the shuffle mask selects the "least significant bits" by
2845 // keeping elements from back of the src vector for big endian, and from the
2846 // front for little endian.
2847 ShuffleMask = ShuffleMaskStorage;
2848 if (IsBigEndian)
2849 ShuffleMask = ShuffleMask.take_back(DestElts);
2850 else
2851 ShuffleMask = ShuffleMask.take_front(DestElts);
2852 } else {
2853 // If we're increasing the number of elements (rewriting an integer zext),
2854 // shuffle in all of the elements from InVal. Fill the rest of the result
2855 // elements with zeros from a constant zero.
2856 V2 = Constant::getNullValue(SrcTy);
2857 // Use first elt from V2 when indicating zero in the shuffle mask.
2858 uint32_t NullElt = SrcElts;
2859 // Extend with null values in the "most significant bits" by adding elements
2860 // in front of the src vector for big endian, and at the back for little
2861 // endian.
2862 unsigned DeltaElts = DestElts - SrcElts;
2863 if (IsBigEndian)
2864 ShuffleMaskStorage.insert(ShuffleMaskStorage.begin(), DeltaElts, NullElt);
2865 else
2866 ShuffleMaskStorage.append(DeltaElts, NullElt);
2867 ShuffleMask = ShuffleMaskStorage;
2868 }
2869
2870 return new ShuffleVectorInst(InVal, V2, ShuffleMask);
2871}
2872
2873static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
2874 return Value % Ty->getPrimitiveSizeInBits() == 0;
2875}
2876
2877static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
2878 return Value / Ty->getPrimitiveSizeInBits();
2879}
2880
2881/// V is a value which is inserted into a vector of VecEltTy.
2882/// Look through the value to see if we can decompose it into
2883/// insertions into the vector. See the example in the comment for
2884/// OptimizeIntegerToVectorInsertions for the pattern this handles.
2885/// The type of V is always a non-zero multiple of VecEltTy's size.
2886/// Shift is the number of bits between the lsb of V and the lsb of
2887/// the vector.
2888///
2889/// This returns false if the pattern can't be matched or true if it can,
2890/// filling in Elements with the elements found here.
2891static bool collectInsertionElements(Value *V, unsigned Shift,
2892 SmallVectorImpl<Value *> &Elements,
2893 Type *VecEltTy, bool isBigEndian) {
2894 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
2895 "Shift should be a multiple of the element type size");
2896
2897 // Poison values never contribute useful bits to the result.
2898 if (match(V, m_Poison()))
2899 return true;
2900
2901 // If we got down to a value of the right type, we win, try inserting into the
2902 // right element.
2903 if (V->getType() == VecEltTy) {
2904 // Inserting null doesn't actually insert any elements.
2905 if (Constant *C = dyn_cast<Constant>(V))
2906 if (C->isNullValue())
2907 return true;
2908
2909 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
2910 if (isBigEndian)
2911 ElementIndex = Elements.size() - ElementIndex - 1;
2912
2913 // Fail if multiple elements are inserted into this slot.
2914 if (Elements[ElementIndex])
2915 return false;
2916
2917 Elements[ElementIndex] = V;
2918 return true;
2919 }
2920
2921 if (Constant *C = dyn_cast<Constant>(V)) {
2922 // Figure out the # elements this provides, and bitcast it or slice it up
2923 // as required.
2924 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
2925 VecEltTy);
2926 // If the constant is the size of a vector element, we just need to bitcast
2927 // it to the right type so it gets properly inserted.
2928 if (NumElts == 1)
2930 Shift, Elements, VecEltTy, isBigEndian);
2931
2932 // Okay, this is a constant that covers multiple elements. Slice it up into
2933 // pieces and insert each element-sized piece into the vector.
2934 if (!isa<IntegerType>(C->getType()))
2935 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
2936 C->getType()->getPrimitiveSizeInBits()));
2937 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
2938 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
2939
2940 for (unsigned i = 0; i != NumElts; ++i) {
2941 unsigned ShiftI = i * ElementSize;
2943 Instruction::LShr, C, ConstantInt::get(C->getType(), ShiftI));
2944 if (!Piece)
2945 return false;
2946
2947 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
2948 if (!collectInsertionElements(Piece, ShiftI + Shift, Elements, VecEltTy,
2949 isBigEndian))
2950 return false;
2951 }
2952 return true;
2953 }
2954
2955 if (!V->hasOneUse()) return false;
2956
2958 if (!I) return false;
2959 switch (I->getOpcode()) {
2960 default: return false; // Unhandled case.
2961 case Instruction::BitCast:
2962 if (I->getOperand(0)->getType()->isVectorTy())
2963 return false;
2964 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2965 isBigEndian);
2966 case Instruction::ZExt:
2968 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
2969 VecEltTy))
2970 return false;
2971 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2972 isBigEndian);
2973 case Instruction::Or:
2974 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2975 isBigEndian) &&
2976 collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
2977 isBigEndian);
2978 case Instruction::Shl: {
2979 // Must be shifting by a constant that is a multiple of the element size.
2980 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
2981 if (!CI) return false;
2982 Shift += CI->getZExtValue();
2983 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
2984 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2985 isBigEndian);
2986 }
2987
2988 }
2989}
2990
2991
2992/// If the input is an 'or' instruction, we may be doing shifts and ors to
2993/// assemble the elements of the vector manually.
2994/// Try to rip the code out and replace it with insertelements. This is to
2995/// optimize code like this:
2996///
2997/// %tmp37 = bitcast float %inc to i32
2998/// %tmp38 = zext i32 %tmp37 to i64
2999/// %tmp31 = bitcast float %inc5 to i32
3000/// %tmp32 = zext i32 %tmp31 to i64
3001/// %tmp33 = shl i64 %tmp32, 32
3002/// %ins35 = or i64 %tmp33, %tmp38
3003/// %tmp43 = bitcast i64 %ins35 to <2 x float>
3004///
3005/// Into two insertelements that do "buildvector{%inc, %inc5}".
3007 InstCombinerImpl &IC) {
3008 auto *DestVecTy = cast<FixedVectorType>(CI.getType());
3009 Value *IntInput = CI.getOperand(0);
3010
3011 // if the int input is just an undef value do not try to optimize to vector
3012 // insertions as it will prevent undef propagation
3013 if (isa<UndefValue>(IntInput))
3014 return nullptr;
3015
3016 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
3017 if (!collectInsertionElements(IntInput, 0, Elements,
3018 DestVecTy->getElementType(),
3019 IC.getDataLayout().isBigEndian()))
3020 return nullptr;
3021
3022 // If we succeeded, we know that all of the element are specified by Elements
3023 // or are zero if Elements has a null entry. Recast this as a set of
3024 // insertions.
3025 Value *Result = Constant::getNullValue(CI.getType());
3026 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
3027 if (!Elements[i]) continue; // Unset element.
3028
3029 Result = IC.Builder.CreateInsertElement(Result, Elements[i], i);
3030 }
3031
3032 return Result;
3033}
3034
3035/// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
3036/// vector followed by extract element. The backend tends to handle bitcasts of
3037/// vectors better than bitcasts of scalars because vector registers are
3038/// usually not type-specific like scalar integer or scalar floating-point.
3040 InstCombinerImpl &IC) {
3041 Value *VecOp, *Index;
3042 if (!match(BitCast.getOperand(0),
3043 m_OneUse(m_ExtractElt(m_Value(VecOp), m_Value(Index)))))
3044 return nullptr;
3045
3046 // The bitcast must be to a vectorizable type, otherwise we can't make a new
3047 // type to extract from.
3048 Type *DestType = BitCast.getType();
3049 VectorType *VecType = cast<VectorType>(VecOp->getType());
3050 if (VectorType::isValidElementType(DestType)) {
3051 auto *NewVecType = VectorType::get(DestType, VecType);
3052 auto *NewBC = IC.Builder.CreateBitCast(VecOp, NewVecType, "bc");
3053 return ExtractElementInst::Create(NewBC, Index);
3054 }
3055
3056 // Only solve DestType is vector to avoid inverse transform in visitBitCast.
3057 // bitcast (extractelement <1 x elt>, dest) -> bitcast(<1 x elt>, dest)
3058 auto *FixedVType = dyn_cast<FixedVectorType>(VecType);
3059 if (DestType->isVectorTy() && FixedVType && FixedVType->getNumElements() == 1)
3060 return CastInst::Create(Instruction::BitCast, VecOp, DestType);
3061
3062 return nullptr;
3063}
3064
3065/// Change the type of a bitwise logic operation if we can eliminate a bitcast.
3067 InstCombiner::BuilderTy &Builder) {
3068 Type *DestTy = BitCast.getType();
3069 BinaryOperator *BO;
3070
3071 if (!match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) ||
3072 !BO->isBitwiseLogicOp())
3073 return nullptr;
3074
3075 // FIXME: This transform is restricted to vector types to avoid backend
3076 // problems caused by creating potentially illegal operations. If a fix-up is
3077 // added to handle that situation, we can remove this check.
3078 if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy())
3079 return nullptr;
3080
3081 if (DestTy->isFPOrFPVectorTy()) {
3082 Value *X, *Y;
3083 // bitcast(logic(bitcast(X), bitcast(Y))) -> bitcast'(logic(bitcast'(X), Y))
3084 if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
3086 if (X->getType()->isFPOrFPVectorTy() &&
3087 Y->getType()->isIntOrIntVectorTy()) {
3088 Value *CastedOp =
3089 Builder.CreateBitCast(BO->getOperand(0), Y->getType());
3090 Value *NewBO = Builder.CreateBinOp(BO->getOpcode(), CastedOp, Y);
3091 return CastInst::CreateBitOrPointerCast(NewBO, DestTy);
3092 }
3093 if (X->getType()->isIntOrIntVectorTy() &&
3094 Y->getType()->isFPOrFPVectorTy()) {
3095 Value *CastedOp =
3096 Builder.CreateBitCast(BO->getOperand(1), X->getType());
3097 Value *NewBO = Builder.CreateBinOp(BO->getOpcode(), CastedOp, X);
3098 return CastInst::CreateBitOrPointerCast(NewBO, DestTy);
3099 }
3100 }
3101 return nullptr;
3102 }
3103
3104 if (!DestTy->isIntOrIntVectorTy())
3105 return nullptr;
3106
3107 Value *X;
3108 if (match(BO->getOperand(0),
3109 m_OneUse(m_BitCast(m_SpecificType(DestTy, X)))) &&
3110 !isa<Constant>(X)) {
3111 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
3112 Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy);
3113 return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1);
3114 }
3115
3116 if (match(BO->getOperand(1),
3117 m_OneUse(m_BitCast(m_SpecificType(DestTy, X)))) &&
3118 !isa<Constant>(X)) {
3119 // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X)
3120 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
3121 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X);
3122 }
3123
3124 // Canonicalize vector bitcasts to come before vector bitwise logic with a
3125 // constant. This eases recognition of special constants for later ops.
3126 // Example:
3127 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
3128 Constant *C;
3129 if (match(BO->getOperand(1), m_Constant(C))) {
3130 // bitcast (logic X, C) --> logic (bitcast X, C')
3131 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
3132 Value *CastedC = Builder.CreateBitCast(C, DestTy);
3133 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC);
3134 }
3135
3136 return nullptr;
3137}
3138
3139/// Change the type of a select if we can eliminate a bitcast.
3141 InstCombiner::BuilderTy &Builder) {
3142 Value *Cond, *TVal, *FVal;
3143 if (!match(BitCast.getOperand(0),
3144 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
3145 return nullptr;
3146
3147 // A vector select must maintain the same number of elements in its operands.
3148 Type *CondTy = Cond->getType();
3149 Type *DestTy = BitCast.getType();
3150
3151 auto *DestVecTy = dyn_cast<VectorType>(DestTy);
3152
3153 if (auto *CondVTy = dyn_cast<VectorType>(CondTy))
3154 if (!DestVecTy ||
3155 CondVTy->getElementCount() != DestVecTy->getElementCount())
3156 return nullptr;
3157
3158 auto *Sel = cast<Instruction>(BitCast.getOperand(0));
3159 auto *SrcVecTy = dyn_cast<VectorType>(TVal->getType());
3160
3161 if ((isa<Constant>(TVal) || isa<Constant>(FVal)) &&
3162 (!DestVecTy ||
3163 (SrcVecTy && ElementCount::isKnownLE(DestVecTy->getElementCount(),
3164 SrcVecTy->getElementCount())))) {
3165 // Avoid introducing select of vector (or select of vector with more
3166 // elements) until the backend can undo this transformation.
3167 Value *CastedTVal = Builder.CreateBitCast(TVal, DestTy);
3168 Value *CastedFVal = Builder.CreateBitCast(FVal, DestTy);
3169 return SelectInst::Create(Cond, CastedTVal, CastedFVal, "", nullptr, Sel);
3170 }
3171
3172 // FIXME: This transform is restricted from changing the select between
3173 // scalars and vectors to avoid backend problems caused by creating
3174 // potentially illegal operations. If a fix-up is added to handle that
3175 // situation, we can remove this check.
3176 if ((DestVecTy != nullptr) != (SrcVecTy != nullptr))
3177 return nullptr;
3178
3179 Value *X;
3180 if (match(TVal, m_OneUse(m_BitCast(m_SpecificType(DestTy, X)))) &&
3181 !isa<Constant>(X)) {
3182 // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y))
3183 Value *CastedVal = Builder.CreateBitCast(FVal, DestTy);
3184 return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel);
3185 }
3186
3187 if (match(FVal, m_OneUse(m_BitCast(m_SpecificType(DestTy, X)))) &&
3188 !isa<Constant>(X)) {
3189 // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X)
3190 Value *CastedVal = Builder.CreateBitCast(TVal, DestTy);
3191 return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel);
3192 }
3193
3194 return nullptr;
3195}
3196
3197/// Check if all users of CI are StoreInsts.
3198static bool hasStoreUsersOnly(CastInst &CI) {
3199 for (User *U : CI.users()) {
3200 if (!isa<StoreInst>(U))
3201 return false;
3202 }
3203 return true;
3204}
3205
3206/// This function handles following case
3207///
3208/// A -> B cast
3209/// PHI
3210/// B -> A cast
3211///
3212/// All the related PHI nodes can be replaced by new PHI nodes with type A.
3213/// The uses of \p CI can be changed to the new PHI node corresponding to \p PN.
3214Instruction *InstCombinerImpl::optimizeBitCastFromPhi(CastInst &CI,
3215 PHINode *PN) {
3216 // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp.
3217 if (hasStoreUsersOnly(CI))
3218 return nullptr;
3219
3220 Value *Src = CI.getOperand(0);
3221 Type *SrcTy = Src->getType(); // Type B
3222 Type *DestTy = CI.getType(); // Type A
3223
3224 SmallVector<PHINode *, 4> PhiWorklist;
3225 SmallSetVector<PHINode *, 4> OldPhiNodes;
3226
3227 // Find all of the A->B casts and PHI nodes.
3228 // We need to inspect all related PHI nodes, but PHIs can be cyclic, so
3229 // OldPhiNodes is used to track all known PHI nodes, before adding a new
3230 // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first.
3231 PhiWorklist.push_back(PN);
3232 OldPhiNodes.insert(PN);
3233 while (!PhiWorklist.empty()) {
3234 auto *OldPN = PhiWorklist.pop_back_val();
3235 for (Value *IncValue : OldPN->incoming_values()) {
3236 if (isa<Constant>(IncValue))
3237 continue;
3238
3239 if (auto *LI = dyn_cast<LoadInst>(IncValue)) {
3240 // If there is a sequence of one or more load instructions, each loaded
3241 // value is used as address of later load instruction, bitcast is
3242 // necessary to change the value type, don't optimize it. For
3243 // simplicity we give up if the load address comes from another load.
3244 Value *Addr = LI->getOperand(0);
3245 if (Addr == &CI || isa<LoadInst>(Addr))
3246 return nullptr;
3247 // Don't tranform "load <256 x i32>, <256 x i32>*" to
3248 // "load x86_amx, x86_amx*", because x86_amx* is invalid.
3249 // TODO: Remove this check when bitcast between vector and x86_amx
3250 // is replaced with a specific intrinsic.
3251 if (DestTy->isX86_AMXTy())
3252 return nullptr;
3253 if (LI->hasOneUse() && LI->isSimple())
3254 continue;
3255 // If a LoadInst has more than one use, changing the type of loaded
3256 // value may create another bitcast.
3257 return nullptr;
3258 }
3259
3260 if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
3261 if (OldPhiNodes.insert(PNode))
3262 PhiWorklist.push_back(PNode);
3263 continue;
3264 }
3265
3266 auto *BCI = dyn_cast<BitCastInst>(IncValue);
3267 // We can't handle other instructions.
3268 if (!BCI)
3269 return nullptr;
3270
3271 // Verify it's a A->B cast.
3272 Type *TyA = BCI->getOperand(0)->getType();
3273 Type *TyB = BCI->getType();
3274 if (TyA != DestTy || TyB != SrcTy)
3275 return nullptr;
3276 }
3277 }
3278
3279 // Check that each user of each old PHI node is something that we can
3280 // rewrite, so that all of the old PHI nodes can be cleaned up afterwards.
3281 for (auto *OldPN : OldPhiNodes) {
3282 for (User *V : OldPN->users()) {
3283 if (auto *SI = dyn_cast<StoreInst>(V)) {
3284 if (!SI->isSimple() || SI->getOperand(0) != OldPN)
3285 return nullptr;
3286 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
3287 // Verify it's a B->A cast.
3288 Type *TyB = BCI->getOperand(0)->getType();
3289 Type *TyA = BCI->getType();
3290 if (TyA != DestTy || TyB != SrcTy)
3291 return nullptr;
3292 } else if (auto *PHI = dyn_cast<PHINode>(V)) {
3293 // As long as the user is another old PHI node, then even if we don't
3294 // rewrite it, the PHI web we're considering won't have any users
3295 // outside itself, so it'll be dead.
3296 if (!OldPhiNodes.contains(PHI))
3297 return nullptr;
3298 } else {
3299 return nullptr;
3300 }
3301 }
3302 }
3303
3304 // For each old PHI node, create a corresponding new PHI node with a type A.
3305 SmallDenseMap<PHINode *, PHINode *> NewPNodes;
3306 for (auto *OldPN : OldPhiNodes) {
3307 Builder.SetInsertPoint(OldPN);
3308 PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
3309 NewPNodes[OldPN] = NewPN;
3310 }
3311
3312 // Fill in the operands of new PHI nodes.
3313 for (auto *OldPN : OldPhiNodes) {
3314 PHINode *NewPN = NewPNodes[OldPN];
3315 for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) {
3316 Value *V = OldPN->getOperand(j);
3317 Value *NewV = nullptr;
3318 if (auto *C = dyn_cast<Constant>(V)) {
3319 NewV = ConstantExpr::getBitCast(C, DestTy);
3320 } else if (auto *LI = dyn_cast<LoadInst>(V)) {
3321 // Explicitly perform load combine to make sure no opposing transform
3322 // can remove the bitcast in the meantime and trigger an infinite loop.
3323 Builder.SetInsertPoint(LI);
3324 NewV = combineLoadToNewType(*LI, DestTy);
3325 // Remove the old load and its use in the old phi, which itself becomes
3326 // dead once the whole transform finishes.
3327 replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
3329 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
3330 NewV = BCI->getOperand(0);
3331 } else if (auto *PrevPN = dyn_cast<PHINode>(V)) {
3332 NewV = NewPNodes[PrevPN];
3333 }
3334 assert(NewV);
3335 NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j));
3336 }
3337 }
3338
3339 // Traverse all accumulated PHI nodes and process its users,
3340 // which are Stores and BitcCasts. Without this processing
3341 // NewPHI nodes could be replicated and could lead to extra
3342 // moves generated after DeSSA.
3343 // If there is a store with type B, change it to type A.
3344
3345
3346 // Replace users of BitCast B->A with NewPHI. These will help
3347 // later to get rid off a closure formed by OldPHI nodes.
3348 Instruction *RetVal = nullptr;
3349 for (auto *OldPN : OldPhiNodes) {
3350 PHINode *NewPN = NewPNodes[OldPN];
3351 for (User *V : make_early_inc_range(OldPN->users())) {
3352 if (auto *SI = dyn_cast<StoreInst>(V)) {
3353 assert(SI->isSimple() && SI->getOperand(0) == OldPN);
3354 Builder.SetInsertPoint(SI);
3355 auto *NewBC =
3356 cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy));
3357 SI->setOperand(0, NewBC);
3358 Worklist.push(SI);
3359 assert(hasStoreUsersOnly(*NewBC));
3360 }
3361 else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
3362 Type *TyB = BCI->getOperand(0)->getType();
3363 Type *TyA = BCI->getType();
3364 assert(TyA == DestTy && TyB == SrcTy);
3365 (void) TyA;
3366 (void) TyB;
3367 Instruction *I = replaceInstUsesWith(*BCI, NewPN);
3368 if (BCI == &CI)
3369 RetVal = I;
3370 } else if (auto *PHI = dyn_cast<PHINode>(V)) {
3371 assert(OldPhiNodes.contains(PHI));
3372 (void) PHI;
3373 } else {
3374 llvm_unreachable("all uses should be handled");
3375 }
3376 }
3377 }
3378
3379 return RetVal;
3380}
3381
3382/// Fold (bitcast (or (and (bitcast X to int), signmask), nneg Y) to fp) to
3383/// copysign((bitcast Y to fp), X)
3385 InstCombiner::BuilderTy &Builder,
3386 const SimplifyQuery &SQ) {
3387 Value *X, *Y;
3388 Type *FTy = CI.getType();
3389 if (!FTy->isFPOrFPVectorTy())
3390 return nullptr;
3393 m_Value(Y)))))
3394 return nullptr;
3395 if (X->getType() != FTy)
3396 return nullptr;
3397 if (!isKnownNonNegative(Y, SQ))
3398 return nullptr;
3399
3400 return Builder.CreateCopySign(Builder.CreateBitCast(Y, FTy), X);
3401}
3402
3404 // If the operands are integer typed then apply the integer transforms,
3405 // otherwise just apply the common ones.
3406 Value *Src = CI.getOperand(0);
3407 Type *SrcTy = Src->getType();
3408 Type *DestTy = CI.getType();
3409
3410 // Get rid of casts from one type to the same type. These are useless and can
3411 // be replaced by the operand.
3412 if (DestTy == Src->getType())
3413 return replaceInstUsesWith(CI, Src);
3414
3415 if (isa<FixedVectorType>(DestTy)) {
3416 if (isa<IntegerType>(SrcTy)) {
3417 // If this is a cast from an integer to vector, check to see if the input
3418 // is a trunc or zext of a bitcast from vector. If so, we can replace all
3419 // the casts with a shuffle and (potentially) a bitcast.
3420 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
3421 CastInst *SrcCast = cast<CastInst>(Src);
3422 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
3423 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
3425 BCIn->getOperand(0), cast<VectorType>(DestTy), *this))
3426 return I;
3427 }
3428
3429 // If the input is an 'or' instruction, we may be doing shifts and ors to
3430 // assemble the elements of the vector manually. Try to rip the code out
3431 // and replace it with insertelements.
3432 if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
3433 return replaceInstUsesWith(CI, V);
3434 }
3435 }
3436
3437 if (FixedVectorType *SrcVTy = dyn_cast<FixedVectorType>(SrcTy)) {
3438 if (SrcVTy->getNumElements() == 1) {
3439 // If our destination is not a vector, then make this a straight
3440 // scalar-scalar cast.
3441 if (!DestTy->isVectorTy()) {
3442 Value *Elem = Builder.CreateExtractElement(Src, uint64_t{0});
3443 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
3444 }
3445
3446 // Otherwise, see if our source is an insert. If so, then use the scalar
3447 // component directly:
3448 // bitcast (inselt <1 x elt> V, X, 0) to <n x m> --> bitcast X to <n x m>
3449 if (auto *InsElt = dyn_cast<InsertElementInst>(Src))
3450 return new BitCastInst(InsElt->getOperand(1), DestTy);
3451 }
3452
3453 // Convert an artificial vector insert into more analyzable bitwise logic.
3454 unsigned BitWidth = DestTy->getScalarSizeInBits();
3455 Value *X, *Y;
3456 uint64_t IndexC;
3457 if (match(Src, m_OneUse(m_InsertElt(
3459 m_Value(Y), m_ConstantInt(IndexC)))) &&
3460 DestTy->isIntegerTy() && Y->getType()->isIntegerTy() &&
3461 isDesirableIntType(BitWidth)) {
3462 // Adjust for big endian - the LSBs are at the high index.
3463 if (DL.isBigEndian())
3464 IndexC = SrcVTy->getNumElements() - 1 - IndexC;
3465
3466 // We only handle (endian-normalized) insert to index 0. Any other insert
3467 // would require a left-shift, so that is an extra instruction.
3468 if (IndexC == 0) {
3469 // bitcast (inselt (bitcast X), Y, 0) --> or (and X, MaskC), (zext Y)
3470 unsigned EltWidth = Y->getType()->getScalarSizeInBits();
3471 APInt MaskC = APInt::getHighBitsSet(BitWidth, BitWidth - EltWidth);
3472 Value *AndX = Builder.CreateAnd(X, MaskC);
3473 Value *ZextY = Builder.CreateZExt(Y, DestTy);
3474 return BinaryOperator::CreateOr(AndX, ZextY);
3475 }
3476 }
3477 }
3478
3479 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(Src)) {
3480 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
3481 // a bitcast to a vector with the same # elts.
3482 Value *ShufOp0 = Shuf->getOperand(0);
3483 Value *ShufOp1 = Shuf->getOperand(1);
3484 auto ShufElts = cast<VectorType>(Shuf->getType())->getElementCount();
3485 auto SrcVecElts = cast<VectorType>(ShufOp0->getType())->getElementCount();
3486 if (Shuf->hasOneUse() && DestTy->isVectorTy() &&
3487 cast<VectorType>(DestTy)->getElementCount() == ShufElts &&
3488 ShufElts == SrcVecElts) {
3489 BitCastInst *Tmp;
3490 // If either of the operands is a cast from CI.getType(), then
3491 // evaluating the shuffle in the casted destination's type will allow
3492 // us to eliminate at least one cast.
3493 if (((Tmp = dyn_cast<BitCastInst>(ShufOp0)) &&
3494 Tmp->getOperand(0)->getType() == DestTy) ||
3495 ((Tmp = dyn_cast<BitCastInst>(ShufOp1)) &&
3496 Tmp->getOperand(0)->getType() == DestTy)) {
3497 Value *LHS = Builder.CreateBitCast(ShufOp0, DestTy);
3498 Value *RHS = Builder.CreateBitCast(ShufOp1, DestTy);
3499 // Return a new shuffle vector. Use the same element ID's, as we
3500 // know the vector types match #elts.
3501 return new ShuffleVectorInst(LHS, RHS, Shuf->getShuffleMask());
3502 }
3503 }
3504
3505 // A bitcasted-to-scalar and byte/bit reversing shuffle is better recognized
3506 // as a byte/bit swap:
3507 // bitcast <N x i8> (shuf X, undef, <N, N-1,...0>) -> bswap (bitcast X)
3508 // bitcast <N x i1> (shuf X, undef, <N, N-1,...0>) -> bitreverse (bitcast X)
3509 if (DestTy->isIntegerTy() && ShufElts.getKnownMinValue() % 2 == 0 &&
3510 Shuf->hasOneUse() && Shuf->isReverse() && match(ShufOp1, m_Poison())) {
3511 unsigned IntrinsicNum = 0;
3512 if (DL.isLegalInteger(DestTy->getScalarSizeInBits()) &&
3513 SrcTy->getScalarSizeInBits() == 8) {
3514 IntrinsicNum = Intrinsic::bswap;
3515 } else if (SrcTy->getScalarSizeInBits() == 1) {
3516 IntrinsicNum = Intrinsic::bitreverse;
3517 }
3518 if (IntrinsicNum != 0) {
3519 assert(ShufOp0->getType() == SrcTy && "Unexpected shuffle mask");
3520 Function *BswapOrBitreverse = Intrinsic::getOrInsertDeclaration(
3521 CI.getModule(), IntrinsicNum, DestTy);
3522 Value *ScalarX = Builder.CreateBitCast(ShufOp0, DestTy);
3523 return CallInst::Create(BswapOrBitreverse, {ScalarX});
3524 }
3525 }
3526 }
3527
3528 // Handle the A->B->A cast, and there is an intervening PHI node.
3529 if (PHINode *PN = dyn_cast<PHINode>(Src))
3530 if (Instruction *I = optimizeBitCastFromPhi(CI, PN))
3531 return I;
3532
3533 if (Instruction *I = canonicalizeBitCastExtElt(CI, *this))
3534 return I;
3535
3537 return I;
3538
3540 return I;
3541
3542 if (Value *V = foldCopySignIdioms(CI, Builder, SQ.getWithInstruction(&CI)))
3543 return replaceInstUsesWith(CI, V);
3544
3545 return commonCastTransforms(CI);
3546}
3547
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
This file defines the DenseMap class.
static bool isSigned(unsigned Opcode)
Hexagon Common GEP
static bool collectInsertionElements(Value *V, unsigned Shift, SmallVectorImpl< Value * > &Elements, Type *VecEltTy, bool isBigEndian)
V is a value which is inserted into a vector of VecEltTy.
static bool hasStoreUsersOnly(CastInst &CI)
Check if all users of CI are StoreInsts.
static Value * foldCopySignIdioms(BitCastInst &CI, InstCombiner::BuilderTy &Builder, const SimplifyQuery &SQ)
Fold (bitcast (or (and (bitcast X to int), signmask), nneg Y) to fp) to copysign((bitcast Y to fp),...
static Type * shrinkFPConstantVector(Value *V, bool PreferBFloat)
static Instruction * canonicalizeBitCastExtElt(BitCastInst &BitCast, InstCombinerImpl &IC)
Canonicalize scalar bitcasts of extracted elements into a bitcast of the vector followed by extract e...
static Instruction * shrinkSplatShuffle(TruncInst &Trunc, InstCombiner::BuilderTy &Builder)
Try to narrow the width of a splat shuffle.
static Instruction * foldFPtoI(Instruction &FI, InstCombiner &IC)
static Instruction * foldBitCastSelect(BitCastInst &BitCast, InstCombiner::BuilderTy &Builder)
Change the type of a select if we can eliminate a bitcast.
static Instruction * foldBitCastBitwiseLogic(BitCastInst &BitCast, InstCombiner::BuilderTy &Builder)
Change the type of a bitwise logic operation if we can eliminate a bitcast.
static bool fitsInFPType(APFloat F, const fltSemantics &Sem)
Return a Constant* for the specified floating-point constant if it fits in the specified FP type with...
static Instruction * optimizeVectorResizeWithIntegerBitCasts(Value *InVal, VectorType *DestTy, InstCombinerImpl &IC)
This input value (which is known to have vector type) is being zero extended or truncated to the spec...
static Instruction * shrinkInsertElt(CastInst &Trunc, InstCombiner::BuilderTy &Builder)
Try to narrow the width of an insert element.
SmallDenseMap< Value *, Value *, 8 > EvaluatedMap
static Type * getMinimumFPType(Value *V, Type *PreferredTy, InstCombiner &IC)
Find the minimum FP type we can safely truncate to.
static bool isMultipleOfTypeSize(unsigned Value, Type *Ty)
static Value * optimizeIntegerToVectorInsertions(BitCastInst &CI, InstCombinerImpl &IC)
If the input is an 'or' instruction, we may be doing shifts and ors to assemble the elements of the v...
static Type * shrinkFPConstant(LLVMContext &Ctx, const APFloat &F, bool PreferBFloat)
static Instruction * foldVecExtTruncToExtElt(TruncInst &Trunc, InstCombinerImpl &IC)
Whenever an element is extracted from a vector, optionally shifted down, and then truncated,...
static Value * EvaluateInDifferentTypeImpl(Value *V, Type *Ty, bool isSigned, InstCombinerImpl &IC, EvaluatedMap &Processed)
static unsigned getTypeSizeIndex(unsigned Value, Type *Ty)
static Instruction * foldVecTruncToExtElt(TruncInst &Trunc, InstCombinerImpl &IC)
Given a vector that is bitcast to an integer, optionally logically right-shifted, and truncated,...
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:318
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static LLVM_ABI unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
Definition APFloat.cpp:332
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
int32_t exactLogBase2() const
Definition APInt.h:1804
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1677
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
This class represents a conversion between pointers from one address space to another.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:279
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:283
This class represents a no-op cast from one type to another.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Type * getSrcTy() const
Return the source type, as a convenience.
Definition InstrTypes.h:679
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static LLVM_ABI CastInst * CreateFPCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create an FPExt, BitCast, or FPTrunc for fp -> fp casts.
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
bool uge(uint64_t Num) const
This function will return true iff this constant represents a value with active bits bigger than 64 b...
Definition Constants.h:262
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
bool isBigEndian() const
Definition DataLayout.h:218
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class represents an extension of floating point types.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noInfs() const
Definition FMF.h:66
void setNoInfs(bool B=true)
Definition FMF.h:81
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2679
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:482
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:477
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2253
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Instruction * visitZExt(ZExtInst &Zext)
Instruction * visitAddrSpaceCast(AddrSpaceCastInst &CI)
Instruction * foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt)
Instruction * visitSExt(SExtInst &Sext)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * visitFPToSI(FPToSIInst &FI)
Instruction * visitTrunc(TruncInst &CI)
Instruction * visitUIToFP(CastInst &CI)
Instruction * visitPtrToInt(PtrToIntInst &CI)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * foldItoFPtoI(FPToIntTy &FI)
fpto{s/u}i.sat --> X or zext(X) or sext(X) or trunc(X) This is safe if the intermediate type has enou...
Instruction * visitSIToFP(CastInst &CI)
Instruction * commonCastTransforms(CastInst &CI)
Implement the transforms common to all CastInst visitors.
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitFPTrunc(FPTruncInst &CI)
Value * foldPtrToIntOrAddrOfGEP(Type *IntTy, Value *Ptr)
Instruction * visitBitCast(BitCastInst &CI)
Instruction * visitIntToPtr(IntToPtrInst &CI)
Instruction * visitFPToUI(FPToUIInst &FI)
Instruction * visitPtrToAddr(PtrToAddrInst &CI)
Value * EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned)
Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns true for,...
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * visitFPExt(CastInst &CI)
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
The core instruction combiner logic.
SimplifyQuery SQ
const DataLayout & getDataLayout() const
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CxtI=nullptr) const
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
LLVM_ABI bool isKnownExactCastIntToFP(CastInst &I) const
Return true if the cast from integer to FP can be proven to be exact for all possible inputs (the con...
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CxtI=nullptr, unsigned Depth=0) const
DominatorTree & DT
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
This class represents a cast from an integer to a pointer.
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
Value * getPointerOperand()
Gets the pointer operand.
This class represents a cast from a pointer to an integer.
Value * getPointerOperand()
Gets the pointer operand.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
void setHasNoSignedWrap(bool B)
void setHasNoUnsignedWrap(bool B)
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition Type.h:202
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:287
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:237
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
static LLVM_ABI Type * getBFloatTy(LLVMContext &C)
Definition Type.cpp:285
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:284
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
This class represents zero extension of integer types.
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
CheckType m_SpecificType(LLT Ty)
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
auto m_VScale()
Matches a call to llvm.vscale().
match_combine_or< CastInst_match< OpTy, FPToUIInst >, CastInst_match< OpTy, FPToSIInst > > m_FPToI(const OpTy &Op)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
CastInst_match< OpTy, FPToSIInst > m_FPToSI(const OpTy &Op)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FDiv > m_FDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::IntToPtr > m_IntToPtr(const OpTy &Op)
Matches IntToPtr.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:345
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2444
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
Matching combinators.
SimplifyQuery getWithInstruction(const Instruction *I) const