LLVM 19.0.0git
Constants.cpp
Go to the documentation of this file.
1//===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 Constant* classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Constants.h"
14#include "LLVMContextImpl.h"
15#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/GlobalIFunc.h"
25#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Operator.h"
33#include <algorithm>
34
35using namespace llvm;
36using namespace PatternMatch;
37
38// As set of temporary options to help migrate how splats are represented.
40 "use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden,
41 cl::desc("Use ConstantInt's native fixed-length vector splat support."));
43 "use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantFP's native fixed-length vector splat support."));
46 "use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,
47 cl::desc("Use ConstantInt's native scalable vector splat support."));
49 "use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden,
50 cl::desc("Use ConstantFP's native scalable vector splat support."));
51
52//===----------------------------------------------------------------------===//
53// Constant Class
54//===----------------------------------------------------------------------===//
55
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && CFP->isNegative();
60
61 // Equivalent for a vector of -0.0's.
62 if (getType()->isVectorTy())
63 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
64 return SplatCFP->isNegativeZeroValue();
65
66 // We've already handled true FP case; any other FP vectors can't represent -0.0.
67 if (getType()->isFPOrFPVectorTy())
68 return false;
69
70 // Otherwise, just use +0.0.
71 return isNullValue();
72}
73
74// Return true iff this constant is positive zero (floating point), negative
75// zero (floating point), or a null value.
77 // Floating point values have an explicit -0.0 value.
78 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
79 return CFP->isZero();
80
81 // Check for constant splat vectors of 1 values.
82 if (getType()->isVectorTy())
83 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
84 return SplatCFP->isZero();
85
86 // Otherwise, just use +0.0.
87 return isNullValue();
88}
89
91 // 0 is null.
92 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
93 return CI->isZero();
94
95 // +0.0 is null.
96 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
97 // ppc_fp128 determine isZero using high order double only
98 // Should check the bitwise value to make sure all bits are zero.
99 return CFP->isExactlyValue(+0.0);
100
101 // constant zero is zero for aggregates, cpnull is null for pointers, none for
102 // tokens.
103 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
104 isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);
105}
106
108 // Check for -1 integers
109 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
110 return CI->isMinusOne();
111
112 // Check for FP which are bitcasted from -1 integers
113 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
114 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
115
116 // Check for constant splat vectors of 1 values.
117 if (getType()->isVectorTy())
118 if (const auto *SplatVal = getSplatValue())
119 return SplatVal->isAllOnesValue();
120
121 return false;
122}
123
125 // Check for 1 integers
126 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
127 return CI->isOne();
128
129 // Check for FP which are bitcasted from 1 integers
130 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
131 return CFP->getValueAPF().bitcastToAPInt().isOne();
132
133 // Check for constant splat vectors of 1 values.
134 if (getType()->isVectorTy())
135 if (const auto *SplatVal = getSplatValue())
136 return SplatVal->isOneValue();
137
138 return false;
139}
140
142 // Check for 1 integers
143 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
144 return !CI->isOneValue();
145
146 // Check for FP which are bitcasted from 1 integers
147 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
148 return !CFP->getValueAPF().bitcastToAPInt().isOne();
149
150 // Check that vectors don't contain 1
151 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
152 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
154 if (!Elt || !Elt->isNotOneValue())
155 return false;
156 }
157 return true;
158 }
159
160 // Check for splats that don't contain 1
161 if (getType()->isVectorTy())
162 if (const auto *SplatVal = getSplatValue())
163 return SplatVal->isNotOneValue();
164
165 // It *may* contain 1, we can't tell.
166 return false;
167}
168
170 // Check for INT_MIN integers
171 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
172 return CI->isMinValue(/*isSigned=*/true);
173
174 // Check for FP which are bitcasted from INT_MIN integers
175 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
176 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
177
178 // Check for splats of INT_MIN values.
179 if (getType()->isVectorTy())
180 if (const auto *SplatVal = getSplatValue())
181 return SplatVal->isMinSignedValue();
182
183 return false;
184}
185
187 // Check for INT_MIN integers
188 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
189 return !CI->isMinValue(/*isSigned=*/true);
190
191 // Check for FP which are bitcasted from INT_MIN integers
192 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
193 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
194
195 // Check that vectors don't contain INT_MIN
196 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
197 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
199 if (!Elt || !Elt->isNotMinSignedValue())
200 return false;
201 }
202 return true;
203 }
204
205 // Check for splats that aren't INT_MIN
206 if (getType()->isVectorTy())
207 if (const auto *SplatVal = getSplatValue())
208 return SplatVal->isNotMinSignedValue();
209
210 // It *may* contain INT_MIN, we can't tell.
211 return false;
212}
213
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isFiniteNonZero();
217
218 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
219 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
221 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
222 return false;
223 }
224 return true;
225 }
226
227 if (getType()->isVectorTy())
228 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
229 return SplatCFP->isFiniteNonZeroFP();
230
231 // It *may* contain finite non-zero, we can't tell.
232 return false;
233}
234
236 if (auto *CFP = dyn_cast<ConstantFP>(this))
237 return CFP->getValueAPF().isNormal();
238
239 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
240 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
241 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
242 if (!CFP || !CFP->getValueAPF().isNormal())
243 return false;
244 }
245 return true;
246 }
247
248 if (getType()->isVectorTy())
249 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
250 return SplatCFP->isNormalFP();
251
252 // It *may* contain a normal fp value, we can't tell.
253 return false;
254}
255
257 if (auto *CFP = dyn_cast<ConstantFP>(this))
258 return CFP->getValueAPF().getExactInverse(nullptr);
259
260 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
261 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
262 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
263 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
264 return false;
265 }
266 return true;
267 }
268
269 if (getType()->isVectorTy())
270 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
271 return SplatCFP->hasExactInverseFP();
272
273 // It *may* have an exact inverse fp value, we can't tell.
274 return false;
275}
276
277bool Constant::isNaN() const {
278 if (auto *CFP = dyn_cast<ConstantFP>(this))
279 return CFP->isNaN();
280
281 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
282 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
283 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
284 if (!CFP || !CFP->isNaN())
285 return false;
286 }
287 return true;
288 }
289
290 if (getType()->isVectorTy())
291 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
292 return SplatCFP->isNaN();
293
294 // It *may* be NaN, we can't tell.
295 return false;
296}
297
299 // Are they fully identical?
300 if (this == Y)
301 return true;
302
303 // The input value must be a vector constant with the same type.
304 auto *VTy = dyn_cast<VectorType>(getType());
305 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
306 return false;
307
308 // TODO: Compare pointer constants?
309 if (!(VTy->getElementType()->isIntegerTy() ||
310 VTy->getElementType()->isFloatingPointTy()))
311 return false;
312
313 // They may still be identical element-wise (if they have `undef`s).
314 // Bitcast to integer to allow exact bitwise comparison for all types.
315 Type *IntTy = VectorType::getInteger(VTy);
316 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
317 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
319 return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
320}
321
322static bool
324 function_ref<bool(const Constant *)> HasFn) {
325 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
326 if (HasFn(C))
327 return true;
328 if (isa<ConstantAggregateZero>(C))
329 return false;
330 if (isa<ScalableVectorType>(C->getType()))
331 return false;
332
333 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
334 i != e; ++i) {
335 if (Constant *Elem = C->getAggregateElement(i))
336 if (HasFn(Elem))
337 return true;
338 }
339 }
340
341 return false;
342}
343
346 this, [&](const auto *C) { return isa<UndefValue>(C); });
347}
348
351 this, [&](const auto *C) { return isa<PoisonValue>(C); });
352}
353
355 return containsUndefinedElement(this, [&](const auto *C) {
356 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
357 });
358}
359
361 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
363 if (isa<ConstantExpr>(getAggregateElement(i)))
364 return true;
365 }
366 return false;
367}
368
369/// Constructor to create a '0' constant of arbitrary type.
371 switch (Ty->getTypeID()) {
373 return ConstantInt::get(Ty, 0);
374 case Type::HalfTyID:
375 case Type::BFloatTyID:
376 case Type::FloatTyID:
377 case Type::DoubleTyID:
379 case Type::FP128TyID:
381 return ConstantFP::get(Ty->getContext(),
384 return ConstantPointerNull::get(cast<PointerType>(Ty));
385 case Type::StructTyID:
386 case Type::ArrayTyID:
390 case Type::TokenTyID:
393 return ConstantTargetNone::get(cast<TargetExtType>(Ty));
394 default:
395 // Function, Label, or Opaque type?
396 llvm_unreachable("Cannot create a null constant of that type!");
397 }
398}
399
401 Type *ScalarTy = Ty->getScalarType();
402
403 // Create the base integer constant.
404 Constant *C = ConstantInt::get(Ty->getContext(), V);
405
406 // Convert an integer to a pointer, if necessary.
407 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
409
410 // Broadcast a scalar to a vector, if necessary.
411 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
412 C = ConstantVector::getSplat(VTy->getElementCount(), C);
413
414 return C;
415}
416
418 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
419 return ConstantInt::get(Ty->getContext(),
420 APInt::getAllOnes(ITy->getBitWidth()));
421
422 if (Ty->isFloatingPointTy()) {
424 return ConstantFP::get(Ty->getContext(), FL);
425 }
426
427 VectorType *VTy = cast<VectorType>(Ty);
430}
431
433 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
434 "Must be an aggregate/vector constant");
435
436 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
437 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
438
439 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
440 return Elt < CAZ->getElementCount().getKnownMinValue()
441 ? CAZ->getElementValue(Elt)
442 : nullptr;
443
444 // FIXME: getNumElements() will fail for non-fixed vector types.
445 if (isa<ScalableVectorType>(getType()))
446 return nullptr;
447
448 if (const auto *PV = dyn_cast<PoisonValue>(this))
449 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
450
451 if (const auto *UV = dyn_cast<UndefValue>(this))
452 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
453
454 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
455 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
456 : nullptr;
457
458 return nullptr;
459}
460
462 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
463 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
464 // Check if the constant fits into an uint64_t.
465 if (CI->getValue().getActiveBits() > 64)
466 return nullptr;
467 return getAggregateElement(CI->getZExtValue());
468 }
469 return nullptr;
470}
471
473 /// First call destroyConstantImpl on the subclass. This gives the subclass
474 /// a chance to remove the constant from any maps/pools it's contained in.
475 switch (getValueID()) {
476 default:
477 llvm_unreachable("Not a constant!");
478#define HANDLE_CONSTANT(Name) \
479 case Value::Name##Val: \
480 cast<Name>(this)->destroyConstantImpl(); \
481 break;
482#include "llvm/IR/Value.def"
483 }
484
485 // When a Constant is destroyed, there may be lingering
486 // references to the constant by other constants in the constant pool. These
487 // constants are implicitly dependent on the module that is being deleted,
488 // but they don't know that. Because we only find out when the CPV is
489 // deleted, we must now notify all of our users (that should only be
490 // Constants) that they are, in fact, invalid now and should be deleted.
491 //
492 while (!use_empty()) {
493 Value *V = user_back();
494#ifndef NDEBUG // Only in -g mode...
495 if (!isa<Constant>(V)) {
496 dbgs() << "While deleting: " << *this
497 << "\n\nUse still stuck around after Def is destroyed: " << *V
498 << "\n\n";
499 }
500#endif
501 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
502 cast<Constant>(V)->destroyConstant();
503
504 // The constant should remove itself from our use list...
505 assert((use_empty() || user_back() != V) && "Constant not removed!");
506 }
507
508 // Value has no outstanding references it is safe to delete it now...
509 deleteConstant(this);
510}
511
513 switch (C->getValueID()) {
514 case Constant::ConstantIntVal:
515 delete static_cast<ConstantInt *>(C);
516 break;
517 case Constant::ConstantFPVal:
518 delete static_cast<ConstantFP *>(C);
519 break;
520 case Constant::ConstantAggregateZeroVal:
521 delete static_cast<ConstantAggregateZero *>(C);
522 break;
523 case Constant::ConstantArrayVal:
524 delete static_cast<ConstantArray *>(C);
525 break;
526 case Constant::ConstantStructVal:
527 delete static_cast<ConstantStruct *>(C);
528 break;
529 case Constant::ConstantVectorVal:
530 delete static_cast<ConstantVector *>(C);
531 break;
532 case Constant::ConstantPointerNullVal:
533 delete static_cast<ConstantPointerNull *>(C);
534 break;
535 case Constant::ConstantDataArrayVal:
536 delete static_cast<ConstantDataArray *>(C);
537 break;
538 case Constant::ConstantDataVectorVal:
539 delete static_cast<ConstantDataVector *>(C);
540 break;
541 case Constant::ConstantTokenNoneVal:
542 delete static_cast<ConstantTokenNone *>(C);
543 break;
544 case Constant::BlockAddressVal:
545 delete static_cast<BlockAddress *>(C);
546 break;
547 case Constant::DSOLocalEquivalentVal:
548 delete static_cast<DSOLocalEquivalent *>(C);
549 break;
550 case Constant::NoCFIValueVal:
551 delete static_cast<NoCFIValue *>(C);
552 break;
553 case Constant::UndefValueVal:
554 delete static_cast<UndefValue *>(C);
555 break;
556 case Constant::PoisonValueVal:
557 delete static_cast<PoisonValue *>(C);
558 break;
559 case Constant::ConstantExprVal:
560 if (isa<CastConstantExpr>(C))
561 delete static_cast<CastConstantExpr *>(C);
562 else if (isa<BinaryConstantExpr>(C))
563 delete static_cast<BinaryConstantExpr *>(C);
564 else if (isa<ExtractElementConstantExpr>(C))
565 delete static_cast<ExtractElementConstantExpr *>(C);
566 else if (isa<InsertElementConstantExpr>(C))
567 delete static_cast<InsertElementConstantExpr *>(C);
568 else if (isa<ShuffleVectorConstantExpr>(C))
569 delete static_cast<ShuffleVectorConstantExpr *>(C);
570 else if (isa<GetElementPtrConstantExpr>(C))
571 delete static_cast<GetElementPtrConstantExpr *>(C);
572 else if (isa<CompareConstantExpr>(C))
573 delete static_cast<CompareConstantExpr *>(C);
574 else
575 llvm_unreachable("Unexpected constant expr");
576 break;
577 default:
578 llvm_unreachable("Unexpected constant");
579 }
580}
581
582/// Check if C contains a GlobalValue for which Predicate is true.
583static bool
585 bool (*Predicate)(const GlobalValue *)) {
588 WorkList.push_back(C);
589 Visited.insert(C);
590
591 while (!WorkList.empty()) {
592 const Constant *WorkItem = WorkList.pop_back_val();
593 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
594 if (Predicate(GV))
595 return true;
596 for (const Value *Op : WorkItem->operands()) {
597 const Constant *ConstOp = dyn_cast<Constant>(Op);
598 if (!ConstOp)
599 continue;
600 if (Visited.insert(ConstOp).second)
601 WorkList.push_back(ConstOp);
602 }
603 }
604 return false;
605}
606
608 auto DLLImportPredicate = [](const GlobalValue *GV) {
609 return GV->isThreadLocal();
610 };
611 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
612}
613
615 auto DLLImportPredicate = [](const GlobalValue *GV) {
616 return GV->hasDLLImportStorageClass();
617 };
618 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
619}
620
622 for (const User *U : users()) {
623 const Constant *UC = dyn_cast<Constant>(U);
624 if (!UC || isa<GlobalValue>(UC))
625 return true;
626
627 if (UC->isConstantUsed())
628 return true;
629 }
630 return false;
631}
632
634 return getRelocationInfo() == GlobalRelocation;
635}
636
638 return getRelocationInfo() != NoRelocation;
639}
640
641Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
642 if (isa<GlobalValue>(this))
643 return GlobalRelocation; // Global reference.
644
645 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
646 return BA->getFunction()->getRelocationInfo();
647
648 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
649 if (CE->getOpcode() == Instruction::Sub) {
650 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
651 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
652 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
653 RHS->getOpcode() == Instruction::PtrToInt) {
654 Constant *LHSOp0 = LHS->getOperand(0);
655 Constant *RHSOp0 = RHS->getOperand(0);
656
657 // While raw uses of blockaddress need to be relocated, differences
658 // between two of them don't when they are for labels in the same
659 // function. This is a common idiom when creating a table for the
660 // indirect goto extension, so we handle it efficiently here.
661 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
662 cast<BlockAddress>(LHSOp0)->getFunction() ==
663 cast<BlockAddress>(RHSOp0)->getFunction())
664 return NoRelocation;
665
666 // Relative pointers do not need to be dynamically relocated.
667 if (auto *RHSGV =
668 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
669 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
670 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
671 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
672 return LocalRelocation;
673 } else if (isa<DSOLocalEquivalent>(LHS)) {
674 if (RHSGV->isDSOLocal())
675 return LocalRelocation;
676 }
677 }
678 }
679 }
680 }
681
682 PossibleRelocationsTy Result = NoRelocation;
683 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
684 Result =
685 std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);
686
687 return Result;
688}
689
690/// Return true if the specified constantexpr is dead. This involves
691/// recursively traversing users of the constantexpr.
692/// If RemoveDeadUsers is true, also remove dead users at the same time.
693static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
694 if (isa<GlobalValue>(C)) return false; // Cannot remove this
695
696 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
697 while (I != E) {
698 const Constant *User = dyn_cast<Constant>(*I);
699 if (!User) return false; // Non-constant usage;
700 if (!constantIsDead(User, RemoveDeadUsers))
701 return false; // Constant wasn't dead
702
703 // Just removed User, so the iterator was invalidated.
704 // Since we return immediately upon finding a live user, we can always
705 // restart from user_begin().
706 if (RemoveDeadUsers)
707 I = C->user_begin();
708 else
709 ++I;
710 }
711
712 if (RemoveDeadUsers) {
713 // If C is only used by metadata, it should not be preserved but should
714 // have its uses replaced.
716 const_cast<Constant *>(C)->destroyConstant();
717 }
718
719 return true;
720}
721
724 Value::const_user_iterator LastNonDeadUser = E;
725 while (I != E) {
726 const Constant *User = dyn_cast<Constant>(*I);
727 if (!User) {
728 LastNonDeadUser = I;
729 ++I;
730 continue;
731 }
732
733 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
734 // If the constant wasn't dead, remember that this was the last live use
735 // and move on to the next constant.
736 LastNonDeadUser = I;
737 ++I;
738 continue;
739 }
740
741 // If the constant was dead, then the iterator is invalidated.
742 if (LastNonDeadUser == E)
743 I = user_begin();
744 else
745 I = std::next(LastNonDeadUser);
746 }
747}
748
749bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
750
751bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
752
753bool Constant::hasNLiveUses(unsigned N) const {
754 unsigned NumUses = 0;
755 for (const Use &U : uses()) {
756 const Constant *User = dyn_cast<Constant>(U.getUser());
757 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
758 ++NumUses;
759
760 if (NumUses > N)
761 return false;
762 }
763 }
764 return NumUses == N;
765}
766
768 assert(C && Replacement && "Expected non-nullptr constant arguments");
769 Type *Ty = C->getType();
770 if (match(C, m_Undef())) {
771 assert(Ty == Replacement->getType() && "Expected matching types");
772 return Replacement;
773 }
774
775 // Don't know how to deal with this constant.
776 auto *VTy = dyn_cast<FixedVectorType>(Ty);
777 if (!VTy)
778 return C;
779
780 unsigned NumElts = VTy->getNumElements();
781 SmallVector<Constant *, 32> NewC(NumElts);
782 for (unsigned i = 0; i != NumElts; ++i) {
783 Constant *EltC = C->getAggregateElement(i);
784 assert((!EltC || EltC->getType() == Replacement->getType()) &&
785 "Expected matching types");
786 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
787 }
788 return ConstantVector::get(NewC);
789}
790
792 assert(C && Other && "Expected non-nullptr constant arguments");
793 if (match(C, m_Undef()))
794 return C;
795
796 Type *Ty = C->getType();
797 if (match(Other, m_Undef()))
798 return UndefValue::get(Ty);
799
800 auto *VTy = dyn_cast<FixedVectorType>(Ty);
801 if (!VTy)
802 return C;
803
804 Type *EltTy = VTy->getElementType();
805 unsigned NumElts = VTy->getNumElements();
806 assert(isa<FixedVectorType>(Other->getType()) &&
807 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
808 "Type mismatch");
809
810 bool FoundExtraUndef = false;
811 SmallVector<Constant *, 32> NewC(NumElts);
812 for (unsigned I = 0; I != NumElts; ++I) {
813 NewC[I] = C->getAggregateElement(I);
814 Constant *OtherEltC = Other->getAggregateElement(I);
815 assert(NewC[I] && OtherEltC && "Unknown vector element");
816 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
817 NewC[I] = UndefValue::get(EltTy);
818 FoundExtraUndef = true;
819 }
820 }
821 if (FoundExtraUndef)
822 return ConstantVector::get(NewC);
823 return C;
824}
825
827 if (isa<ConstantData>(this))
828 return true;
829 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
830 for (const Value *Op : operand_values())
831 if (!cast<Constant>(Op)->isManifestConstant())
832 return false;
833 return true;
834 }
835 return false;
836}
837
838//===----------------------------------------------------------------------===//
839// ConstantInt
840//===----------------------------------------------------------------------===//
841
842ConstantInt::ConstantInt(Type *Ty, const APInt &V)
843 : ConstantData(Ty, ConstantIntVal), Val(V) {
844 assert(V.getBitWidth() ==
845 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
846 "Invalid constant for type");
847}
848
851 if (!pImpl->TheTrueVal)
852 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
853 return pImpl->TheTrueVal;
854}
855
858 if (!pImpl->TheFalseVal)
859 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
860 return pImpl->TheFalseVal;
861}
862
864 return V ? getTrue(Context) : getFalse(Context);
865}
866
868 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
870 if (auto *VTy = dyn_cast<VectorType>(Ty))
871 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
872 return TrueC;
873}
874
876 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
878 if (auto *VTy = dyn_cast<VectorType>(Ty))
879 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
880 return FalseC;
881}
882
884 return V ? getTrue(Ty) : getFalse(Ty);
885}
886
887// Get a ConstantInt from an APInt.
888ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
889 // get an existing value or the insertion position
891 std::unique_ptr<ConstantInt> &Slot =
892 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
893 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
894 : pImpl->IntConstants[V];
895 if (!Slot) {
896 // Get the corresponding integer type for the bit width of the value.
897 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
898 Slot.reset(new ConstantInt(ITy, V));
899 }
900 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
901 return Slot.get();
902}
903
904// Get a ConstantInt vector with each lane set to the same APInt.
905ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
906 const APInt &V) {
907 // Get an existing value or the insertion position.
908 std::unique_ptr<ConstantInt> &Slot =
909 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
910 if (!Slot) {
911 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
912 VectorType *VTy = VectorType::get(ITy, EC);
913 Slot.reset(new ConstantInt(VTy, V));
914 }
915
916#ifndef NDEBUG
917 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
918 VectorType *VTy = VectorType::get(ITy, EC);
919 assert(Slot->getType() == VTy);
920#endif
921 return Slot.get();
922}
923
924Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
925 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
926
927 // For vectors, broadcast the value.
928 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
929 return ConstantVector::getSplat(VTy->getElementCount(), C);
930
931 return C;
932}
933
934ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
935 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
936}
937
938Constant *ConstantInt::get(Type *Ty, const APInt& V) {
939 ConstantInt *C = get(Ty->getContext(), V);
940 assert(C->getType() == Ty->getScalarType() &&
941 "ConstantInt type doesn't match the type implied by its value!");
942
943 // For vectors, broadcast the value.
944 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
945 return ConstantVector::getSplat(VTy->getElementCount(), C);
946
947 return C;
948}
949
950ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
951 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
952}
953
954/// Remove the constant from the constant table.
955void ConstantInt::destroyConstantImpl() {
956 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
957}
958
959//===----------------------------------------------------------------------===//
960// ConstantFP
961//===----------------------------------------------------------------------===//
962
963Constant *ConstantFP::get(Type *Ty, double V) {
965
966 APFloat FV(V);
967 bool ignored;
970 Constant *C = get(Context, FV);
971
972 // For vectors, broadcast the value.
973 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
974 return ConstantVector::getSplat(VTy->getElementCount(), C);
975
976 return C;
977}
978
979Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
980 ConstantFP *C = get(Ty->getContext(), V);
981 assert(C->getType() == Ty->getScalarType() &&
982 "ConstantFP type doesn't match the type implied by its value!");
983
984 // For vectors, broadcast the value.
985 if (auto *VTy = dyn_cast<VectorType>(Ty))
986 return ConstantVector::getSplat(VTy->getElementCount(), C);
987
988 return C;
989}
990
991Constant *ConstantFP::get(Type *Ty, StringRef Str) {
993
994 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
995 Constant *C = get(Context, FV);
996
997 // For vectors, broadcast the value.
998 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
999 return ConstantVector::getSplat(VTy->getElementCount(), C);
1000
1001 return C;
1002}
1003
1004Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1005 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1006 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1007 Constant *C = get(Ty->getContext(), NaN);
1008
1009 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1010 return ConstantVector::getSplat(VTy->getElementCount(), C);
1011
1012 return C;
1013}
1014
1015Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1016 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1017 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1018 Constant *C = get(Ty->getContext(), NaN);
1019
1020 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1021 return ConstantVector::getSplat(VTy->getElementCount(), C);
1022
1023 return C;
1024}
1025
1026Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1027 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1028 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1029 Constant *C = get(Ty->getContext(), NaN);
1030
1031 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1032 return ConstantVector::getSplat(VTy->getElementCount(), C);
1033
1034 return C;
1035}
1036
1037Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1038 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1039 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1040 Constant *C = get(Ty->getContext(), NegZero);
1041
1042 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1043 return ConstantVector::getSplat(VTy->getElementCount(), C);
1044
1045 return C;
1046}
1047
1048
1049// ConstantFP accessors.
1050ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1051 LLVMContextImpl* pImpl = Context.pImpl;
1052
1053 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1054
1055 if (!Slot) {
1056 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1057 Slot.reset(new ConstantFP(Ty, V));
1058 }
1059
1060 return Slot.get();
1061}
1062
1063// Get a ConstantFP vector with each lane set to the same APFloat.
1064ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1065 const APFloat &V) {
1066 // Get an existing value or the insertion position.
1067 std::unique_ptr<ConstantFP> &Slot =
1068 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1069 if (!Slot) {
1070 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1071 VectorType *VTy = VectorType::get(EltTy, EC);
1072 Slot.reset(new ConstantFP(VTy, V));
1073 }
1074
1075#ifndef NDEBUG
1076 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1077 VectorType *VTy = VectorType::get(EltTy, EC);
1078 assert(Slot->getType() == VTy);
1079#endif
1080 return Slot.get();
1081}
1082
1084 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1085 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1086
1087 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1088 return ConstantVector::getSplat(VTy->getElementCount(), C);
1089
1090 return C;
1091}
1092
1093ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1094 : ConstantData(Ty, ConstantFPVal), Val(V) {
1095 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1096 "FP type Mismatch");
1097}
1098
1100 return Val.bitwiseIsEqual(V);
1101}
1102
1103/// Remove the constant from the constant table.
1104void ConstantFP::destroyConstantImpl() {
1105 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1106}
1107
1108//===----------------------------------------------------------------------===//
1109// ConstantAggregateZero Implementation
1110//===----------------------------------------------------------------------===//
1111
1113 if (auto *AT = dyn_cast<ArrayType>(getType()))
1114 return Constant::getNullValue(AT->getElementType());
1115 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1116}
1117
1119 return Constant::getNullValue(getType()->getStructElementType(Elt));
1120}
1121
1123 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1124 return getSequentialElement();
1125 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1126}
1127
1129 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1130 return getSequentialElement();
1131 return getStructElement(Idx);
1132}
1133
1135 Type *Ty = getType();
1136 if (auto *AT = dyn_cast<ArrayType>(Ty))
1137 return ElementCount::getFixed(AT->getNumElements());
1138 if (auto *VT = dyn_cast<VectorType>(Ty))
1139 return VT->getElementCount();
1141}
1142
1143//===----------------------------------------------------------------------===//
1144// UndefValue Implementation
1145//===----------------------------------------------------------------------===//
1146
1148 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1149 return UndefValue::get(ATy->getElementType());
1150 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1151}
1152
1154 return UndefValue::get(getType()->getStructElementType(Elt));
1155}
1156
1158 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1159 return getSequentialElement();
1160 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1161}
1162
1164 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1165 return getSequentialElement();
1166 return getStructElement(Idx);
1167}
1168
1170 Type *Ty = getType();
1171 if (auto *AT = dyn_cast<ArrayType>(Ty))
1172 return AT->getNumElements();
1173 if (auto *VT = dyn_cast<VectorType>(Ty))
1174 return cast<FixedVectorType>(VT)->getNumElements();
1175 return Ty->getStructNumElements();
1176}
1177
1178//===----------------------------------------------------------------------===//
1179// PoisonValue Implementation
1180//===----------------------------------------------------------------------===//
1181
1183 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1184 return PoisonValue::get(ATy->getElementType());
1185 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1186}
1187
1189 return PoisonValue::get(getType()->getStructElementType(Elt));
1190}
1191
1193 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1194 return getSequentialElement();
1195 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1196}
1197
1199 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1200 return getSequentialElement();
1201 return getStructElement(Idx);
1202}
1203
1204//===----------------------------------------------------------------------===//
1205// ConstantXXX Classes
1206//===----------------------------------------------------------------------===//
1207
1208template <typename ItTy, typename EltTy>
1209static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1210 for (; Start != End; ++Start)
1211 if (*Start != Elt)
1212 return false;
1213 return true;
1214}
1215
1216template <typename SequentialTy, typename ElementTy>
1218 assert(!V.empty() && "Cannot get empty int sequence.");
1219
1221 for (Constant *C : V)
1222 if (auto *CI = dyn_cast<ConstantInt>(C))
1223 Elts.push_back(CI->getZExtValue());
1224 else
1225 return nullptr;
1226 return SequentialTy::get(V[0]->getContext(), Elts);
1227}
1228
1229template <typename SequentialTy, typename ElementTy>
1231 assert(!V.empty() && "Cannot get empty FP sequence.");
1232
1234 for (Constant *C : V)
1235 if (auto *CFP = dyn_cast<ConstantFP>(C))
1236 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1237 else
1238 return nullptr;
1239 return SequentialTy::getFP(V[0]->getType(), Elts);
1240}
1241
1242template <typename SequenceTy>
1245 // We speculatively build the elements here even if it turns out that there is
1246 // a constantexpr or something else weird, since it is so uncommon for that to
1247 // happen.
1248 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1249 if (CI->getType()->isIntegerTy(8))
1250 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1251 else if (CI->getType()->isIntegerTy(16))
1252 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1253 else if (CI->getType()->isIntegerTy(32))
1254 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1255 else if (CI->getType()->isIntegerTy(64))
1256 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1257 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1258 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1259 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1260 else if (CFP->getType()->isFloatTy())
1261 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1262 else if (CFP->getType()->isDoubleTy())
1263 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1264 }
1265
1266 return nullptr;
1267}
1268
1271 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
1272 V.size()) {
1273 llvm::copy(V, op_begin());
1274
1275 // Check that types match, unless this is an opaque struct.
1276 if (auto *ST = dyn_cast<StructType>(T)) {
1277 if (ST->isOpaque())
1278 return;
1279 for (unsigned I = 0, E = V.size(); I != E; ++I)
1280 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1281 "Initializer for struct element doesn't match!");
1282 }
1283}
1284
1285ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
1286 : ConstantAggregate(T, ConstantArrayVal, V) {
1287 assert(V.size() == T->getNumElements() &&
1288 "Invalid initializer for constant array");
1289}
1290
1292 if (Constant *C = getImpl(Ty, V))
1293 return C;
1294 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1295}
1296
1297Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1298 // Empty arrays are canonicalized to ConstantAggregateZero.
1299 if (V.empty())
1300 return ConstantAggregateZero::get(Ty);
1301
1302 for (Constant *C : V) {
1303 assert(C->getType() == Ty->getElementType() &&
1304 "Wrong type in array element initializer");
1305 (void)C;
1306 }
1307
1308 // If this is an all-zero array, return a ConstantAggregateZero object. If
1309 // all undef, return an UndefValue, if "all simple", then return a
1310 // ConstantDataArray.
1311 Constant *C = V[0];
1312 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1313 return PoisonValue::get(Ty);
1314
1315 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1316 return UndefValue::get(Ty);
1317
1318 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1319 return ConstantAggregateZero::get(Ty);
1320
1321 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1322 // the element type is compatible with ConstantDataVector. If so, use it.
1324 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1325
1326 // Otherwise, we really do want to create a ConstantArray.
1327 return nullptr;
1328}
1329
1332 bool Packed) {
1333 unsigned VecSize = V.size();
1334 SmallVector<Type*, 16> EltTypes(VecSize);
1335 for (unsigned i = 0; i != VecSize; ++i)
1336 EltTypes[i] = V[i]->getType();
1337
1338 return StructType::get(Context, EltTypes, Packed);
1339}
1340
1341
1343 bool Packed) {
1344 assert(!V.empty() &&
1345 "ConstantStruct::getTypeForElements cannot be called on empty list");
1346 return getTypeForElements(V[0]->getContext(), V, Packed);
1347}
1348
1349ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1350 : ConstantAggregate(T, ConstantStructVal, V) {
1351 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1352 "Invalid initializer for constant struct");
1353}
1354
1355// ConstantStruct accessors.
1357 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1358 "Incorrect # elements specified to ConstantStruct::get");
1359
1360 // Create a ConstantAggregateZero value if all elements are zeros.
1361 bool isZero = true;
1362 bool isUndef = false;
1363 bool isPoison = false;
1364
1365 if (!V.empty()) {
1366 isUndef = isa<UndefValue>(V[0]);
1367 isPoison = isa<PoisonValue>(V[0]);
1368 isZero = V[0]->isNullValue();
1369 // PoisonValue inherits UndefValue, so its check is not necessary.
1370 if (isUndef || isZero) {
1371 for (Constant *C : V) {
1372 if (!C->isNullValue())
1373 isZero = false;
1374 if (!isa<PoisonValue>(C))
1375 isPoison = false;
1376 if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
1377 isUndef = false;
1378 }
1379 }
1380 }
1381 if (isZero)
1382 return ConstantAggregateZero::get(ST);
1383 if (isPoison)
1384 return PoisonValue::get(ST);
1385 if (isUndef)
1386 return UndefValue::get(ST);
1387
1388 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1389}
1390
1391ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1392 : ConstantAggregate(T, ConstantVectorVal, V) {
1393 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1394 "Invalid initializer for constant vector");
1395}
1396
1397// ConstantVector accessors.
1399 if (Constant *C = getImpl(V))
1400 return C;
1401 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1402 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1403}
1404
1405Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1406 assert(!V.empty() && "Vectors can't be empty");
1407 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1408
1409 // If this is an all-undef or all-zero vector, return a
1410 // ConstantAggregateZero or UndefValue.
1411 Constant *C = V[0];
1412 bool isZero = C->isNullValue();
1413 bool isUndef = isa<UndefValue>(C);
1414 bool isPoison = isa<PoisonValue>(C);
1415 bool isSplatFP = UseConstantFPForFixedLengthSplat && isa<ConstantFP>(C);
1416 bool isSplatInt = UseConstantIntForFixedLengthSplat && isa<ConstantInt>(C);
1417
1418 if (isZero || isUndef || isSplatFP || isSplatInt) {
1419 for (unsigned i = 1, e = V.size(); i != e; ++i)
1420 if (V[i] != C) {
1421 isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;
1422 break;
1423 }
1424 }
1425
1426 if (isZero)
1428 if (isPoison)
1429 return PoisonValue::get(T);
1430 if (isUndef)
1431 return UndefValue::get(T);
1432 if (isSplatFP)
1433 return ConstantFP::get(C->getContext(), T->getElementCount(),
1434 cast<ConstantFP>(C)->getValue());
1435 if (isSplatInt)
1436 return ConstantInt::get(C->getContext(), T->getElementCount(),
1437 cast<ConstantInt>(C)->getValue());
1438
1439 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1440 // the element type is compatible with ConstantDataVector. If so, use it.
1442 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1443
1444 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1445 // the operand list contains a ConstantExpr or something else strange.
1446 return nullptr;
1447}
1448
1450 if (!EC.isScalable()) {
1451 // Maintain special handling of zero.
1452 if (!V->isNullValue()) {
1453 if (UseConstantIntForFixedLengthSplat && isa<ConstantInt>(V))
1454 return ConstantInt::get(V->getContext(), EC,
1455 cast<ConstantInt>(V)->getValue());
1456 if (UseConstantFPForFixedLengthSplat && isa<ConstantFP>(V))
1457 return ConstantFP::get(V->getContext(), EC,
1458 cast<ConstantFP>(V)->getValue());
1459 }
1460
1461 // If this splat is compatible with ConstantDataVector, use it instead of
1462 // ConstantVector.
1463 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1465 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1466
1467 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1468 return get(Elts);
1469 }
1470
1471 // Maintain special handling of zero.
1472 if (!V->isNullValue()) {
1473 if (UseConstantIntForScalableSplat && isa<ConstantInt>(V))
1474 return ConstantInt::get(V->getContext(), EC,
1475 cast<ConstantInt>(V)->getValue());
1476 if (UseConstantFPForScalableSplat && isa<ConstantFP>(V))
1477 return ConstantFP::get(V->getContext(), EC,
1478 cast<ConstantFP>(V)->getValue());
1479 }
1480
1481 Type *VTy = VectorType::get(V->getType(), EC);
1482
1483 if (V->isNullValue())
1484 return ConstantAggregateZero::get(VTy);
1485 else if (isa<UndefValue>(V))
1486 return UndefValue::get(VTy);
1487
1488 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1489
1490 // Move scalar into vector.
1491 Constant *PoisonV = PoisonValue::get(VTy);
1492 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1493 // Build shuffle mask to perform the splat.
1494 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1495 // Splat.
1496 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1497}
1498
1500 LLVMContextImpl *pImpl = Context.pImpl;
1501 if (!pImpl->TheNoneToken)
1502 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1503 return pImpl->TheNoneToken.get();
1504}
1505
1506/// Remove the constant from the constant table.
1507void ConstantTokenNone::destroyConstantImpl() {
1508 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1509}
1510
1511// Utility function for determining if a ConstantExpr is a CastOp or not. This
1512// can't be inline because we don't want to #include Instruction.h into
1513// Constant.h
1516}
1517
1519 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1520}
1521
1523 return cast<CompareConstantExpr>(this)->predicate;
1524}
1525
1527 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1528}
1529
1531 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1532}
1533
1535 bool OnlyIfReduced, Type *SrcTy) const {
1536 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1537
1538 // If no operands changed return self.
1539 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1540 return const_cast<ConstantExpr*>(this);
1541
1542 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1543 switch (getOpcode()) {
1544 case Instruction::Trunc:
1545 case Instruction::ZExt:
1546 case Instruction::SExt:
1547 case Instruction::FPTrunc:
1548 case Instruction::FPExt:
1549 case Instruction::UIToFP:
1550 case Instruction::SIToFP:
1551 case Instruction::FPToUI:
1552 case Instruction::FPToSI:
1553 case Instruction::PtrToInt:
1554 case Instruction::IntToPtr:
1555 case Instruction::BitCast:
1556 case Instruction::AddrSpaceCast:
1557 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1558 case Instruction::InsertElement:
1559 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1560 OnlyIfReducedTy);
1561 case Instruction::ExtractElement:
1562 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1563 case Instruction::ShuffleVector:
1564 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1565 OnlyIfReducedTy);
1566 case Instruction::GetElementPtr: {
1567 auto *GEPO = cast<GEPOperator>(this);
1568 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1570 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1571 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1572 }
1573 case Instruction::ICmp:
1574 case Instruction::FCmp:
1575 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1576 OnlyIfReducedTy);
1577 default:
1578 assert(getNumOperands() == 2 && "Must be binary operator?");
1579 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1580 OnlyIfReducedTy);
1581 }
1582}
1583
1584
1585//===----------------------------------------------------------------------===//
1586// isValueValidForType implementations
1587
1589 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1590 if (Ty->isIntegerTy(1))
1591 return Val == 0 || Val == 1;
1592 return isUIntN(NumBits, Val);
1593}
1594
1596 unsigned NumBits = Ty->getIntegerBitWidth();
1597 if (Ty->isIntegerTy(1))
1598 return Val == 0 || Val == 1 || Val == -1;
1599 return isIntN(NumBits, Val);
1600}
1601
1603 // convert modifies in place, so make a copy.
1604 APFloat Val2 = APFloat(Val);
1605 bool losesInfo;
1606 switch (Ty->getTypeID()) {
1607 default:
1608 return false; // These can't be represented as floating point!
1609
1610 // FIXME rounding mode needs to be more flexible
1611 case Type::HalfTyID: {
1612 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1613 return true;
1615 return !losesInfo;
1616 }
1617 case Type::BFloatTyID: {
1618 if (&Val2.getSemantics() == &APFloat::BFloat())
1619 return true;
1621 return !losesInfo;
1622 }
1623 case Type::FloatTyID: {
1624 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1625 return true;
1627 return !losesInfo;
1628 }
1629 case Type::DoubleTyID: {
1630 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1631 &Val2.getSemantics() == &APFloat::BFloat() ||
1632 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1633 &Val2.getSemantics() == &APFloat::IEEEdouble())
1634 return true;
1636 return !losesInfo;
1637 }
1638 case Type::X86_FP80TyID:
1639 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1640 &Val2.getSemantics() == &APFloat::BFloat() ||
1641 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1642 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1644 case Type::FP128TyID:
1645 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1646 &Val2.getSemantics() == &APFloat::BFloat() ||
1647 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1648 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1649 &Val2.getSemantics() == &APFloat::IEEEquad();
1651 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1652 &Val2.getSemantics() == &APFloat::BFloat() ||
1653 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1654 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1656 }
1657}
1658
1659
1660//===----------------------------------------------------------------------===//
1661// Factory Function Implementation
1662
1664 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1665 "Cannot create an aggregate zero of non-aggregate type!");
1666
1667 std::unique_ptr<ConstantAggregateZero> &Entry =
1668 Ty->getContext().pImpl->CAZConstants[Ty];
1669 if (!Entry)
1670 Entry.reset(new ConstantAggregateZero(Ty));
1671
1672 return Entry.get();
1673}
1674
1675/// Remove the constant from the constant table.
1676void ConstantAggregateZero::destroyConstantImpl() {
1678}
1679
1680/// Remove the constant from the constant table.
1681void ConstantArray::destroyConstantImpl() {
1683}
1684
1685
1686//---- ConstantStruct::get() implementation...
1687//
1688
1689/// Remove the constant from the constant table.
1690void ConstantStruct::destroyConstantImpl() {
1692}
1693
1694/// Remove the constant from the constant table.
1695void ConstantVector::destroyConstantImpl() {
1697}
1698
1699Constant *Constant::getSplatValue(bool AllowUndefs) const {
1700 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1701 if (isa<ConstantAggregateZero>(this))
1702 return getNullValue(cast<VectorType>(getType())->getElementType());
1703 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1704 return CV->getSplatValue();
1705 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1706 return CV->getSplatValue(AllowUndefs);
1707
1708 // Check if this is a constant expression splat of the form returned by
1709 // ConstantVector::getSplat()
1710 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1711 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1712 isa<UndefValue>(Shuf->getOperand(1))) {
1713
1714 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1715 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1716 isa<UndefValue>(IElt->getOperand(0))) {
1717
1718 ArrayRef<int> Mask = Shuf->getShuffleMask();
1719 Constant *SplatVal = IElt->getOperand(1);
1720 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1721
1722 if (Index && Index->getValue() == 0 &&
1723 llvm::all_of(Mask, [](int I) { return I == 0; }))
1724 return SplatVal;
1725 }
1726 }
1727
1728 return nullptr;
1729}
1730
1731Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
1732 // Check out first element.
1733 Constant *Elt = getOperand(0);
1734 // Then make sure all remaining elements point to the same value.
1735 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1736 Constant *OpC = getOperand(I);
1737 if (OpC == Elt)
1738 continue;
1739
1740 // Strict mode: any mismatch is not a splat.
1741 if (!AllowUndefs)
1742 return nullptr;
1743
1744 // Allow undefs mode: ignore undefined elements.
1745 if (isa<UndefValue>(OpC))
1746 continue;
1747
1748 // If we do not have a defined element yet, use the current operand.
1749 if (isa<UndefValue>(Elt))
1750 Elt = OpC;
1751
1752 if (OpC != Elt)
1753 return nullptr;
1754 }
1755 return Elt;
1756}
1757
1759 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1760 return CI->getValue();
1761 // Scalable vectors can use a ConstantExpr to build a splat.
1762 if (isa<ConstantExpr>(this))
1763 return cast<ConstantInt>(this->getSplatValue())->getValue();
1764 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1765 // calling getSplatValue in release builds.
1766 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1767 const Constant *C = this->getAggregateElement(0U);
1768 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1769 return cast<ConstantInt>(C)->getValue();
1770}
1771
1772//---- ConstantPointerNull::get() implementation.
1773//
1774
1776 std::unique_ptr<ConstantPointerNull> &Entry =
1777 Ty->getContext().pImpl->CPNConstants[Ty];
1778 if (!Entry)
1779 Entry.reset(new ConstantPointerNull(Ty));
1780
1781 return Entry.get();
1782}
1783
1784/// Remove the constant from the constant table.
1785void ConstantPointerNull::destroyConstantImpl() {
1787}
1788
1789//---- ConstantTargetNone::get() implementation.
1790//
1791
1794 "Target extension type not allowed to have a zeroinitializer");
1795 std::unique_ptr<ConstantTargetNone> &Entry =
1796 Ty->getContext().pImpl->CTNConstants[Ty];
1797 if (!Entry)
1798 Entry.reset(new ConstantTargetNone(Ty));
1799
1800 return Entry.get();
1801}
1802
1803/// Remove the constant from the constant table.
1804void ConstantTargetNone::destroyConstantImpl() {
1806}
1807
1809 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1810 if (!Entry)
1811 Entry.reset(new UndefValue(Ty));
1812
1813 return Entry.get();
1814}
1815
1816/// Remove the constant from the constant table.
1817void UndefValue::destroyConstantImpl() {
1818 // Free the constant and any dangling references to it.
1819 if (getValueID() == UndefValueVal) {
1820 getContext().pImpl->UVConstants.erase(getType());
1821 } else if (getValueID() == PoisonValueVal) {
1822 getContext().pImpl->PVConstants.erase(getType());
1823 }
1824 llvm_unreachable("Not a undef or a poison!");
1825}
1826
1828 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1829 if (!Entry)
1830 Entry.reset(new PoisonValue(Ty));
1831
1832 return Entry.get();
1833}
1834
1835/// Remove the constant from the constant table.
1836void PoisonValue::destroyConstantImpl() {
1837 // Free the constant and any dangling references to it.
1838 getContext().pImpl->PVConstants.erase(getType());
1839}
1840
1842 assert(BB->getParent() && "Block must have a parent");
1843 return get(BB->getParent(), BB);
1844}
1845
1847 BlockAddress *&BA =
1848 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1849 if (!BA)
1850 BA = new BlockAddress(F, BB);
1851
1852 assert(BA->getFunction() == F && "Basic block moved between functions");
1853 return BA;
1854}
1855
1856BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1857 : Constant(PointerType::get(F->getContext(), F->getAddressSpace()),
1858 Value::BlockAddressVal, &Op<0>(), 2) {
1859 setOperand(0, F);
1860 setOperand(1, BB);
1861 BB->AdjustBlockAddressRefCount(1);
1862}
1863
1865 if (!BB->hasAddressTaken())
1866 return nullptr;
1867
1868 const Function *F = BB->getParent();
1869 assert(F && "Block must have a parent");
1870 BlockAddress *BA =
1871 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1872 assert(BA && "Refcount and block address map disagree!");
1873 return BA;
1874}
1875
1876/// Remove the constant from the constant table.
1877void BlockAddress::destroyConstantImpl() {
1879 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1880 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1881}
1882
1883Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1884 // This could be replacing either the Basic Block or the Function. In either
1885 // case, we have to remove the map entry.
1886 Function *NewF = getFunction();
1887 BasicBlock *NewBB = getBasicBlock();
1888
1889 if (From == NewF)
1890 NewF = cast<Function>(To->stripPointerCasts());
1891 else {
1892 assert(From == NewBB && "From does not match any operand");
1893 NewBB = cast<BasicBlock>(To);
1894 }
1895
1896 // See if the 'new' entry already exists, if not, just update this in place
1897 // and return early.
1898 BlockAddress *&NewBA =
1899 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1900 if (NewBA)
1901 return NewBA;
1902
1903 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1904
1905 // Remove the old entry, this can't cause the map to rehash (just a
1906 // tombstone will get added).
1907 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1908 getBasicBlock()));
1909 NewBA = this;
1910 setOperand(0, NewF);
1911 setOperand(1, NewBB);
1912 getBasicBlock()->AdjustBlockAddressRefCount(1);
1913
1914 // If we just want to keep the existing value, then return null.
1915 // Callers know that this means we shouldn't delete this value.
1916 return nullptr;
1917}
1918
1921 if (!Equiv)
1922 Equiv = new DSOLocalEquivalent(GV);
1923
1924 assert(Equiv->getGlobalValue() == GV &&
1925 "DSOLocalFunction does not match the expected global value");
1926 return Equiv;
1927}
1928
1929DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1930 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
1931 setOperand(0, GV);
1932}
1933
1934/// Remove the constant from the constant table.
1935void DSOLocalEquivalent::destroyConstantImpl() {
1936 const GlobalValue *GV = getGlobalValue();
1937 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1938}
1939
1940Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1941 assert(From == getGlobalValue() && "Changing value does not match operand.");
1942 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1943
1944 // The replacement is with another global value.
1945 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1946 DSOLocalEquivalent *&NewEquiv =
1948 if (NewEquiv)
1949 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1950 }
1951
1952 // If the argument is replaced with a null value, just replace this constant
1953 // with a null value.
1954 if (cast<Constant>(To)->isNullValue())
1955 return To;
1956
1957 // The replacement could be a bitcast or an alias to another function. We can
1958 // replace it with a bitcast to the dso_local_equivalent of that function.
1959 auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
1961 if (NewEquiv)
1962 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1963
1964 // Replace this with the new one.
1966 NewEquiv = this;
1967 setOperand(0, Func);
1968
1969 if (Func->getType() != getType()) {
1970 // It is ok to mutate the type here because this constant should always
1971 // reflect the type of the function it's holding.
1972 mutateType(Func->getType());
1973 }
1974 return nullptr;
1975}
1976
1978 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1979 if (!NC)
1980 NC = new NoCFIValue(GV);
1981
1982 assert(NC->getGlobalValue() == GV &&
1983 "NoCFIValue does not match the expected global value");
1984 return NC;
1985}
1986
1987NoCFIValue::NoCFIValue(GlobalValue *GV)
1988 : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1989 setOperand(0, GV);
1990}
1991
1992/// Remove the constant from the constant table.
1993void NoCFIValue::destroyConstantImpl() {
1994 const GlobalValue *GV = getGlobalValue();
1995 GV->getContext().pImpl->NoCFIValues.erase(GV);
1996}
1997
1998Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1999 assert(From == getGlobalValue() && "Changing value does not match operand.");
2000
2001 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2002 assert(GV && "Can only replace the operands with a global value");
2003
2004 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
2005 if (NewNC)
2006 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2007
2009 NewNC = this;
2010 setOperand(0, GV);
2011
2012 if (GV->getType() != getType())
2013 mutateType(GV->getType());
2014
2015 return nullptr;
2016}
2017
2018//---- ConstantExpr::get() implementations.
2019//
2020
2021/// This is a utility function to handle folding of casts and lookup of the
2022/// cast in the ExprConstants map. It is used by the various get* methods below.
2024 bool OnlyIfReduced = false) {
2025 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2026 // Fold a few common cases
2027 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2028 return FC;
2029
2030 if (OnlyIfReduced)
2031 return nullptr;
2032
2033 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2034
2035 // Look up the constant in the table first to ensure uniqueness.
2036 ConstantExprKeyType Key(opc, C);
2037
2038 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2039}
2040
2042 bool OnlyIfReduced) {
2044 assert(Instruction::isCast(opc) && "opcode out of range");
2046 "Cast opcode not supported as constant expression");
2047 assert(C && Ty && "Null arguments to getCast");
2048 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2049
2050 switch (opc) {
2051 default:
2052 llvm_unreachable("Invalid cast opcode");
2053 case Instruction::Trunc:
2054 return getTrunc(C, Ty, OnlyIfReduced);
2055 case Instruction::PtrToInt:
2056 return getPtrToInt(C, Ty, OnlyIfReduced);
2057 case Instruction::IntToPtr:
2058 return getIntToPtr(C, Ty, OnlyIfReduced);
2059 case Instruction::BitCast:
2060 return getBitCast(C, Ty, OnlyIfReduced);
2061 case Instruction::AddrSpaceCast:
2062 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2063 }
2064}
2065
2067 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2068 return getBitCast(C, Ty);
2069 return getTrunc(C, Ty);
2070}
2071
2073 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2074 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2075 "Invalid cast");
2076
2077 if (Ty->isIntOrIntVectorTy())
2078 return getPtrToInt(S, Ty);
2079
2080 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2081 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2082 return getAddrSpaceCast(S, Ty);
2083
2084 return getBitCast(S, Ty);
2085}
2086
2088 Type *Ty) {
2089 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2090 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2091
2093 return getAddrSpaceCast(S, Ty);
2094
2095 return getBitCast(S, Ty);
2096}
2097
2098Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2099#ifndef NDEBUG
2100 bool fromVec = isa<VectorType>(C->getType());
2101 bool toVec = isa<VectorType>(Ty);
2102#endif
2103 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2104 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2105 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2106 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2107 "SrcTy must be larger than DestTy for Trunc!");
2108
2109 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2110}
2111
2113 bool OnlyIfReduced) {
2114 assert(C->getType()->isPtrOrPtrVectorTy() &&
2115 "PtrToInt source must be pointer or pointer vector");
2116 assert(DstTy->isIntOrIntVectorTy() &&
2117 "PtrToInt destination must be integer or integer vector");
2118 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2119 if (isa<VectorType>(C->getType()))
2120 assert(cast<VectorType>(C->getType())->getElementCount() ==
2121 cast<VectorType>(DstTy)->getElementCount() &&
2122 "Invalid cast between a different number of vector elements");
2123 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2124}
2125
2127 bool OnlyIfReduced) {
2128 assert(C->getType()->isIntOrIntVectorTy() &&
2129 "IntToPtr source must be integer or integer vector");
2130 assert(DstTy->isPtrOrPtrVectorTy() &&
2131 "IntToPtr destination must be a pointer or pointer vector");
2132 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2133 if (isa<VectorType>(C->getType()))
2134 assert(cast<VectorType>(C->getType())->getElementCount() ==
2135 cast<VectorType>(DstTy)->getElementCount() &&
2136 "Invalid cast between a different number of vector elements");
2137 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2138}
2139
2141 bool OnlyIfReduced) {
2142 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2143 "Invalid constantexpr bitcast!");
2144
2145 // It is common to ask for a bitcast of a value to its own type, handle this
2146 // speedily.
2147 if (C->getType() == DstTy) return C;
2148
2149 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2150}
2151
2153 bool OnlyIfReduced) {
2154 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2155 "Invalid constantexpr addrspacecast!");
2156 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2157}
2158
2159Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2160 unsigned Flags, Type *OnlyIfReducedTy) {
2161 // Check the operands for consistency first.
2163 "Invalid opcode in binary constant expression");
2164 assert(isSupportedBinOp(Opcode) &&
2165 "Binop not supported as constant expression");
2166 assert(C1->getType() == C2->getType() &&
2167 "Operand types in binary constant expression should match");
2168
2169#ifndef NDEBUG
2170 switch (Opcode) {
2171 case Instruction::Add:
2172 case Instruction::Sub:
2173 case Instruction::Mul:
2175 "Tried to create an integer operation on a non-integer type!");
2176 break;
2177 case Instruction::And:
2178 case Instruction::Or:
2179 case Instruction::Xor:
2181 "Tried to create a logical operation on a non-integral type!");
2182 break;
2183 case Instruction::Shl:
2184 case Instruction::LShr:
2185 case Instruction::AShr:
2187 "Tried to create a shift operation on a non-integer type!");
2188 break;
2189 default:
2190 break;
2191 }
2192#endif
2193
2194 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2195 return FC;
2196
2197 if (OnlyIfReducedTy == C1->getType())
2198 return nullptr;
2199
2200 Constant *ArgVec[] = { C1, C2 };
2201 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2202
2203 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2204 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2205}
2206
2207bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2208 switch (Opcode) {
2209 case Instruction::UDiv:
2210 case Instruction::SDiv:
2211 case Instruction::URem:
2212 case Instruction::SRem:
2213 case Instruction::FAdd:
2214 case Instruction::FSub:
2215 case Instruction::FMul:
2216 case Instruction::FDiv:
2217 case Instruction::FRem:
2218 case Instruction::And:
2219 case Instruction::Or:
2220 case Instruction::LShr:
2221 case Instruction::AShr:
2222 return false;
2223 case Instruction::Add:
2224 case Instruction::Sub:
2225 case Instruction::Mul:
2226 case Instruction::Shl:
2227 case Instruction::Xor:
2228 return true;
2229 default:
2230 llvm_unreachable("Argument must be binop opcode");
2231 }
2232}
2233
2234bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2235 switch (Opcode) {
2236 case Instruction::UDiv:
2237 case Instruction::SDiv:
2238 case Instruction::URem:
2239 case Instruction::SRem:
2240 case Instruction::FAdd:
2241 case Instruction::FSub:
2242 case Instruction::FMul:
2243 case Instruction::FDiv:
2244 case Instruction::FRem:
2245 case Instruction::And:
2246 case Instruction::Or:
2247 case Instruction::LShr:
2248 case Instruction::AShr:
2249 return false;
2250 case Instruction::Add:
2251 case Instruction::Sub:
2252 case Instruction::Mul:
2253 case Instruction::Shl:
2254 case Instruction::Xor:
2255 return true;
2256 default:
2257 llvm_unreachable("Argument must be binop opcode");
2258 }
2259}
2260
2261bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2262 switch (Opcode) {
2263 case Instruction::ZExt:
2264 case Instruction::SExt:
2265 case Instruction::FPTrunc:
2266 case Instruction::FPExt:
2267 case Instruction::UIToFP:
2268 case Instruction::SIToFP:
2269 case Instruction::FPToUI:
2270 case Instruction::FPToSI:
2271 return false;
2272 case Instruction::Trunc:
2273 case Instruction::PtrToInt:
2274 case Instruction::IntToPtr:
2275 case Instruction::BitCast:
2276 case Instruction::AddrSpaceCast:
2277 return true;
2278 default:
2279 llvm_unreachable("Argument must be cast opcode");
2280 }
2281}
2282
2283bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2284 switch (Opcode) {
2285 case Instruction::ZExt:
2286 case Instruction::SExt:
2287 case Instruction::FPTrunc:
2288 case Instruction::FPExt:
2289 case Instruction::UIToFP:
2290 case Instruction::SIToFP:
2291 case Instruction::FPToUI:
2292 case Instruction::FPToSI:
2293 return false;
2294 case Instruction::Trunc:
2295 case Instruction::PtrToInt:
2296 case Instruction::IntToPtr:
2297 case Instruction::BitCast:
2298 case Instruction::AddrSpaceCast:
2299 return true;
2300 default:
2301 llvm_unreachable("Argument must be cast opcode");
2302 }
2303}
2304
2306 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2307 // Note that a non-inbounds gep is used, as null isn't within any object.
2308 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2311 return getPtrToInt(GEP,
2313}
2314
2316 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2317 // Note that a non-inbounds gep is used, as null isn't within any object.
2318 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2320 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2321 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2322 Constant *Indices[2] = { Zero, One };
2323 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2324 return getPtrToInt(GEP,
2326}
2327
2328Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
2329 Constant *C2, bool OnlyIfReduced) {
2330 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2331
2332 switch (Predicate) {
2333 default: llvm_unreachable("Invalid CmpInst predicate");
2339 case CmpInst::FCMP_TRUE:
2340 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2341
2345 case CmpInst::ICMP_SLE:
2346 return getICmp(Predicate, C1, C2, OnlyIfReduced);
2347 }
2348}
2349
2351 ArrayRef<Value *> Idxs, bool InBounds,
2352 std::optional<unsigned> InRangeIndex,
2353 Type *OnlyIfReducedTy) {
2354 assert(Ty && "Must specify element type");
2355 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2356
2357 if (Constant *FC =
2358 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2359 return FC; // Fold a few common cases.
2360
2362 "GEP indices invalid!");;
2363
2364 // Get the result type of the getelementptr!
2366 if (OnlyIfReducedTy == ReqTy)
2367 return nullptr;
2368
2369 auto EltCount = ElementCount::getFixed(0);
2370 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2371 EltCount = VecTy->getElementCount();
2372
2373 // Look up the constant in the table first to ensure uniqueness
2374 std::vector<Constant*> ArgVec;
2375 ArgVec.reserve(1 + Idxs.size());
2376 ArgVec.push_back(C);
2377 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2378 for (; GTI != GTE; ++GTI) {
2379 auto *Idx = cast<Constant>(GTI.getOperand());
2380 assert(
2381 (!isa<VectorType>(Idx->getType()) ||
2382 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2383 "getelementptr index type missmatch");
2384
2385 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2386 Idx = Idx->getSplatValue();
2387 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2388 !Idx->getType()->isVectorTy()) {
2389 Idx = ConstantVector::getSplat(EltCount, Idx);
2390 }
2391 ArgVec.push_back(Idx);
2392 }
2393
2394 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2395 if (InRangeIndex && *InRangeIndex < 63)
2396 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2397 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2398 SubClassOptionalData, std::nullopt, Ty);
2399
2400 LLVMContextImpl *pImpl = C->getContext().pImpl;
2401 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2402}
2403
2405 Constant *RHS, bool OnlyIfReduced) {
2406 auto Predicate = static_cast<CmpInst::Predicate>(pred);
2407 assert(LHS->getType() == RHS->getType());
2408 assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
2409
2410 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2411 return FC; // Fold a few common cases...
2412
2413 if (OnlyIfReduced)
2414 return nullptr;
2415
2416 // Look up the constant in the table first to ensure uniqueness
2417 Constant *ArgVec[] = { LHS, RHS };
2418 // Get the key type with both the opcode and predicate
2419 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
2420
2421 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2422 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2423 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2424
2426 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2427}
2428
2430 Constant *RHS, bool OnlyIfReduced) {
2431 auto Predicate = static_cast<CmpInst::Predicate>(pred);
2432 assert(LHS->getType() == RHS->getType());
2433 assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
2434
2435 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2436 return FC; // Fold a few common cases...
2437
2438 if (OnlyIfReduced)
2439 return nullptr;
2440
2441 // Look up the constant in the table first to ensure uniqueness
2442 Constant *ArgVec[] = { LHS, RHS };
2443 // Get the key type with both the opcode and predicate
2444 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
2445
2446 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2447 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2448 ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2449
2451 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2452}
2453
2455 Type *OnlyIfReducedTy) {
2456 assert(Val->getType()->isVectorTy() &&
2457 "Tried to create extractelement operation on non-vector type!");
2458 assert(Idx->getType()->isIntegerTy() &&
2459 "Extractelement index must be an integer type!");
2460
2462 return FC; // Fold a few common cases.
2463
2464 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2465 if (OnlyIfReducedTy == ReqTy)
2466 return nullptr;
2467
2468 // Look up the constant in the table first to ensure uniqueness
2469 Constant *ArgVec[] = { Val, Idx };
2470 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2471
2472 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2473 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2474}
2475
2477 Constant *Idx, Type *OnlyIfReducedTy) {
2478 assert(Val->getType()->isVectorTy() &&
2479 "Tried to create insertelement operation on non-vector type!");
2480 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2481 "Insertelement types must match!");
2482 assert(Idx->getType()->isIntegerTy() &&
2483 "Insertelement index must be i32 type!");
2484
2486 return FC; // Fold a few common cases.
2487
2488 if (OnlyIfReducedTy == Val->getType())
2489 return nullptr;
2490
2491 // Look up the constant in the table first to ensure uniqueness
2492 Constant *ArgVec[] = { Val, Elt, Idx };
2493 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2494
2495 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2496 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2497}
2498
2500 ArrayRef<int> Mask,
2501 Type *OnlyIfReducedTy) {
2503 "Invalid shuffle vector constant expr operands!");
2504
2505 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2506 return FC; // Fold a few common cases.
2507
2508 unsigned NElts = Mask.size();
2509 auto V1VTy = cast<VectorType>(V1->getType());
2510 Type *EltTy = V1VTy->getElementType();
2511 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2512 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2513
2514 if (OnlyIfReducedTy == ShufTy)
2515 return nullptr;
2516
2517 // Look up the constant in the table first to ensure uniqueness
2518 Constant *ArgVec[] = {V1, V2};
2519 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, Mask);
2520
2521 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2522 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2523}
2524
2525Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2526 assert(C->getType()->isIntOrIntVectorTy() &&
2527 "Cannot NEG a nonintegral value!");
2528 return getSub(ConstantInt::get(C->getType(), 0), C, HasNUW, HasNSW);
2529}
2530
2532 assert(C->getType()->isIntOrIntVectorTy() &&
2533 "Cannot NOT a nonintegral value!");
2534 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2535}
2536
2538 bool HasNUW, bool HasNSW) {
2539 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2541 return get(Instruction::Add, C1, C2, Flags);
2542}
2543
2545 bool HasNUW, bool HasNSW) {
2546 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2548 return get(Instruction::Sub, C1, C2, Flags);
2549}
2550
2552 bool HasNUW, bool HasNSW) {
2553 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2555 return get(Instruction::Mul, C1, C2, Flags);
2556}
2557
2559 return get(Instruction::Xor, C1, C2);
2560}
2561
2563 bool HasNUW, bool HasNSW) {
2564 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2566 return get(Instruction::Shl, C1, C2, Flags);
2567}
2568
2570 Type *Ty = C->getType();
2571 const APInt *IVal;
2572 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2573 return ConstantInt::get(Ty, IVal->logBase2());
2574
2575 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2576 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2577 if (!VecTy)
2578 return nullptr;
2579
2581 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2582 Constant *Elt = C->getAggregateElement(I);
2583 if (!Elt)
2584 return nullptr;
2585 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2586 if (isa<UndefValue>(Elt)) {
2588 continue;
2589 }
2590 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2591 return nullptr;
2592 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2593 }
2594
2595 return ConstantVector::get(Elts);
2596}
2597
2599 bool AllowRHSConstant, bool NSZ) {
2600 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2601
2602 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2603 if (Instruction::isCommutative(Opcode)) {
2604 switch (Opcode) {
2605 case Instruction::Add: // X + 0 = X
2606 case Instruction::Or: // X | 0 = X
2607 case Instruction::Xor: // X ^ 0 = X
2608 return Constant::getNullValue(Ty);
2609 case Instruction::Mul: // X * 1 = X
2610 return ConstantInt::get(Ty, 1);
2611 case Instruction::And: // X & -1 = X
2612 return Constant::getAllOnesValue(Ty);
2613 case Instruction::FAdd: // X + -0.0 = X
2614 return ConstantFP::getZero(Ty, !NSZ);
2615 case Instruction::FMul: // X * 1.0 = X
2616 return ConstantFP::get(Ty, 1.0);
2617 default:
2618 llvm_unreachable("Every commutative binop has an identity constant");
2619 }
2620 }
2621
2622 // Non-commutative opcodes: AllowRHSConstant must be set.
2623 if (!AllowRHSConstant)
2624 return nullptr;
2625
2626 switch (Opcode) {
2627 case Instruction::Sub: // X - 0 = X
2628 case Instruction::Shl: // X << 0 = X
2629 case Instruction::LShr: // X >>u 0 = X
2630 case Instruction::AShr: // X >> 0 = X
2631 case Instruction::FSub: // X - 0.0 = X
2632 return Constant::getNullValue(Ty);
2633 case Instruction::SDiv: // X / 1 = X
2634 case Instruction::UDiv: // X /u 1 = X
2635 return ConstantInt::get(Ty, 1);
2636 case Instruction::FDiv: // X / 1.0 = X
2637 return ConstantFP::get(Ty, 1.0);
2638 default:
2639 return nullptr;
2640 }
2641}
2642
2644 switch (ID) {
2645 case Intrinsic::umax:
2646 return Constant::getNullValue(Ty);
2647 case Intrinsic::umin:
2648 return Constant::getAllOnesValue(Ty);
2649 case Intrinsic::smax:
2652 case Intrinsic::smin:
2655 default:
2656 return nullptr;
2657 }
2658}
2659
2661 bool AllowRHSConstant, bool NSZ) {
2662 if (I->isBinaryOp())
2663 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2664 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2665 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2666 return nullptr;
2667}
2668
2670 switch (Opcode) {
2671 default:
2672 // Doesn't have an absorber.
2673 return nullptr;
2674
2675 case Instruction::Or:
2676 return Constant::getAllOnesValue(Ty);
2677
2678 case Instruction::And:
2679 case Instruction::Mul:
2680 return Constant::getNullValue(Ty);
2681 }
2682}
2683
2684/// Remove the constant from the constant table.
2685void ConstantExpr::destroyConstantImpl() {
2686 getType()->getContext().pImpl->ExprConstants.remove(this);
2687}
2688
2689const char *ConstantExpr::getOpcodeName() const {
2691}
2692
2693GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2694 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2695 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2697 (IdxList.size() + 1),
2698 IdxList.size() + 1),
2699 SrcElementTy(SrcElementTy),
2700 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2701 Op<0>() = C;
2702 Use *OperandList = getOperandList();
2703 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2704 OperandList[i+1] = IdxList[i];
2705}
2706
2708 return SrcElementTy;
2709}
2710
2712 return ResElementTy;
2713}
2714
2715//===----------------------------------------------------------------------===//
2716// ConstantData* implementations
2717
2719 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2720 return ATy->getElementType();
2721 return cast<VectorType>(getType())->getElementType();
2722}
2723
2725 return StringRef(DataElements, getNumElements()*getElementByteSize());
2726}
2727
2729 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2730 return true;
2731 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2732 switch (IT->getBitWidth()) {
2733 case 8:
2734 case 16:
2735 case 32:
2736 case 64:
2737 return true;
2738 default: break;
2739 }
2740 }
2741 return false;
2742}
2743
2745 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2746 return AT->getNumElements();
2747 return cast<FixedVectorType>(getType())->getNumElements();
2748}
2749
2750
2753}
2754
2755/// Return the start of the specified element.
2756const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2757 assert(Elt < getNumElements() && "Invalid Elt");
2758 return DataElements+Elt*getElementByteSize();
2759}
2760
2761
2762/// Return true if the array is empty or all zeros.
2763static bool isAllZeros(StringRef Arr) {
2764 for (char I : Arr)
2765 if (I != 0)
2766 return false;
2767 return true;
2768}
2769
2770/// This is the underlying implementation of all of the
2771/// ConstantDataSequential::get methods. They all thunk down to here, providing
2772/// the correct element type. We take the bytes in as a StringRef because
2773/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2775#ifndef NDEBUG
2776 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2777 assert(isElementTypeCompatible(ATy->getElementType()));
2778 else
2779 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2780#endif
2781 // If the elements are all zero or there are no elements, return a CAZ, which
2782 // is more dense and canonical.
2783 if (isAllZeros(Elements))
2784 return ConstantAggregateZero::get(Ty);
2785
2786 // Do a lookup to see if we have already formed one of these.
2787 auto &Slot =
2788 *Ty->getContext()
2789 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2790 .first;
2791
2792 // The bucket can point to a linked list of different CDS's that have the same
2793 // body but different types. For example, 0,0,0,1 could be a 4 element array
2794 // of i8, or a 1-element array of i32. They'll both end up in the same
2795 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2796 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2797 for (; *Entry; Entry = &(*Entry)->Next)
2798 if ((*Entry)->getType() == Ty)
2799 return Entry->get();
2800
2801 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2802 // and return it.
2803 if (isa<ArrayType>(Ty)) {
2804 // Use reset because std::make_unique can't access the constructor.
2805 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2806 return Entry->get();
2807 }
2808
2809 assert(isa<VectorType>(Ty));
2810 // Use reset because std::make_unique can't access the constructor.
2811 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2812 return Entry->get();
2813}
2814
2815void ConstantDataSequential::destroyConstantImpl() {
2816 // Remove the constant from the StringMap.
2819
2820 auto Slot = CDSConstants.find(getRawDataValues());
2821
2822 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2823
2824 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2825
2826 // Remove the entry from the hash table.
2827 if (!(*Entry)->Next) {
2828 // If there is only one value in the bucket (common case) it must be this
2829 // entry, and removing the entry should remove the bucket completely.
2830 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2831 getContext().pImpl->CDSConstants.erase(Slot);
2832 return;
2833 }
2834
2835 // Otherwise, there are multiple entries linked off the bucket, unlink the
2836 // node we care about but keep the bucket around.
2837 while (true) {
2838 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2839 assert(Node && "Didn't find entry in its uniquing hash table!");
2840 // If we found our entry, unlink it from the list and we're done.
2841 if (Node.get() == this) {
2842 Node = std::move(Node->Next);
2843 return;
2844 }
2845
2846 Entry = &Node->Next;
2847 }
2848}
2849
2850/// getFP() constructors - Return a constant of array type with a float
2851/// element type taken from argument `ElementType', and count taken from
2852/// argument `Elts'. The amount of bits of the contained type must match the
2853/// number of bits of the type contained in the passed in ArrayRef.
2854/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2855/// that this can return a ConstantAggregateZero object.
2857 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2858 "Element type is not a 16-bit float type");
2859 Type *Ty = ArrayType::get(ElementType, Elts.size());
2860 const char *Data = reinterpret_cast<const char *>(Elts.data());
2861 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2862}
2864 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2865 Type *Ty = ArrayType::get(ElementType, Elts.size());
2866 const char *Data = reinterpret_cast<const char *>(Elts.data());
2867 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2868}
2870 assert(ElementType->isDoubleTy() &&
2871 "Element type is not a 64-bit float type");
2872 Type *Ty = ArrayType::get(ElementType, Elts.size());
2873 const char *Data = reinterpret_cast<const char *>(Elts.data());
2874 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2875}
2876
2878 StringRef Str, bool AddNull) {
2879 if (!AddNull) {
2880 const uint8_t *Data = Str.bytes_begin();
2881 return get(Context, ArrayRef(Data, Str.size()));
2882 }
2883
2884 SmallVector<uint8_t, 64> ElementVals;
2885 ElementVals.append(Str.begin(), Str.end());
2886 ElementVals.push_back(0);
2887 return get(Context, ElementVals);
2888}
2889
2890/// get() constructors - Return a constant with vector type with an element
2891/// count and element type matching the ArrayRef passed in. Note that this
2892/// can return a ConstantAggregateZero object.
2894 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
2895 const char *Data = reinterpret_cast<const char *>(Elts.data());
2896 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2897}
2900 const char *Data = reinterpret_cast<const char *>(Elts.data());
2901 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2902}
2905 const char *Data = reinterpret_cast<const char *>(Elts.data());
2906 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2907}
2910 const char *Data = reinterpret_cast<const char *>(Elts.data());
2911 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2912}
2915 const char *Data = reinterpret_cast<const char *>(Elts.data());
2916 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2917}
2920 const char *Data = reinterpret_cast<const char *>(Elts.data());
2921 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2922}
2923
2924/// getFP() constructors - Return a constant of vector type with a float
2925/// element type taken from argument `ElementType', and count taken from
2926/// argument `Elts'. The amount of bits of the contained type must match the
2927/// number of bits of the type contained in the passed in ArrayRef.
2928/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2929/// that this can return a ConstantAggregateZero object.
2931 ArrayRef<uint16_t> Elts) {
2932 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2933 "Element type is not a 16-bit float type");
2934 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2935 const char *Data = reinterpret_cast<const char *>(Elts.data());
2936 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2937}
2939 ArrayRef<uint32_t> Elts) {
2940 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2941 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2942 const char *Data = reinterpret_cast<const char *>(Elts.data());
2943 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2944}
2946 ArrayRef<uint64_t> Elts) {
2947 assert(ElementType->isDoubleTy() &&
2948 "Element type is not a 64-bit float type");
2949 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2950 const char *Data = reinterpret_cast<const char *>(Elts.data());
2951 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2952}
2953
2955 assert(isElementTypeCompatible(V->getType()) &&
2956 "Element type not compatible with ConstantData");
2957 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2958 if (CI->getType()->isIntegerTy(8)) {
2959 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2960 return get(V->getContext(), Elts);
2961 }
2962 if (CI->getType()->isIntegerTy(16)) {
2963 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2964 return get(V->getContext(), Elts);
2965 }
2966 if (CI->getType()->isIntegerTy(32)) {
2967 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2968 return get(V->getContext(), Elts);
2969 }
2970 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2971 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2972 return get(V->getContext(), Elts);
2973 }
2974
2975 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2976 if (CFP->getType()->isHalfTy()) {
2978 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2979 return getFP(V->getType(), Elts);
2980 }
2981 if (CFP->getType()->isBFloatTy()) {
2983 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2984 return getFP(V->getType(), Elts);
2985 }
2986 if (CFP->getType()->isFloatTy()) {
2988 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2989 return getFP(V->getType(), Elts);
2990 }
2991 if (CFP->getType()->isDoubleTy()) {
2993 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2994 return getFP(V->getType(), Elts);
2995 }
2996 }
2998}
2999
3000
3002 assert(isa<IntegerType>(getElementType()) &&
3003 "Accessor can only be used when element is an integer");
3004 const char *EltPtr = getElementPointer(Elt);
3005
3006 // The data is stored in host byte order, make sure to cast back to the right
3007 // type to load with the right endianness.
3008 switch (getElementType()->getIntegerBitWidth()) {
3009 default: llvm_unreachable("Invalid bitwidth for CDS");
3010 case 8:
3011 return *reinterpret_cast<const uint8_t *>(EltPtr);
3012 case 16:
3013 return *reinterpret_cast<const uint16_t *>(EltPtr);
3014 case 32:
3015 return *reinterpret_cast<const uint32_t *>(EltPtr);
3016 case 64:
3017 return *reinterpret_cast<const uint64_t *>(EltPtr);
3018 }
3019}
3020
3022 assert(isa<IntegerType>(getElementType()) &&
3023 "Accessor can only be used when element is an integer");
3024 const char *EltPtr = getElementPointer(Elt);
3025
3026 // The data is stored in host byte order, make sure to cast back to the right
3027 // type to load with the right endianness.
3028 switch (getElementType()->getIntegerBitWidth()) {
3029 default: llvm_unreachable("Invalid bitwidth for CDS");
3030 case 8: {
3031 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3032 return APInt(8, EltVal);
3033 }
3034 case 16: {
3035 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3036 return APInt(16, EltVal);
3037 }
3038 case 32: {
3039 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3040 return APInt(32, EltVal);
3041 }
3042 case 64: {
3043 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3044 return APInt(64, EltVal);
3045 }
3046 }
3047}
3048
3050 const char *EltPtr = getElementPointer(Elt);
3051
3052 switch (getElementType()->getTypeID()) {
3053 default:
3054 llvm_unreachable("Accessor can only be used when element is float/double!");
3055 case Type::HalfTyID: {
3056 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3057 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3058 }
3059 case Type::BFloatTyID: {
3060 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3061 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3062 }
3063 case Type::FloatTyID: {
3064 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3065 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3066 }
3067 case Type::DoubleTyID: {
3068 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3069 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3070 }
3071 }
3072}
3073
3075 assert(getElementType()->isFloatTy() &&
3076 "Accessor can only be used when element is a 'float'");
3077 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3078}
3079
3081 assert(getElementType()->isDoubleTy() &&
3082 "Accessor can only be used when element is a 'float'");
3083 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3084}
3085
3087 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3088 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3089 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3090
3091 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3092}
3093
3094bool ConstantDataSequential::isString(unsigned CharSize) const {
3095 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3096}
3097
3099 if (!isString())
3100 return false;
3101
3102 StringRef Str = getAsString();
3103
3104 // The last value must be nul.
3105 if (Str.back() != 0) return false;
3106
3107 // Other elements must be non-nul.
3108 return !Str.drop_back().contains(0);
3109}
3110
3111bool ConstantDataVector::isSplatData() const {
3112 const char *Base = getRawDataValues().data();
3113
3114 // Compare elements 1+ to the 0'th element.
3115 unsigned EltSize = getElementByteSize();
3116 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3117 if (memcmp(Base, Base+i*EltSize, EltSize))
3118 return false;
3119
3120 return true;
3121}
3122
3124 if (!IsSplatSet) {
3125 IsSplatSet = true;
3126 IsSplat = isSplatData();
3127 }
3128 return IsSplat;
3129}
3130
3132 // If they're all the same, return the 0th one as a representative.
3133 return isSplat() ? getElementAsConstant(0) : nullptr;
3134}
3135
3136//===----------------------------------------------------------------------===//
3137// handleOperandChange implementations
3138
3139/// Update this constant array to change uses of
3140/// 'From' to be uses of 'To'. This must update the uniquing data structures
3141/// etc.
3142///
3143/// Note that we intentionally replace all uses of From with To here. Consider
3144/// a large array that uses 'From' 1000 times. By handling this case all here,
3145/// ConstantArray::handleOperandChange is only invoked once, and that
3146/// single invocation handles all 1000 uses. Handling them one at a time would
3147/// work, but would be really slow because it would have to unique each updated
3148/// array instance.
3149///
3151 Value *Replacement = nullptr;
3152 switch (getValueID()) {
3153 default:
3154 llvm_unreachable("Not a constant!");
3155#define HANDLE_CONSTANT(Name) \
3156 case Value::Name##Val: \
3157 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3158 break;
3159#include "llvm/IR/Value.def"
3160 }
3161
3162 // If handleOperandChangeImpl returned nullptr, then it handled
3163 // replacing itself and we don't want to delete or replace anything else here.
3164 if (!Replacement)
3165 return;
3166
3167 // I do need to replace this with an existing value.
3168 assert(Replacement != this && "I didn't contain From!");
3169
3170 // Everyone using this now uses the replacement.
3171 replaceAllUsesWith(Replacement);
3172
3173 // Delete the old constant!
3175}
3176
3177Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3178 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3179 Constant *ToC = cast<Constant>(To);
3180
3182 Values.reserve(getNumOperands()); // Build replacement array.
3183
3184 // Fill values with the modified operands of the constant array. Also,
3185 // compute whether this turns into an all-zeros array.
3186 unsigned NumUpdated = 0;
3187
3188 // Keep track of whether all the values in the array are "ToC".
3189 bool AllSame = true;
3190 Use *OperandList = getOperandList();
3191 unsigned OperandNo = 0;
3192 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3193 Constant *Val = cast<Constant>(O->get());
3194 if (Val == From) {
3195 OperandNo = (O - OperandList);
3196 Val = ToC;
3197 ++NumUpdated;
3198 }
3199 Values.push_back(Val);
3200 AllSame &= Val == ToC;
3201 }
3202
3203 if (AllSame && ToC->isNullValue())
3205
3206 if (AllSame && isa<UndefValue>(ToC))
3207 return UndefValue::get(getType());
3208
3209 // Check for any other type of constant-folding.
3210 if (Constant *C = getImpl(getType(), Values))
3211 return C;
3212
3213 // Update to the new value.
3215 Values, this, From, ToC, NumUpdated, OperandNo);
3216}
3217
3218Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3219 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3220 Constant *ToC = cast<Constant>(To);
3221
3222 Use *OperandList = getOperandList();
3223
3225 Values.reserve(getNumOperands()); // Build replacement struct.
3226
3227 // Fill values with the modified operands of the constant struct. Also,
3228 // compute whether this turns into an all-zeros struct.
3229 unsigned NumUpdated = 0;
3230 bool AllSame = true;
3231 unsigned OperandNo = 0;
3232 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3233 Constant *Val = cast<Constant>(O->get());
3234 if (Val == From) {
3235 OperandNo = (O - OperandList);
3236 Val = ToC;
3237 ++NumUpdated;
3238 }
3239 Values.push_back(Val);
3240 AllSame &= Val == ToC;
3241 }
3242
3243 if (AllSame && ToC->isNullValue())
3245
3246 if (AllSame && isa<UndefValue>(ToC))
3247 return UndefValue::get(getType());
3248
3249 // Update to the new value.
3251 Values, this, From, ToC, NumUpdated, OperandNo);
3252}
3253
3254Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3255 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3256 Constant *ToC = cast<Constant>(To);
3257
3259 Values.reserve(getNumOperands()); // Build replacement array...
3260 unsigned NumUpdated = 0;
3261 unsigned OperandNo = 0;
3262 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3263 Constant *Val = getOperand(i);
3264 if (Val == From) {
3265 OperandNo = i;
3266 ++NumUpdated;
3267 Val = ToC;
3268 }
3269 Values.push_back(Val);
3270 }
3271
3272 if (Constant *C = getImpl(Values))
3273 return C;
3274
3275 // Update to the new value.
3277 Values, this, From, ToC, NumUpdated, OperandNo);
3278}
3279
3280Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3281 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3282 Constant *To = cast<Constant>(ToV);
3283
3285 unsigned NumUpdated = 0;
3286 unsigned OperandNo = 0;
3287 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3288 Constant *Op = getOperand(i);
3289 if (Op == From) {
3290 OperandNo = i;
3291 ++NumUpdated;
3292 Op = To;
3293 }
3294 NewOps.push_back(Op);
3295 }
3296 assert(NumUpdated && "I didn't contain From!");
3297
3298 if (Constant *C = getWithOperands(NewOps, getType(), true))
3299 return C;
3300
3301 // Update to the new value.
3302 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3303 NewOps, this, From, To, NumUpdated, OperandNo);
3304}
3305
3307 SmallVector<Value *, 4> ValueOperands(operands());
3308 ArrayRef<Value*> Ops(ValueOperands);
3309
3310 switch (getOpcode()) {
3311 case Instruction::Trunc:
3312 case Instruction::ZExt:
3313 case Instruction::SExt:
3314 case Instruction::FPTrunc:
3315 case Instruction::FPExt:
3316 case Instruction::UIToFP:
3317 case Instruction::SIToFP:
3318 case Instruction::FPToUI:
3319 case Instruction::FPToSI:
3320 case Instruction::PtrToInt:
3321 case Instruction::IntToPtr:
3322 case Instruction::BitCast:
3323 case Instruction::AddrSpaceCast:
3325 getType(), "", InsertBefore);
3326 case Instruction::InsertElement:
3327 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3328 case Instruction::ExtractElement:
3329 return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
3330 case Instruction::ShuffleVector:
3331 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
3332 InsertBefore);
3333
3334 case Instruction::GetElementPtr: {
3335 const auto *GO = cast<GEPOperator>(this);
3336 if (GO->isInBounds())
3338 GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
3339 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3340 Ops.slice(1), "", InsertBefore);
3341 }
3342 case Instruction::ICmp:
3343 case Instruction::FCmp:
3345 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
3346 "", InsertBefore);
3347 default:
3348 assert(getNumOperands() == 2 && "Must be binary operator?");
3350 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
3351 if (isa<OverflowingBinaryOperator>(BO)) {
3356 }
3357 if (isa<PossiblyExactOperator>(BO))
3359 return BO;
3360 }
3361}
This file defines the StringMap class.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
BlockVerifier::State From
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
Definition: Constants.cpp:2763
static cl::opt< bool > UseConstantIntForScalableSplat("use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantInt's native scalable vector splat support."))
static cl::opt< bool > UseConstantIntForFixedLengthSplat("use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantInt's native fixed-length vector splat support."))
static Constant * getFPSequenceIfElementsMatch(ArrayRef< Constant * > V)
Definition: Constants.cpp:1230
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt)
Definition: Constants.cpp:1209
static Constant * getIntSequenceIfElementsMatch(ArrayRef< Constant * > V)
Definition: Constants.cpp:1217
static Constant * getSequenceIfElementsMatch(Constant *C, ArrayRef< Constant * > V)
Definition: Constants.cpp:1243
static bool ConstHasGlobalValuePredicate(const Constant *C, bool(*Predicate)(const GlobalValue *))
Check if C contains a GlobalValue for which Predicate is true.
Definition: Constants.cpp:584
static cl::opt< bool > UseConstantFPForScalableSplat("use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantFP's native scalable vector splat support."))
static bool constantIsDead(const Constant *C, bool RemoveDeadUsers)
Return true if the specified constantexpr is dead.
Definition: Constants.cpp:693
static bool containsUndefinedElement(const Constant *C, function_ref< bool(const Constant *)> HasFn)
Definition: Constants.cpp:323
static Constant * getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is a utility function to handle folding of casts and lookup of the cast in the ExprConstants map...
Definition: Constants.cpp:2023
static cl::opt< bool > UseConstantFPForFixedLengthSplat("use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantFP's native fixed-length vector splat support."))
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
bool End
Definition: ELF_riscv.cpp:480
static Function * getFunction(Constant *C)
Definition: Evaluator.cpp:236
static bool isSigned(unsigned int Opcode)
static char getTypeID(Type *Ty)
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
hexagon gen pred
static bool isUndef(ArrayRef< int > Mask)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:531
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:911
LLVMContext & Context
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
Value * RHS
Value * LHS
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:988
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:996
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:5196
bool bitwiseIsEqual(const APFloat &RHS) const
Definition: APFloat.h:1260
static APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition: APFloat.cpp:5221
const fltSemantics & getSemantics() const
Definition: APFloat.h:1303
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition: APFloat.h:966
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition: APFloat.h:977
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:957
Class for arbitrary precision integers.
Definition: APInt.h:76
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:212
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:187
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
unsigned logBase2() const
Definition: APInt.h:1703
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:418
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
const T * data() const
Definition: ArrayRef.h:162
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:195
Class to represent array types.
Definition: DerivedTypes.h:371
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
Type * getElementType() const
Definition: DerivedTypes.h:384
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:639
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:205
BinaryConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to impleme...
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
The address of a basic block.
Definition: Constants.h:888
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1864
Function * getFunction() const
Definition: Constants.h:916
BasicBlock * getBasicBlock() const
Definition: Constants.h:917
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1846
CastConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to implement...
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:965
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:968
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:982
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:994
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:995
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:971
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:980
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:969
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:970
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:989
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:988
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:992
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:979
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:973
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:976
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:990
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:977
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:972
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:974
@ ICMP_EQ
equal
Definition: InstrTypes.h:986
@ ICMP_NE
not equal
Definition: InstrTypes.h:987
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:993
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:981
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:991
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:978
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:967
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:975
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
Definition: InstrTypes.h:1083
bool isIntPredicate() const
Definition: InstrTypes.h:1084
All zero aggregate value.
Definition: Constants.h:349
ElementCount getElementCount() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:1134
Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
Definition: Constants.cpp:1112
Constant * getElementValue(Constant *C) const
Return a zero of the right value for the specified GEP index if we can, otherwise return null (e....
Definition: Constants.cpp:1122
Constant * getStructElement(unsigned Elt) const
If this CAZ has struct type, return a zero with the right element type for the specified element.
Definition: Constants.cpp:1118
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1663
Base class for aggregate constants (with operands).
Definition: Constants.h:398
ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V)
Definition: Constants.cpp:1269
ConstantArray - Constant Array Declarations.
Definition: Constants.h:422
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1291
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:441
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:691
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2877
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:704
static Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
Definition: Constants.cpp:2856
APInt getElementAsAPInt(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element as an APInt...
Definition: Constants.cpp:3021
double getElementAsDouble(unsigned i) const
If this is an sequential container of doubles, return the specified element as a double.
Definition: Constants.cpp:3080
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition: Constants.h:657
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2751
float getElementAsFloat(unsigned i) const
If this is an sequential container of floats, return the specified element as a float.
Definition: Constants.cpp:3074
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:3094
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:3001
static Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
Definition: Constants.cpp:2774
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2744
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index's element.
Definition: Constants.cpp:3086
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2718
bool isCString() const
This method returns true if the array "isString", ends with a null byte, and does not contains any ot...
Definition: Constants.cpp:3098
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
Definition: Constants.cpp:3049
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2724
static bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
Definition: Constants.cpp:2728
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:765
Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value,...
Definition: Constants.cpp:3131
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2954
bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value.
Definition: Constants.cpp:3123
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
Definition: Constants.cpp:2893
static Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
Definition: Constants.cpp:2930
Base class for constants with no operands.
Definition: Constants.h:51
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1016
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2429
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2126
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2454
static Constant * getAlignOf(Type *Ty)
getAlignOf constant expr - computes the alignment of a type in a target independent way (Note: the re...
Definition: Constants.cpp:2315
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2072
static Constant * getTruncOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:2066
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2087
bool isCast() const
Return true if this is a convert constant expression.
Definition: Constants.cpp:1514
static Constant * getIdentity(Instruction *I, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary or intrinsic Instruction.
Definition: Constants.cpp:2660
static bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
Definition: Constants.cpp:2261
Constant * getShuffleMaskForBitcode() const
Assert that this is a shufflevector and return the mask.
Definition: Constants.cpp:1530
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:2041
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2544
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2531
const char * getOpcodeName() const
Return a string representation for an opcode.
Definition: Constants.cpp:2689
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2476
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2112
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2404
Instruction * getAsInstruction(Instruction *InsertBefore=nullptr) const
Returns an Instruction which implements the same operation as this ConstantExpr.
Definition: Constants.cpp:3306
bool isCompare() const
Return true if this is a compare constant expression.
Definition: Constants.cpp:1518
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2499
static Constant * getSizeOf(Type *Ty)
getSizeOf constant expr - computes the (alloc) size of a type (in address-units, not bits) in a targe...
Definition: Constants.cpp:2305
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition: Constants.h:1317
static Constant * getIntrinsicIdentity(Intrinsic::ID, Type *Ty)
Definition: Constants.cpp:2643
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1201
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2558
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
Definition: Constants.cpp:2669
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2551
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2562
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
Definition: Constants.cpp:2159
static bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
Definition: Constants.cpp:2207
unsigned getPredicate() const
Return the ICMP or FCMP predicate value.
Definition: Constants.cpp:1522
ArrayRef< int > getShuffleMask() const
Assert that this is a shufflevector and return the mask.
Definition: Constants.cpp:1526
static bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
Definition: Constants.cpp:2234
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2152
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1252
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2537
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2140
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2598
static bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
Definition: Constants.cpp:2283
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2098
static Constant * getExactLogBase2(Constant *C)
If C is a scalar/fixed width vector of known powers of 2, then this function returns a new scalar/fix...
Definition: Constants.cpp:2569
Constant * getWithOperands(ArrayRef< Constant * > Ops) const
This returns the current constant expression with the operands replaced with the specified values.
Definition: Constants.h:1274
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2525
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Definition: Constants.cpp:2328
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:267
static Constant * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:1026
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1083
static Constant * getZero(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1037
static Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
Definition: Constants.cpp:1004
bool isExactlyValue(const APFloat &V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: Constants.cpp:1099
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1602
static Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:1015
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V.
Definition: Constants.cpp:1588
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:856
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:863
A constant pointer value that points to null.
Definition: Constants.h:547
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1775
PointerType * getType() const
Specialize the getType() method to always return an PointerType, which reduces the amount of casting ...
Definition: Constants.h:563
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1356
static StructType * getTypeForElements(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct type to use for a constant with the specified set of elements.
Definition: Constants.cpp:1342
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:493
A constant target extension type default initializer.
Definition: Constants.h:860
static ConstantTargetNone * get(TargetExtType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1792
TargetExtType * getType() const
Specialize the getType() method to always return an TargetExtType, which reduces the amount of castin...
Definition: Constants.h:876
A constant token which is empty.
Definition: Constants.h:839
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Definition: Constants.cpp:1499
ConstantClass * getOrCreate(TypeClass *Ty, ValType V)
Return the specified constant from the map, creating it if necessary.
void remove(ConstantClass *CP)
Remove this constant from the map.
ConstantClass * replaceOperandsInPlace(ArrayRef< Constant * > Operands, ConstantClass *CP, Value *From, Constant *To, unsigned NumUpdated=0, unsigned OperandNo=~0u)
Constant Vector Declarations.
Definition: Constants.h:506
Constant * getSplatValue(bool AllowUndefs=false) const
If all elements of the vector constant have the same value, return that value.
Definition: Constants.cpp:1731
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition: Constants.h:529
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1449
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:400
bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
Definition: Constants.cpp:256
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
Definition: Constants.cpp:767
bool containsUndefElement() const
Return true if this is a vector constant that includes any strictly undef (not poison) elements.
Definition: Constants.cpp:354
Constant * getSplatValue(bool AllowUndefs=false) const
If all elements of the vector constant have the same value, return that value.
Definition: Constants.cpp:1699
static Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
Definition: Constants.cpp:791
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
bool hasZeroLiveUses() const
Return true if the constant has no live uses.
Definition: Constants.cpp:751
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:124
bool isManifestConstant() const
Return true if a constant is ConstantData or a ConstantAggregate or ConstantExpr that contain only Co...
Definition: Constants.cpp:826
bool isNegativeZeroValue() const
Return true if the value is what would be returned by getZeroValueForNegation.
Definition: Constants.cpp:56
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:107
bool hasOneLiveUse() const
Return true if the constant has exactly one live use.
Definition: Constants.cpp:749
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry (eith...
Definition: Constants.cpp:637
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
Definition: Constants.cpp:614
const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
Definition: Constants.cpp:1758
bool containsConstantExpression() const
Return true if this is a fixed width vector constant that includes any constant expressions.
Definition: Constants.cpp:360
bool isFiniteNonZeroFP() const
Return true if this is a finite and non-zero floating-point scalar constant or a fixed width vector c...
Definition: Constants.cpp:214
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:722
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
Definition: Constants.cpp:235
bool needsDynamicRelocation() const
Definition: Constants.cpp:633
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isNaN() const
Return true if this is a floating-point NaN constant or a vector floating-point constant with all NaN...
Definition: Constants.cpp:277
bool isMinSignedValue() const
Return true if the value is the smallest signed value.
Definition: Constants.cpp:169
bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things.
Definition: Constants.cpp:621
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:432
bool isThreadDependent() const
Return true if the value can vary between threads.
Definition: Constants.cpp:607
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:76
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:472
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
Definition: Constants.cpp:186
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
bool isNotOneValue() const
Return true if the value is not the one value, or, for vectors, does not contain one value elements.
Definition: Constants.cpp:141
bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
Definition: Constants.cpp:298
bool containsUndefOrPoisonElement() const
Return true if this is a vector constant that includes any undef or poison elements.
Definition: Constants.cpp:344
bool containsPoisonElement() const
Return true if this is a vector constant that includes any poison elements.
Definition: Constants.cpp:349
void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Definition: Constants.cpp:3150
Wrapper for a function that represents a value that functionally represents the original function.
Definition: Constants.h:934
GlobalValue * getGlobalValue() const
Definition: Constants.h:953
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1919
This class represents an Operation in the Expression.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:296
ExtractElementConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to...
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:692
GetElementPtrConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
static Type * getGEPReturnType(Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Create an "inbounds" getelementptr.
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
InsertElementConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool isCast() const
Definition: Instruction.h:259
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
Definition: Instruction.h:256
const char * getOpcodeName() const
Definition: Instruction.h:253
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
Class to represent integer types.
Definition: DerivedTypes.h:40
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:278
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:72
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
DenseMap< PointerType *, std::unique_ptr< ConstantPointerNull > > CPNConstants
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
DenseMap< Type *, std::unique_ptr< PoisonValue > > PVConstants
DenseMap< std::pair< const Function *, const BasicBlock * >, BlockAddress * > BlockAddresses
DenseMap< APInt, std::unique_ptr< ConstantInt > > IntConstants
std::unique_ptr< ConstantTokenNone > TheNoneToken
VectorConstantsTy VectorConstants
DenseMap< const GlobalValue *, NoCFIValue * > NoCFIValues
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
StringMap< std::unique_ptr< ConstantDataSequential > > CDSConstants
StructConstantsTy StructConstants
DenseMap< TargetExtType *, std::unique_ptr< ConstantTargetNone > > CTNConstants
ConstantUniqueMap< ConstantExpr > ExprConstants
DenseMap< std::pair< ElementCount, APInt >, std::unique_ptr< ConstantInt > > IntSplatConstants
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
DenseMap< std::pair< ElementCount, APFloat >, std::unique_ptr< ConstantFP > > FPSplatConstants
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:69
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition: Constants.h:971
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:1977
PointerType * getType() const
NoCFIValue is always a pointer.
Definition: Constants.h:993
GlobalValue * getGlobalValue() const
Definition: Constants.h:988
Class to represent pointers.
Definition: DerivedTypes.h:646
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition: Constants.h:1398
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
PoisonValue * getStructElement(unsigned Elt) const
If this poison has struct type, return a poison with the right element type for the specified element...
Definition: Constants.cpp:1188
PoisonValue * getSequentialElement() const
If this poison has array or vector type, return a poison with the right element type.
Definition: Constants.cpp:1182
PoisonValue * getElementValue(Constant *C) const
Return an poison of the right value for the specified GEP index if we can, otherwise return null (e....
Definition: Constants.cpp:1192
static void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition: Metadata.cpp:328
ShuffleVectorConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
This instruction constructs a fixed permutation of two input vectors.
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
void reserve(size_type N)
Definition: SmallVector.h:676
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
iterator end()
Definition: StringMap.h:221
iterator find(StringRef Key)
Definition: StringMap.h:234
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:373
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:720
bool hasProperty(Property Prop) const
Returns true if the target extension type contains the given property.
Definition: Type.cpp:855
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:769
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
static Type * getDoubleTy(LLVMContext &C)
const fltSemantics & getFltSemantics() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
static Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:252
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:146
unsigned getStructNumElements() const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition: Type.h:75
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:79
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:77
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:74
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:76
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition: Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
@ TokenTyID
Tokens.
Definition: Type.h:68
@ PointerTyID
Pointers.
Definition: Type.h:73
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition: Type.h:61
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:249
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:281
static IntegerType * getInt16Ty(LLVMContext &C)
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:157
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
static Type * getFloatTy(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
'undef' values are things that do not have specified contents.
Definition: Constants.h:1350
UndefValue * getElementValue(Constant *C) const
Return an undef of the right value for the specified GEP index if we can, otherwise return null (e....
Definition: Constants.cpp:1157
UndefValue * getStructElement(unsigned Elt) const
If this undef has struct type, return a undef with the right element type for the specified element.
Definition: Constants.cpp:1153
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1808
unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:1169
UndefValue * getSequentialElement() const
If this Undef has array or vector type, return a undef with the right element type.
Definition: Constants.cpp:1147
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
const Use * getOperandList() const
Definition: User.h:162
op_range operands()
Definition: User.h:242
op_iterator op_begin()
Definition: User.h:234
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
iterator_range< value_op_iterator > operand_values()
Definition: User.h:266
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:391
user_iterator user_begin()
Definition: Value.h:397
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition: Value.h:84
const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition: Value.cpp:697
const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition: Value.cpp:705
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
User * user_back()
Definition: Value.h:407
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:532
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
bool use_empty() const
Definition: Value.h:344
user_iterator user_end()
Definition: Value.h:405
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
iterator_range< use_iterator > uses()
Definition: Value.h:376
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition: Value.h:815
ValueTy
Concrete subclass of this.
Definition: Value.h:513
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:641
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
Definition: DerivedTypes.h:454
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
Type * getElementType() const
Definition: DerivedTypes.h:436
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:541
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:294
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
constexpr double e
Definition: MathExtras.h:31
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1731
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1689
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:228
Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, bool InBounds, std::optional< unsigned > InRangeIndex, ArrayRef< Value * > Idxs)
Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
gep_type_iterator gep_type_end(const User *GEP)
void deleteConstant(Constant *C)
Definition: Constants.cpp:512
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ Other
Any other memory.
Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:233
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1833
gep_type_iterator gep_type_begin(const User *GEP)
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
#define N
#define NC
Definition: regutils.h:42
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:249
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:230
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:252
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:263
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:251
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:250
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:247
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:248
Compile-time customization of User operands.
Definition: User.h:42