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