LLVM 22.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.
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) {
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) {
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) {
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) {
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);
319 return CmpEq && (isa<PoisonValue>(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;
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 (isa<ConstantInt>(this) || isa<ConstantFP>(this))
362 return false;
363
364 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
365 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
367 return true;
368 }
369 return false;
370}
371
372/// Constructor to create a '0' constant of arbitrary type.
374 switch (Ty->getTypeID()) {
376 return ConstantInt::get(Ty, 0);
377 case Type::HalfTyID:
378 case Type::BFloatTyID:
379 case Type::FloatTyID:
380 case Type::DoubleTyID:
382 case Type::FP128TyID:
384 return ConstantFP::get(Ty->getContext(),
385 APFloat::getZero(Ty->getFltSemantics()));
388 case Type::StructTyID:
389 case Type::ArrayTyID:
393 case Type::TokenTyID:
394 return ConstantTokenNone::get(Ty->getContext());
397 default:
398 // Function, Label, or Opaque type?
399 llvm_unreachable("Cannot create a null constant of that type!");
400 }
401}
402
404 Type *ScalarTy = Ty->getScalarType();
405
406 // Create the base integer constant.
407 Constant *C = ConstantInt::get(Ty->getContext(), V);
408
409 // Convert an integer to a pointer, if necessary.
410 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
412
413 // Broadcast a scalar to a vector, if necessary.
414 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
415 C = ConstantVector::getSplat(VTy->getElementCount(), C);
416
417 return C;
418}
419
421 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
422 return ConstantInt::get(Ty->getContext(),
423 APInt::getAllOnes(ITy->getBitWidth()));
424
425 if (Ty->isFloatingPointTy()) {
426 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
427 return ConstantFP::get(Ty->getContext(), FL);
428 }
429
430 VectorType *VTy = cast<VectorType>(Ty);
431 return ConstantVector::getSplat(VTy->getElementCount(),
432 getAllOnesValue(VTy->getElementType()));
433}
434
436 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
437 "Must be an aggregate/vector constant");
438
439 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
440 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
441
442 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
443 return Elt < CAZ->getElementCount().getKnownMinValue()
444 ? CAZ->getElementValue(Elt)
445 : nullptr;
446
447 if (const auto *CI = dyn_cast<ConstantInt>(this))
448 return Elt < cast<VectorType>(getType())
449 ->getElementCount()
450 .getKnownMinValue()
451 ? ConstantInt::get(getContext(), CI->getValue())
452 : nullptr;
453
454 if (const auto *CFP = dyn_cast<ConstantFP>(this))
455 return Elt < cast<VectorType>(getType())
456 ->getElementCount()
457 .getKnownMinValue()
458 ? ConstantFP::get(getContext(), CFP->getValue())
459 : nullptr;
460
461 // FIXME: getNumElements() will fail for non-fixed vector types.
463 return nullptr;
464
465 if (const auto *PV = dyn_cast<PoisonValue>(this))
466 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
467
468 if (const auto *UV = dyn_cast<UndefValue>(this))
469 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
470
471 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
472 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
473 : nullptr;
474
475 return nullptr;
476}
477
479 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
480 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
481 // Check if the constant fits into an uint64_t.
482 if (CI->getValue().getActiveBits() > 64)
483 return nullptr;
484 return getAggregateElement(CI->getZExtValue());
485 }
486 return nullptr;
487}
488
490 /// First call destroyConstantImpl on the subclass. This gives the subclass
491 /// a chance to remove the constant from any maps/pools it's contained in.
492 switch (getValueID()) {
493 default:
494 llvm_unreachable("Not a constant!");
495#define HANDLE_CONSTANT(Name) \
496 case Value::Name##Val: \
497 cast<Name>(this)->destroyConstantImpl(); \
498 break;
499#include "llvm/IR/Value.def"
500 }
501
502 // When a Constant is destroyed, there may be lingering
503 // references to the constant by other constants in the constant pool. These
504 // constants are implicitly dependent on the module that is being deleted,
505 // but they don't know that. Because we only find out when the CPV is
506 // deleted, we must now notify all of our users (that should only be
507 // Constants) that they are, in fact, invalid now and should be deleted.
508 //
509 while (!use_empty()) {
510 Value *V = user_back();
511#ifndef NDEBUG // Only in -g mode...
512 if (!isa<Constant>(V)) {
513 dbgs() << "While deleting: " << *this
514 << "\n\nUse still stuck around after Def is destroyed: " << *V
515 << "\n\n";
516 }
517#endif
518 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
519 cast<Constant>(V)->destroyConstant();
520
521 // The constant should remove itself from our use list...
522 assert((use_empty() || user_back() != V) && "Constant not removed!");
523 }
524
525 // Value has no outstanding references it is safe to delete it now...
526 deleteConstant(this);
527}
528
530 switch (C->getValueID()) {
531 case Constant::ConstantIntVal:
532 delete static_cast<ConstantInt *>(C);
533 break;
534 case Constant::ConstantFPVal:
535 delete static_cast<ConstantFP *>(C);
536 break;
537 case Constant::ConstantAggregateZeroVal:
538 delete static_cast<ConstantAggregateZero *>(C);
539 break;
540 case Constant::ConstantArrayVal:
541 delete static_cast<ConstantArray *>(C);
542 break;
543 case Constant::ConstantStructVal:
544 delete static_cast<ConstantStruct *>(C);
545 break;
546 case Constant::ConstantVectorVal:
547 delete static_cast<ConstantVector *>(C);
548 break;
549 case Constant::ConstantPointerNullVal:
550 delete static_cast<ConstantPointerNull *>(C);
551 break;
552 case Constant::ConstantDataArrayVal:
553 delete static_cast<ConstantDataArray *>(C);
554 break;
555 case Constant::ConstantDataVectorVal:
556 delete static_cast<ConstantDataVector *>(C);
557 break;
558 case Constant::ConstantTokenNoneVal:
559 delete static_cast<ConstantTokenNone *>(C);
560 break;
561 case Constant::BlockAddressVal:
562 delete static_cast<BlockAddress *>(C);
563 break;
564 case Constant::DSOLocalEquivalentVal:
565 delete static_cast<DSOLocalEquivalent *>(C);
566 break;
567 case Constant::NoCFIValueVal:
568 delete static_cast<NoCFIValue *>(C);
569 break;
570 case Constant::ConstantPtrAuthVal:
571 delete static_cast<ConstantPtrAuth *>(C);
572 break;
573 case Constant::UndefValueVal:
574 delete static_cast<UndefValue *>(C);
575 break;
576 case Constant::PoisonValueVal:
577 delete static_cast<PoisonValue *>(C);
578 break;
579 case Constant::ConstantExprVal:
581 delete static_cast<CastConstantExpr *>(C);
582 else if (isa<BinaryConstantExpr>(C))
583 delete static_cast<BinaryConstantExpr *>(C);
585 delete static_cast<ExtractElementConstantExpr *>(C);
587 delete static_cast<InsertElementConstantExpr *>(C);
589 delete static_cast<ShuffleVectorConstantExpr *>(C);
591 delete static_cast<GetElementPtrConstantExpr *>(C);
592 else
593 llvm_unreachable("Unexpected constant expr");
594 break;
595 default:
596 llvm_unreachable("Unexpected constant");
597 }
598}
599
600/// Check if C contains a GlobalValue for which Predicate is true.
601static bool
603 bool (*Predicate)(const GlobalValue *)) {
606 WorkList.push_back(C);
607 Visited.insert(C);
608
609 while (!WorkList.empty()) {
610 const Constant *WorkItem = WorkList.pop_back_val();
611 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
612 if (Predicate(GV))
613 return true;
614 for (const Value *Op : WorkItem->operands()) {
615 const Constant *ConstOp = dyn_cast<Constant>(Op);
616 if (!ConstOp)
617 continue;
618 if (Visited.insert(ConstOp).second)
619 WorkList.push_back(ConstOp);
620 }
621 }
622 return false;
623}
624
626 auto DLLImportPredicate = [](const GlobalValue *GV) {
627 return GV->isThreadLocal();
628 };
629 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
630}
631
633 auto DLLImportPredicate = [](const GlobalValue *GV) {
634 return GV->hasDLLImportStorageClass();
635 };
636 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
637}
638
640 for (const User *U : users()) {
641 const Constant *UC = dyn_cast<Constant>(U);
642 if (!UC || isa<GlobalValue>(UC))
643 return true;
644
645 if (UC->isConstantUsed())
646 return true;
647 }
648 return false;
649}
650
652 return getRelocationInfo() == GlobalRelocation;
653}
654
656 return getRelocationInfo() != NoRelocation;
657}
658
659Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
660 if (isa<GlobalValue>(this))
661 return GlobalRelocation; // Global reference.
662
663 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
664 return BA->getFunction()->getRelocationInfo();
665
666 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
667 if (CE->getOpcode() == Instruction::Sub) {
668 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
669 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
670 if (LHS && RHS &&
671 (LHS->getOpcode() == Instruction::PtrToInt ||
672 LHS->getOpcode() == Instruction::PtrToAddr) &&
673 (RHS->getOpcode() == Instruction::PtrToInt ||
674 RHS->getOpcode() == Instruction::PtrToAddr)) {
675 Constant *LHSOp0 = LHS->getOperand(0);
676 Constant *RHSOp0 = RHS->getOperand(0);
677
678 // While raw uses of blockaddress need to be relocated, differences
679 // between two of them don't when they are for labels in the same
680 // function. This is a common idiom when creating a table for the
681 // indirect goto extension, so we handle it efficiently here.
682 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
683 cast<BlockAddress>(LHSOp0)->getFunction() ==
685 return NoRelocation;
686
687 // Relative pointers do not need to be dynamically relocated.
688 if (auto *RHSGV =
690 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
691 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
692 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
693 return LocalRelocation;
694 } else if (isa<DSOLocalEquivalent>(LHS)) {
695 if (RHSGV->isDSOLocal())
696 return LocalRelocation;
697 }
698 }
699 }
700 }
701 }
702
703 PossibleRelocationsTy Result = NoRelocation;
704 for (const Value *Op : operands())
705 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
706
707 return Result;
708}
709
710/// Return true if the specified constantexpr is dead. This involves
711/// recursively traversing users of the constantexpr.
712/// If RemoveDeadUsers is true, also remove dead users at the same time.
713static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
714 if (isa<GlobalValue>(C)) return false; // Cannot remove this
715
716 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
717 while (I != E) {
719 if (!User) return false; // Non-constant usage;
720 if (!constantIsDead(User, RemoveDeadUsers))
721 return false; // Constant wasn't dead
722
723 // Just removed User, so the iterator was invalidated.
724 // Since we return immediately upon finding a live user, we can always
725 // restart from user_begin().
726 if (RemoveDeadUsers)
727 I = C->user_begin();
728 else
729 ++I;
730 }
731
732 if (RemoveDeadUsers) {
733 // If C is only used by metadata, it should not be preserved but should
734 // have its uses replaced.
736 const_cast<Constant *>(C)->destroyConstant();
737 }
738
739 return true;
740}
741
744 Value::const_user_iterator LastNonDeadUser = E;
745 while (I != E) {
747 if (!User) {
748 LastNonDeadUser = I;
749 ++I;
750 continue;
751 }
752
753 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
754 // If the constant wasn't dead, remember that this was the last live use
755 // and move on to the next constant.
756 LastNonDeadUser = I;
757 ++I;
758 continue;
759 }
760
761 // If the constant was dead, then the iterator is invalidated.
762 if (LastNonDeadUser == E)
763 I = user_begin();
764 else
765 I = std::next(LastNonDeadUser);
766 }
767}
768
769bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
770
771bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
772
773bool Constant::hasNLiveUses(unsigned N) const {
774 unsigned NumUses = 0;
775 for (const Use &U : uses()) {
776 const Constant *User = dyn_cast<Constant>(U.getUser());
777 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
778 ++NumUses;
779
780 if (NumUses > N)
781 return false;
782 }
783 }
784 return NumUses == N;
785}
786
788 assert(C && Replacement && "Expected non-nullptr constant arguments");
789 Type *Ty = C->getType();
790 if (match(C, m_Undef())) {
791 assert(Ty == Replacement->getType() && "Expected matching types");
792 return Replacement;
793 }
794
795 // Don't know how to deal with this constant.
796 auto *VTy = dyn_cast<FixedVectorType>(Ty);
797 if (!VTy)
798 return C;
799
800 unsigned NumElts = VTy->getNumElements();
801 SmallVector<Constant *, 32> NewC(NumElts);
802 for (unsigned i = 0; i != NumElts; ++i) {
803 Constant *EltC = C->getAggregateElement(i);
804 assert((!EltC || EltC->getType() == Replacement->getType()) &&
805 "Expected matching types");
806 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
807 }
808 return ConstantVector::get(NewC);
809}
810
812 assert(C && Other && "Expected non-nullptr constant arguments");
813 if (match(C, m_Undef()))
814 return C;
815
816 Type *Ty = C->getType();
817 if (match(Other, m_Undef()))
818 return UndefValue::get(Ty);
819
820 auto *VTy = dyn_cast<FixedVectorType>(Ty);
821 if (!VTy)
822 return C;
823
824 Type *EltTy = VTy->getElementType();
825 unsigned NumElts = VTy->getNumElements();
826 assert(isa<FixedVectorType>(Other->getType()) &&
827 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
828 "Type mismatch");
829
830 bool FoundExtraUndef = false;
831 SmallVector<Constant *, 32> NewC(NumElts);
832 for (unsigned I = 0; I != NumElts; ++I) {
833 NewC[I] = C->getAggregateElement(I);
834 Constant *OtherEltC = Other->getAggregateElement(I);
835 assert(NewC[I] && OtherEltC && "Unknown vector element");
836 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
837 NewC[I] = UndefValue::get(EltTy);
838 FoundExtraUndef = true;
839 }
840 }
841 if (FoundExtraUndef)
842 return ConstantVector::get(NewC);
843 return C;
844}
845
847 if (isa<UndefValue>(this))
848 return false;
849 if (isa<ConstantData>(this))
850 return true;
851 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
852 for (const Value *Op : operand_values())
854 return false;
855 return true;
856 }
857 return false;
858}
859
860//===----------------------------------------------------------------------===//
861// ConstantInt
862//===----------------------------------------------------------------------===//
863
864ConstantInt::ConstantInt(Type *Ty, const APInt &V)
865 : ConstantData(Ty, ConstantIntVal), Val(V) {
866 assert(V.getBitWidth() ==
867 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
868 "Invalid constant for type");
869}
870
871ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
872 LLVMContextImpl *pImpl = Context.pImpl;
873 if (!pImpl->TheTrueVal)
874 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
875 return pImpl->TheTrueVal;
876}
877
878ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
879 LLVMContextImpl *pImpl = Context.pImpl;
880 if (!pImpl->TheFalseVal)
881 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
882 return pImpl->TheFalseVal;
883}
884
885ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
886 return V ? getTrue(Context) : getFalse(Context);
887}
888
890 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
891 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
892 if (auto *VTy = dyn_cast<VectorType>(Ty))
893 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
894 return TrueC;
895}
896
898 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
899 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
900 if (auto *VTy = dyn_cast<VectorType>(Ty))
901 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
902 return FalseC;
903}
904
906 return V ? getTrue(Ty) : getFalse(Ty);
907}
908
909// Get a ConstantInt from an APInt.
910ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
911 // get an existing value or the insertion position
912 LLVMContextImpl *pImpl = Context.pImpl;
913 std::unique_ptr<ConstantInt> &Slot =
914 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
915 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
916 : pImpl->IntConstants[V];
917 if (!Slot) {
918 // Get the corresponding integer type for the bit width of the value.
919 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
920 Slot.reset(new ConstantInt(ITy, V));
921 }
922 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
923 return Slot.get();
924}
925
926// Get a ConstantInt vector with each lane set to the same APInt.
927ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
928 const APInt &V) {
929 // Get an existing value or the insertion position.
930 std::unique_ptr<ConstantInt> &Slot =
931 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
932 if (!Slot) {
933 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
934 VectorType *VTy = VectorType::get(ITy, EC);
935 Slot.reset(new ConstantInt(VTy, V));
936 }
937
938#ifndef NDEBUG
939 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
940 VectorType *VTy = VectorType::get(ITy, EC);
941 assert(Slot->getType() == VTy);
942#endif
943 return Slot.get();
944}
945
946Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
947 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
948
949 // For vectors, broadcast the value.
950 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
951 return ConstantVector::getSplat(VTy->getElementCount(), C);
952
953 return C;
954}
955
956ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
957 // TODO: Avoid implicit trunc?
958 // See https://github.com/llvm/llvm-project/issues/112510.
959 return get(Ty->getContext(),
960 APInt(Ty->getBitWidth(), V, isSigned, /*implicitTrunc=*/true));
961}
962
963Constant *ConstantInt::get(Type *Ty, const APInt& V) {
964 ConstantInt *C = get(Ty->getContext(), V);
965 assert(C->getType() == Ty->getScalarType() &&
966 "ConstantInt type doesn't match the type implied by its value!");
967
968 // For vectors, broadcast the value.
969 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
970 return ConstantVector::getSplat(VTy->getElementCount(), C);
971
972 return C;
973}
974
975ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
976 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
977}
978
979/// Remove the constant from the constant table.
980void ConstantInt::destroyConstantImpl() {
981 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
982}
983
984//===----------------------------------------------------------------------===//
985// ConstantFP
986//===----------------------------------------------------------------------===//
987
988Constant *ConstantFP::get(Type *Ty, double V) {
989 LLVMContext &Context = Ty->getContext();
990
991 APFloat FV(V);
992 bool ignored;
993 FV.convert(Ty->getScalarType()->getFltSemantics(),
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::get(Type *Ty, const APFloat &V) {
1005 ConstantFP *C = get(Ty->getContext(), V);
1006 assert(C->getType() == Ty->getScalarType() &&
1007 "ConstantFP type doesn't match the type implied by its value!");
1008
1009 // For vectors, broadcast the value.
1010 if (auto *VTy = dyn_cast<VectorType>(Ty))
1011 return ConstantVector::getSplat(VTy->getElementCount(), C);
1012
1013 return C;
1014}
1015
1016Constant *ConstantFP::get(Type *Ty, StringRef Str) {
1017 LLVMContext &Context = Ty->getContext();
1018
1019 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1020 Constant *C = get(Context, FV);
1021
1022 // For vectors, broadcast the value.
1023 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1024 return ConstantVector::getSplat(VTy->getElementCount(), C);
1025
1026 return C;
1027}
1028
1029Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1030 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1031 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1032 Constant *C = get(Ty->getContext(), NaN);
1033
1034 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1035 return ConstantVector::getSplat(VTy->getElementCount(), C);
1036
1037 return C;
1038}
1039
1040Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1041 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1042 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1043 Constant *C = get(Ty->getContext(), NaN);
1044
1045 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1046 return ConstantVector::getSplat(VTy->getElementCount(), C);
1047
1048 return C;
1049}
1050
1051Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1052 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1053 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1054 Constant *C = get(Ty->getContext(), NaN);
1055
1056 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1057 return ConstantVector::getSplat(VTy->getElementCount(), C);
1058
1059 return C;
1060}
1061
1062Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1063 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1064 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1065 Constant *C = get(Ty->getContext(), NegZero);
1066
1067 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1068 return ConstantVector::getSplat(VTy->getElementCount(), C);
1069
1070 return C;
1071}
1072
1073
1074// ConstantFP accessors.
1075ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1076 LLVMContextImpl* pImpl = Context.pImpl;
1077
1078 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1079
1080 if (!Slot) {
1081 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1082 Slot.reset(new ConstantFP(Ty, V));
1083 }
1084
1085 return Slot.get();
1086}
1087
1088// Get a ConstantFP vector with each lane set to the same APFloat.
1089ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1090 const APFloat &V) {
1091 // Get an existing value or the insertion position.
1092 std::unique_ptr<ConstantFP> &Slot =
1093 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1094 if (!Slot) {
1095 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1096 VectorType *VTy = VectorType::get(EltTy, EC);
1097 Slot.reset(new ConstantFP(VTy, V));
1098 }
1099
1100#ifndef NDEBUG
1101 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1102 VectorType *VTy = VectorType::get(EltTy, EC);
1103 assert(Slot->getType() == VTy);
1104#endif
1105 return Slot.get();
1106}
1107
1109 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1110 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1111
1112 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1113 return ConstantVector::getSplat(VTy->getElementCount(), C);
1114
1115 return C;
1116}
1117
1118ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1119 : ConstantData(Ty, ConstantFPVal), Val(V) {
1120 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1121 "FP type Mismatch");
1122}
1123
1125 return Val.bitwiseIsEqual(V);
1126}
1127
1128/// Remove the constant from the constant table.
1129void ConstantFP::destroyConstantImpl() {
1130 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1131}
1132
1133//===----------------------------------------------------------------------===//
1134// ConstantAggregateZero Implementation
1135//===----------------------------------------------------------------------===//
1136
1138 if (auto *AT = dyn_cast<ArrayType>(getType()))
1139 return Constant::getNullValue(AT->getElementType());
1140 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1141}
1142
1144 return Constant::getNullValue(getType()->getStructElementType(Elt));
1145}
1146
1152
1155 return getSequentialElement();
1156 return getStructElement(Idx);
1157}
1158
1160 Type *Ty = getType();
1161 if (auto *AT = dyn_cast<ArrayType>(Ty))
1162 return ElementCount::getFixed(AT->getNumElements());
1163 if (auto *VT = dyn_cast<VectorType>(Ty))
1164 return VT->getElementCount();
1165 return ElementCount::getFixed(Ty->getStructNumElements());
1166}
1167
1168//===----------------------------------------------------------------------===//
1169// UndefValue Implementation
1170//===----------------------------------------------------------------------===//
1171
1174 return UndefValue::get(ATy->getElementType());
1175 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1176}
1177
1178UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1179 return UndefValue::get(getType()->getStructElementType(Elt));
1180}
1181
1184 return getSequentialElement();
1185 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1186}
1187
1188UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1190 return getSequentialElement();
1191 return getStructElement(Idx);
1192}
1193
1195 Type *Ty = getType();
1196 if (auto *AT = dyn_cast<ArrayType>(Ty))
1197 return AT->getNumElements();
1198 if (auto *VT = dyn_cast<VectorType>(Ty))
1199 return cast<FixedVectorType>(VT)->getNumElements();
1200 return Ty->getStructNumElements();
1201}
1202
1203//===----------------------------------------------------------------------===//
1204// PoisonValue Implementation
1205//===----------------------------------------------------------------------===//
1206
1209 return PoisonValue::get(ATy->getElementType());
1210 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1211}
1212
1213PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1214 return PoisonValue::get(getType()->getStructElementType(Elt));
1215}
1216
1219 return getSequentialElement();
1220 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1221}
1222
1223PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1225 return getSequentialElement();
1226 return getStructElement(Idx);
1227}
1228
1229//===----------------------------------------------------------------------===//
1230// ConstantXXX Classes
1231//===----------------------------------------------------------------------===//
1232
1233template <typename ItTy, typename EltTy>
1234static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1235 for (; Start != End; ++Start)
1236 if (*Start != Elt)
1237 return false;
1238 return true;
1239}
1240
1241template <typename SequentialTy, typename ElementTy>
1243 assert(!V.empty() && "Cannot get empty int sequence.");
1244
1246 for (Constant *C : V)
1247 if (auto *CI = dyn_cast<ConstantInt>(C))
1248 Elts.push_back(CI->getZExtValue());
1249 else
1250 return nullptr;
1251 return SequentialTy::get(V[0]->getContext(), Elts);
1252}
1253
1254template <typename SequentialTy, typename ElementTy>
1256 assert(!V.empty() && "Cannot get empty FP sequence.");
1257
1259 for (Constant *C : V)
1260 if (auto *CFP = dyn_cast<ConstantFP>(C))
1261 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1262 else
1263 return nullptr;
1264 return SequentialTy::getFP(V[0]->getType(), Elts);
1265}
1266
1267template <typename SequenceTy>
1270 // We speculatively build the elements here even if it turns out that there is
1271 // a constantexpr or something else weird, since it is so uncommon for that to
1272 // happen.
1273 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1274 if (CI->getType()->isIntegerTy(8))
1276 else if (CI->getType()->isIntegerTy(16))
1278 else if (CI->getType()->isIntegerTy(32))
1280 else if (CI->getType()->isIntegerTy(64))
1282 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1283 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1285 else if (CFP->getType()->isFloatTy())
1287 else if (CFP->getType()->isDoubleTy())
1289 }
1290
1291 return nullptr;
1292}
1293
1297 : Constant(T, VT, AllocInfo) {
1298 llvm::copy(V, op_begin());
1299
1300 // Check that types match, unless this is an opaque struct.
1301 if (auto *ST = dyn_cast<StructType>(T)) {
1302 if (ST->isOpaque())
1303 return;
1304 for (unsigned I = 0, E = V.size(); I != E; ++I)
1305 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1306 "Initializer for struct element doesn't match!");
1307 }
1308}
1309
1310ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1312 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1313 assert(V.size() == T->getNumElements() &&
1314 "Invalid initializer for constant array");
1315}
1316
1318 if (Constant *C = getImpl(Ty, V))
1319 return C;
1320 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1321}
1322
1323Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1324 // Empty arrays are canonicalized to ConstantAggregateZero.
1325 if (V.empty())
1326 return ConstantAggregateZero::get(Ty);
1327
1328 for (Constant *C : V) {
1329 assert(C->getType() == Ty->getElementType() &&
1330 "Wrong type in array element initializer");
1331 (void)C;
1332 }
1333
1334 // If this is an all-zero array, return a ConstantAggregateZero object. If
1335 // all undef, return an UndefValue, if "all simple", then return a
1336 // ConstantDataArray.
1337 Constant *C = V[0];
1338 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1339 return PoisonValue::get(Ty);
1340
1341 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1342 return UndefValue::get(Ty);
1343
1344 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1345 return ConstantAggregateZero::get(Ty);
1346
1347 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1348 // the element type is compatible with ConstantDataVector. If so, use it.
1351
1352 // Otherwise, we really do want to create a ConstantArray.
1353 return nullptr;
1354}
1355
1358 bool Packed) {
1359 unsigned VecSize = V.size();
1360 SmallVector<Type*, 16> EltTypes(VecSize);
1361 for (unsigned i = 0; i != VecSize; ++i)
1362 EltTypes[i] = V[i]->getType();
1363
1364 return StructType::get(Context, EltTypes, Packed);
1365}
1366
1367
1369 bool Packed) {
1370 assert(!V.empty() &&
1371 "ConstantStruct::getTypeForElements cannot be called on empty list");
1372 return getTypeForElements(V[0]->getContext(), V, Packed);
1373}
1374
1375ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1377 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1378 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1379 "Invalid initializer for constant struct");
1380}
1381
1382// ConstantStruct accessors.
1384 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1385 "Incorrect # elements specified to ConstantStruct::get");
1386
1387 // Create a ConstantAggregateZero value if all elements are zeros.
1388 bool isZero = true;
1389 bool isUndef = false;
1390 bool isPoison = false;
1391
1392 if (!V.empty()) {
1393 isUndef = isa<UndefValue>(V[0]);
1394 isPoison = isa<PoisonValue>(V[0]);
1395 isZero = V[0]->isNullValue();
1396 // PoisonValue inherits UndefValue, so its check is not necessary.
1397 if (isUndef || isZero) {
1398 for (Constant *C : V) {
1399 if (!C->isNullValue())
1400 isZero = false;
1401 if (!isa<PoisonValue>(C))
1402 isPoison = false;
1404 isUndef = false;
1405 }
1406 }
1407 }
1408 if (isZero)
1409 return ConstantAggregateZero::get(ST);
1410 if (isPoison)
1411 return PoisonValue::get(ST);
1412 if (isUndef)
1413 return UndefValue::get(ST);
1414
1415 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1416}
1417
1418ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1420 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1421 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1422 "Invalid initializer for constant vector");
1423}
1424
1425// ConstantVector accessors.
1427 if (Constant *C = getImpl(V))
1428 return C;
1429 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1430 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1431}
1432
1433Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1434 assert(!V.empty() && "Vectors can't be empty");
1435 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1436
1437 // If this is an all-undef or all-zero vector, return a
1438 // ConstantAggregateZero or UndefValue.
1439 Constant *C = V[0];
1440 bool isZero = C->isNullValue();
1441 bool isUndef = isa<UndefValue>(C);
1442 bool isPoison = isa<PoisonValue>(C);
1445
1446 if (isZero || isUndef || isSplatFP || isSplatInt) {
1447 for (unsigned i = 1, e = V.size(); i != e; ++i)
1448 if (V[i] != C) {
1449 isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;
1450 break;
1451 }
1452 }
1453
1454 if (isZero)
1456 if (isPoison)
1457 return PoisonValue::get(T);
1458 if (isUndef)
1459 return UndefValue::get(T);
1460 if (isSplatFP)
1461 return ConstantFP::get(C->getContext(), T->getElementCount(),
1462 cast<ConstantFP>(C)->getValue());
1463 if (isSplatInt)
1464 return ConstantInt::get(C->getContext(), T->getElementCount(),
1465 cast<ConstantInt>(C)->getValue());
1466
1467 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1468 // the element type is compatible with ConstantDataVector. If so, use it.
1471
1472 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1473 // the operand list contains a ConstantExpr or something else strange.
1474 return nullptr;
1475}
1476
1478 if (!EC.isScalable()) {
1479 // Maintain special handling of zero.
1480 if (!V->isNullValue()) {
1482 return ConstantInt::get(V->getContext(), EC,
1483 cast<ConstantInt>(V)->getValue());
1485 return ConstantFP::get(V->getContext(), EC,
1486 cast<ConstantFP>(V)->getValue());
1487 }
1488
1489 // If this splat is compatible with ConstantDataVector, use it instead of
1490 // ConstantVector.
1491 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1493 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1494
1495 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1496 return get(Elts);
1497 }
1498
1499 // Maintain special handling of zero.
1500 if (!V->isNullValue()) {
1502 return ConstantInt::get(V->getContext(), EC,
1503 cast<ConstantInt>(V)->getValue());
1505 return ConstantFP::get(V->getContext(), EC,
1506 cast<ConstantFP>(V)->getValue());
1507 }
1508
1509 Type *VTy = VectorType::get(V->getType(), EC);
1510
1511 if (V->isNullValue())
1512 return ConstantAggregateZero::get(VTy);
1513 if (isa<PoisonValue>(V))
1514 return PoisonValue::get(VTy);
1515 if (isa<UndefValue>(V))
1516 return UndefValue::get(VTy);
1517
1518 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1519
1520 // Move scalar into vector.
1521 Constant *PoisonV = PoisonValue::get(VTy);
1522 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1523 // Build shuffle mask to perform the splat.
1524 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1525 // Splat.
1526 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1527}
1528
1529ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1530 LLVMContextImpl *pImpl = Context.pImpl;
1531 if (!pImpl->TheNoneToken)
1532 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1533 return pImpl->TheNoneToken.get();
1534}
1535
1536/// Remove the constant from the constant table.
1537void ConstantTokenNone::destroyConstantImpl() {
1538 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1539}
1540
1541// Utility function for determining if a ConstantExpr is a CastOp or not. This
1542// can't be inline because we don't want to #include Instruction.h into
1543// Constant.h
1545
1549
1551 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1552}
1553
1555 bool OnlyIfReduced, Type *SrcTy) const {
1556 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1557
1558 // If no operands changed return self.
1559 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1560 return const_cast<ConstantExpr*>(this);
1561
1562 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1563 switch (getOpcode()) {
1564 case Instruction::Trunc:
1565 case Instruction::ZExt:
1566 case Instruction::SExt:
1567 case Instruction::FPTrunc:
1568 case Instruction::FPExt:
1569 case Instruction::UIToFP:
1570 case Instruction::SIToFP:
1571 case Instruction::FPToUI:
1572 case Instruction::FPToSI:
1573 case Instruction::PtrToAddr:
1574 case Instruction::PtrToInt:
1575 case Instruction::IntToPtr:
1576 case Instruction::BitCast:
1577 case Instruction::AddrSpaceCast:
1578 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1579 case Instruction::InsertElement:
1580 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1581 OnlyIfReducedTy);
1582 case Instruction::ExtractElement:
1583 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1584 case Instruction::ShuffleVector:
1586 OnlyIfReducedTy);
1587 case Instruction::GetElementPtr: {
1588 auto *GEPO = cast<GEPOperator>(this);
1589 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1591 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1592 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1593 }
1594 default:
1595 assert(getNumOperands() == 2 && "Must be binary operator?");
1597 OnlyIfReducedTy);
1598 }
1599}
1600
1601
1602//===----------------------------------------------------------------------===//
1603// isValueValidForType implementations
1604
1606 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1607 if (Ty->isIntegerTy(1))
1608 return Val == 0 || Val == 1;
1609 return isUIntN(NumBits, Val);
1610}
1611
1613 unsigned NumBits = Ty->getIntegerBitWidth();
1614 if (Ty->isIntegerTy(1))
1615 return Val == 0 || Val == 1 || Val == -1;
1616 return isIntN(NumBits, Val);
1617}
1618
1620 // convert modifies in place, so make a copy.
1621 APFloat Val2 = APFloat(Val);
1622 bool losesInfo;
1623 switch (Ty->getTypeID()) {
1624 default:
1625 return false; // These can't be represented as floating point!
1626
1627 // FIXME rounding mode needs to be more flexible
1628 case Type::HalfTyID: {
1629 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1630 return true;
1632 return !losesInfo;
1633 }
1634 case Type::BFloatTyID: {
1635 if (&Val2.getSemantics() == &APFloat::BFloat())
1636 return true;
1638 return !losesInfo;
1639 }
1640 case Type::FloatTyID: {
1641 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1642 return true;
1644 return !losesInfo;
1645 }
1646 case Type::DoubleTyID: {
1647 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1648 &Val2.getSemantics() == &APFloat::BFloat() ||
1649 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1650 &Val2.getSemantics() == &APFloat::IEEEdouble())
1651 return true;
1653 return !losesInfo;
1654 }
1655 case Type::X86_FP80TyID:
1656 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1657 &Val2.getSemantics() == &APFloat::BFloat() ||
1658 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1659 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1661 case Type::FP128TyID:
1662 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1663 &Val2.getSemantics() == &APFloat::BFloat() ||
1664 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1665 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1666 &Val2.getSemantics() == &APFloat::IEEEquad();
1668 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1669 &Val2.getSemantics() == &APFloat::BFloat() ||
1670 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1671 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1673 }
1674}
1675
1676
1677//===----------------------------------------------------------------------===//
1678// Factory Function Implementation
1679
1680ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1681 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1682 "Cannot create an aggregate zero of non-aggregate type!");
1683
1684 std::unique_ptr<ConstantAggregateZero> &Entry =
1685 Ty->getContext().pImpl->CAZConstants[Ty];
1686 if (!Entry)
1687 Entry.reset(new ConstantAggregateZero(Ty));
1688
1689 return Entry.get();
1690}
1691
1692/// Remove the constant from the constant table.
1693void ConstantAggregateZero::destroyConstantImpl() {
1695}
1696
1697/// Remove the constant from the constant table.
1698void ConstantArray::destroyConstantImpl() {
1700}
1701
1702
1703//---- ConstantStruct::get() implementation...
1704//
1705
1706/// Remove the constant from the constant table.
1707void ConstantStruct::destroyConstantImpl() {
1709}
1710
1711/// Remove the constant from the constant table.
1712void ConstantVector::destroyConstantImpl() {
1714}
1715
1716Constant *Constant::getSplatValue(bool AllowPoison) const {
1717 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1718 if (isa<PoisonValue>(this))
1719 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1721 return getNullValue(cast<VectorType>(getType())->getElementType());
1722 if (auto *CI = dyn_cast<ConstantInt>(this))
1723 return ConstantInt::get(getContext(), CI->getValue());
1724 if (auto *CFP = dyn_cast<ConstantFP>(this))
1725 return ConstantFP::get(getContext(), CFP->getValue());
1727 return CV->getSplatValue();
1728 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1729 return CV->getSplatValue(AllowPoison);
1730
1731 // Check if this is a constant expression splat of the form returned by
1732 // ConstantVector::getSplat()
1733 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1734 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1735 isa<UndefValue>(Shuf->getOperand(1))) {
1736
1737 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1738 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1739 isa<UndefValue>(IElt->getOperand(0))) {
1740
1741 ArrayRef<int> Mask = Shuf->getShuffleMask();
1742 Constant *SplatVal = IElt->getOperand(1);
1743 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1744
1745 if (Index && Index->getValue() == 0 &&
1746 llvm::all_of(Mask, [](int I) { return I == 0; }))
1747 return SplatVal;
1748 }
1749 }
1750
1751 return nullptr;
1752}
1753
1754Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1755 // Check out first element.
1756 Constant *Elt = getOperand(0);
1757 // Then make sure all remaining elements point to the same value.
1758 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1759 Constant *OpC = getOperand(I);
1760 if (OpC == Elt)
1761 continue;
1762
1763 // Strict mode: any mismatch is not a splat.
1764 if (!AllowPoison)
1765 return nullptr;
1766
1767 // Allow poison mode: ignore poison elements.
1768 if (isa<PoisonValue>(OpC))
1769 continue;
1770
1771 // If we do not have a defined element yet, use the current operand.
1772 if (isa<PoisonValue>(Elt))
1773 Elt = OpC;
1774
1775 if (OpC != Elt)
1776 return nullptr;
1777 }
1778 return Elt;
1779}
1780
1782 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1783 return CI->getValue();
1784 // Scalable vectors can use a ConstantExpr to build a splat.
1785 if (isa<ConstantExpr>(this))
1786 return cast<ConstantInt>(this->getSplatValue())->getValue();
1787 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1788 // calling getSplatValue in release builds.
1789 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1790 const Constant *C = this->getAggregateElement(0U);
1791 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1792 return cast<ConstantInt>(C)->getValue();
1793}
1794
1796 if (auto *CI = dyn_cast<ConstantInt>(this))
1797 return ConstantRange(CI->getValue());
1798
1799 unsigned BitWidth = getType()->getScalarSizeInBits();
1800 if (!getType()->isVectorTy())
1801 return ConstantRange::getFull(BitWidth);
1802
1803 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1804 getSplatValue(/*AllowPoison=*/true)))
1805 return ConstantRange(CI->getValue());
1806
1807 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1808 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1809 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1810 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1811 return CR;
1812 }
1813
1814 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1815 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1816 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1817 Constant *Elem = CV->getOperand(I);
1818 if (!Elem)
1819 return ConstantRange::getFull(BitWidth);
1820 if (isa<PoisonValue>(Elem))
1821 continue;
1822 auto *CI = dyn_cast<ConstantInt>(Elem);
1823 if (!CI)
1824 return ConstantRange::getFull(BitWidth);
1825 CR = CR.unionWith(CI->getValue());
1826 }
1827 return CR;
1828 }
1829
1830 return ConstantRange::getFull(BitWidth);
1831}
1832
1833//---- ConstantPointerNull::get() implementation.
1834//
1835
1836ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1837 std::unique_ptr<ConstantPointerNull> &Entry =
1838 Ty->getContext().pImpl->CPNConstants[Ty];
1839 if (!Entry)
1840 Entry.reset(new ConstantPointerNull(Ty));
1841
1842 return Entry.get();
1843}
1844
1845/// Remove the constant from the constant table.
1846void ConstantPointerNull::destroyConstantImpl() {
1848}
1849
1850//---- ConstantTargetNone::get() implementation.
1851//
1852
1853ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1854 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1855 "Target extension type not allowed to have a zeroinitializer");
1856 std::unique_ptr<ConstantTargetNone> &Entry =
1857 Ty->getContext().pImpl->CTNConstants[Ty];
1858 if (!Entry)
1859 Entry.reset(new ConstantTargetNone(Ty));
1860
1861 return Entry.get();
1862}
1863
1864/// Remove the constant from the constant table.
1865void ConstantTargetNone::destroyConstantImpl() {
1867}
1868
1869UndefValue *UndefValue::get(Type *Ty) {
1870 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1871 if (!Entry)
1872 Entry.reset(new UndefValue(Ty));
1873
1874 return Entry.get();
1875}
1876
1877/// Remove the constant from the constant table.
1878void UndefValue::destroyConstantImpl() {
1879 // Free the constant and any dangling references to it.
1880 if (getValueID() == UndefValueVal) {
1881 getContext().pImpl->UVConstants.erase(getType());
1882 } else if (getValueID() == PoisonValueVal) {
1883 getContext().pImpl->PVConstants.erase(getType());
1884 }
1885 llvm_unreachable("Not a undef or a poison!");
1886}
1887
1888PoisonValue *PoisonValue::get(Type *Ty) {
1889 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1890 if (!Entry)
1891 Entry.reset(new PoisonValue(Ty));
1892
1893 return Entry.get();
1894}
1895
1896/// Remove the constant from the constant table.
1897void PoisonValue::destroyConstantImpl() {
1898 // Free the constant and any dangling references to it.
1899 getContext().pImpl->PVConstants.erase(getType());
1900}
1901
1902BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
1903 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
1904 if (!BA)
1905 BA = new BlockAddress(Ty, BB);
1906 return BA;
1907}
1908
1909BlockAddress *BlockAddress::get(BasicBlock *BB) {
1910 assert(BB->getParent() && "Block must have a parent");
1911 return get(BB->getParent()->getType(), BB);
1912}
1913
1915 assert(BB->getParent() == F && "Block not part of specified function");
1916 return get(BB->getParent()->getType(), BB);
1917}
1918
1919BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
1920 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
1921 setOperand(0, BB);
1922 BB->setHasAddressTaken(true);
1923}
1924
1925BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1926 if (!BB->hasAddressTaken())
1927 return nullptr;
1928
1929 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
1930 assert(BA && "Refcount and block address map disagree!");
1931 return BA;
1932}
1933
1934/// Remove the constant from the constant table.
1935void BlockAddress::destroyConstantImpl() {
1937 getBasicBlock()->setHasAddressTaken(false);
1938}
1939
1940Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1941 assert(From == getBasicBlock());
1942 BasicBlock *NewBB = cast<BasicBlock>(To);
1943
1944 // See if the 'new' entry already exists, if not, just update this in place
1945 // and return early.
1946 BlockAddress *&NewBA = getContext().pImpl->BlockAddresses[NewBB];
1947 if (NewBA)
1948 return NewBA;
1949
1950 getBasicBlock()->setHasAddressTaken(false);
1951
1952 // Remove the old entry, this can't cause the map to rehash (just a
1953 // tombstone will get added).
1955 NewBA = this;
1956 setOperand(0, NewBB);
1957 getBasicBlock()->setHasAddressTaken(true);
1958
1959 // If we just want to keep the existing value, then return null.
1960 // Callers know that this means we shouldn't delete this value.
1961 return nullptr;
1962}
1963
1964DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1965 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1966 if (!Equiv)
1967 Equiv = new DSOLocalEquivalent(GV);
1968
1969 assert(Equiv->getGlobalValue() == GV &&
1970 "DSOLocalFunction does not match the expected global value");
1971 return Equiv;
1972}
1973
1974DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1975 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
1976 setOperand(0, GV);
1977}
1978
1979/// Remove the constant from the constant table.
1980void DSOLocalEquivalent::destroyConstantImpl() {
1981 const GlobalValue *GV = getGlobalValue();
1982 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1983}
1984
1985Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1986 assert(From == getGlobalValue() && "Changing value does not match operand.");
1987 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1988
1989 // The replacement is with another global value.
1990 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1991 DSOLocalEquivalent *&NewEquiv =
1993 if (NewEquiv)
1994 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1995 }
1996
1997 // If the argument is replaced with a null value, just replace this constant
1998 // with a null value.
1999 if (cast<Constant>(To)->isNullValue())
2000 return To;
2001
2002 // The replacement could be a bitcast or an alias to another function. We can
2003 // replace it with a bitcast to the dso_local_equivalent of that function.
2005 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
2006 if (NewEquiv)
2007 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2008
2009 // Replace this with the new one.
2011 NewEquiv = this;
2012 setOperand(0, Func);
2013
2014 if (Func->getType() != getType()) {
2015 // It is ok to mutate the type here because this constant should always
2016 // reflect the type of the function it's holding.
2017 mutateType(Func->getType());
2018 }
2019 return nullptr;
2020}
2021
2023 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2024 if (!NC)
2025 NC = new NoCFIValue(GV);
2026
2027 assert(NC->getGlobalValue() == GV &&
2028 "NoCFIValue does not match the expected global value");
2029 return NC;
2030}
2031
2032NoCFIValue::NoCFIValue(GlobalValue *GV)
2033 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2034 setOperand(0, GV);
2035}
2036
2037/// Remove the constant from the constant table.
2038void NoCFIValue::destroyConstantImpl() {
2039 const GlobalValue *GV = getGlobalValue();
2040 GV->getContext().pImpl->NoCFIValues.erase(GV);
2041}
2042
2043Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2044 assert(From == getGlobalValue() && "Changing value does not match operand.");
2045
2046 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2047 assert(GV && "Can only replace the operands with a global value");
2048
2049 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
2050 if (NewNC)
2051 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2052
2054 NewNC = this;
2055 setOperand(0, GV);
2056
2057 if (GV->getType() != getType())
2058 mutateType(GV->getType());
2059
2060 return nullptr;
2061}
2062
2063//---- ConstantPtrAuth::get() implementations.
2064//
2065
2067 ConstantInt *Disc, Constant *AddrDisc) {
2068 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc};
2069 ConstantPtrAuthKeyType MapKey(ArgVec);
2070 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2071 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2072}
2073
2074ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2075 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator());
2076}
2077
2078ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2079 ConstantInt *Disc, Constant *AddrDisc)
2080 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2081 assert(Ptr->getType()->isPointerTy());
2082 assert(Key->getBitWidth() == 32);
2083 assert(Disc->getBitWidth() == 64);
2084 assert(AddrDisc->getType()->isPointerTy());
2085 setOperand(0, Ptr);
2086 setOperand(1, Key);
2087 setOperand(2, Disc);
2088 setOperand(3, AddrDisc);
2089}
2090
2091/// Remove the constant from the constant table.
2092void ConstantPtrAuth::destroyConstantImpl() {
2093 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2094}
2095
2096Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2097 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2098 Constant *To = cast<Constant>(ToV);
2099
2101 Values.reserve(getNumOperands());
2102
2103 unsigned NumUpdated = 0;
2104
2105 Use *OperandList = getOperandList();
2106 unsigned OperandNo = 0;
2107 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2108 Constant *Val = cast<Constant>(O->get());
2109 if (Val == From) {
2110 OperandNo = (O - OperandList);
2111 Val = To;
2112 ++NumUpdated;
2113 }
2114 Values.push_back(Val);
2115 }
2116
2117 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2118 Values, this, From, To, NumUpdated, OperandNo);
2119}
2120
2122 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2123 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2124 return false;
2125
2126 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2127 if (!IntVal)
2128 return false;
2129
2130 return IntVal->getValue() == Value;
2131}
2132
2134 const Value *Discriminator,
2135 const DataLayout &DL) const {
2136 // If the keys are different, there's no chance for this to be compatible.
2137 if (getKey() != Key)
2138 return false;
2139
2140 // We can have 3 kinds of discriminators:
2141 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2142 // - address-only: `i64 0, ptr p` vs. `ptr p`
2143 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2144
2145 // If this constant has a simple discriminator (integer, no address), easy:
2146 // it's compatible iff the provided full discriminator is also a simple
2147 // discriminator, identical to our integer discriminator.
2149 return getDiscriminator() == Discriminator;
2150
2151 // Otherwise, we can isolate address and integer discriminator components.
2152 const Value *AddrDiscriminator = nullptr;
2153
2154 // This constant may or may not have an integer discriminator (instead of 0).
2155 if (!getDiscriminator()->isNullValue()) {
2156 // If it does, there's an implicit blend. We need to have a matching blend
2157 // intrinsic in the provided full discriminator.
2158 if (!match(Discriminator,
2160 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2161 return false;
2162 } else {
2163 // Otherwise, interpret the provided full discriminator as address-only.
2164 AddrDiscriminator = Discriminator;
2165 }
2166
2167 // Either way, we can now focus on comparing the address discriminators.
2168
2169 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2170 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2171 AddrDiscriminator = Cast->getPointerOperand();
2172
2173 // Beyond that, we're only interested in compatible pointers.
2174 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2175 return false;
2176
2177 // These are often the same constant GEP, making them trivially equivalent.
2178 if (getAddrDiscriminator() == AddrDiscriminator)
2179 return true;
2180
2181 // Finally, they may be equivalent base+offset expressions.
2182 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2184 DL, Off1, /*AllowNonInbounds=*/true);
2185
2186 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2187 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2188 DL, Off2, /*AllowNonInbounds=*/true);
2189
2190 return Base1 == Base2 && Off1 == Off2;
2191}
2192
2193//---- ConstantExpr::get() implementations.
2194//
2195
2196/// This is a utility function to handle folding of casts and lookup of the
2197/// cast in the ExprConstants map. It is used by the various get* methods below.
2199 bool OnlyIfReduced = false) {
2200 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2201 // Fold a few common cases
2202 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2203 return FC;
2204
2205 if (OnlyIfReduced)
2206 return nullptr;
2207
2208 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2209
2210 // Look up the constant in the table first to ensure uniqueness.
2212
2213 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2214}
2215
2217 bool OnlyIfReduced) {
2219 assert(Instruction::isCast(opc) && "opcode out of range");
2221 "Cast opcode not supported as constant expression");
2222 assert(C && Ty && "Null arguments to getCast");
2223 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2224
2225 switch (opc) {
2226 default:
2227 llvm_unreachable("Invalid cast opcode");
2228 case Instruction::Trunc:
2229 return getTrunc(C, Ty, OnlyIfReduced);
2230 case Instruction::PtrToAddr:
2231 return getPtrToAddr(C, Ty, OnlyIfReduced);
2232 case Instruction::PtrToInt:
2233 return getPtrToInt(C, Ty, OnlyIfReduced);
2234 case Instruction::IntToPtr:
2235 return getIntToPtr(C, Ty, OnlyIfReduced);
2236 case Instruction::BitCast:
2237 return getBitCast(C, Ty, OnlyIfReduced);
2238 case Instruction::AddrSpaceCast:
2239 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2240 }
2241}
2242
2244 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2245 return getBitCast(C, Ty);
2246 return getTrunc(C, Ty);
2247}
2248
2250 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2251 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2252 "Invalid cast");
2253
2254 if (Ty->isIntOrIntVectorTy())
2255 return getPtrToInt(S, Ty);
2256
2257 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2258 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2259 return getAddrSpaceCast(S, Ty);
2260
2261 return getBitCast(S, Ty);
2262}
2263
2265 Type *Ty) {
2266 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2267 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2268
2269 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2270 return getAddrSpaceCast(S, Ty);
2271
2272 return getBitCast(S, Ty);
2273}
2274
2275Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2276#ifndef NDEBUG
2277 bool fromVec = isa<VectorType>(C->getType());
2278 bool toVec = isa<VectorType>(Ty);
2279#endif
2280 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2281 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2282 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2283 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2284 "SrcTy must be larger than DestTy for Trunc!");
2285
2286 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2287}
2288
2290 bool OnlyIfReduced) {
2291 assert(C->getType()->isPtrOrPtrVectorTy() &&
2292 "PtrToAddr source must be pointer or pointer vector");
2293 assert(DstTy->isIntOrIntVectorTy() &&
2294 "PtrToAddr destination must be integer or integer vector");
2295 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2296 if (isa<VectorType>(C->getType()))
2297 assert(cast<VectorType>(C->getType())->getElementCount() ==
2298 cast<VectorType>(DstTy)->getElementCount() &&
2299 "Invalid cast between a different number of vector elements");
2300 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2301}
2302
2304 bool OnlyIfReduced) {
2305 assert(C->getType()->isPtrOrPtrVectorTy() &&
2306 "PtrToInt source must be pointer or pointer vector");
2307 assert(DstTy->isIntOrIntVectorTy() &&
2308 "PtrToInt destination must be integer or integer vector");
2309 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2310 if (isa<VectorType>(C->getType()))
2311 assert(cast<VectorType>(C->getType())->getElementCount() ==
2312 cast<VectorType>(DstTy)->getElementCount() &&
2313 "Invalid cast between a different number of vector elements");
2314 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2315}
2316
2318 bool OnlyIfReduced) {
2319 assert(C->getType()->isIntOrIntVectorTy() &&
2320 "IntToPtr source must be integer or integer vector");
2321 assert(DstTy->isPtrOrPtrVectorTy() &&
2322 "IntToPtr destination must be a pointer or pointer vector");
2323 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2324 if (isa<VectorType>(C->getType()))
2325 assert(cast<VectorType>(C->getType())->getElementCount() ==
2326 cast<VectorType>(DstTy)->getElementCount() &&
2327 "Invalid cast between a different number of vector elements");
2328 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2329}
2330
2332 bool OnlyIfReduced) {
2333 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2334 "Invalid constantexpr bitcast!");
2335
2336 // It is common to ask for a bitcast of a value to its own type, handle this
2337 // speedily.
2338 if (C->getType() == DstTy) return C;
2339
2340 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2341}
2342
2344 bool OnlyIfReduced) {
2345 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2346 "Invalid constantexpr addrspacecast!");
2347 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2348}
2349
2350Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2351 unsigned Flags, Type *OnlyIfReducedTy) {
2352 // Check the operands for consistency first.
2354 "Invalid opcode in binary constant expression");
2355 assert(isSupportedBinOp(Opcode) &&
2356 "Binop not supported as constant expression");
2357 assert(C1->getType() == C2->getType() &&
2358 "Operand types in binary constant expression should match");
2359
2360#ifndef NDEBUG
2361 switch (Opcode) {
2362 case Instruction::Add:
2363 case Instruction::Sub:
2364 case Instruction::Mul:
2366 "Tried to create an integer operation on a non-integer type!");
2367 break;
2368 case Instruction::And:
2369 case Instruction::Or:
2370 case Instruction::Xor:
2372 "Tried to create a logical operation on a non-integral type!");
2373 break;
2374 default:
2375 break;
2376 }
2377#endif
2378
2379 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2380 return FC;
2381
2382 if (OnlyIfReducedTy == C1->getType())
2383 return nullptr;
2384
2385 Constant *ArgVec[] = {C1, C2};
2386 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2387
2388 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2389 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2390}
2391
2392bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2393 switch (Opcode) {
2394 case Instruction::UDiv:
2395 case Instruction::SDiv:
2396 case Instruction::URem:
2397 case Instruction::SRem:
2398 case Instruction::FAdd:
2399 case Instruction::FSub:
2400 case Instruction::FMul:
2401 case Instruction::FDiv:
2402 case Instruction::FRem:
2403 case Instruction::And:
2404 case Instruction::Or:
2405 case Instruction::LShr:
2406 case Instruction::AShr:
2407 case Instruction::Shl:
2408 case Instruction::Mul:
2409 return false;
2410 case Instruction::Add:
2411 case Instruction::Sub:
2412 case Instruction::Xor:
2413 return true;
2414 default:
2415 llvm_unreachable("Argument must be binop opcode");
2416 }
2417}
2418
2419bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2420 switch (Opcode) {
2421 case Instruction::UDiv:
2422 case Instruction::SDiv:
2423 case Instruction::URem:
2424 case Instruction::SRem:
2425 case Instruction::FAdd:
2426 case Instruction::FSub:
2427 case Instruction::FMul:
2428 case Instruction::FDiv:
2429 case Instruction::FRem:
2430 case Instruction::And:
2431 case Instruction::Or:
2432 case Instruction::LShr:
2433 case Instruction::AShr:
2434 case Instruction::Shl:
2435 case Instruction::Mul:
2436 return false;
2437 case Instruction::Add:
2438 case Instruction::Sub:
2439 case Instruction::Xor:
2440 return true;
2441 default:
2442 llvm_unreachable("Argument must be binop opcode");
2443 }
2444}
2445
2446bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2447 switch (Opcode) {
2448 case Instruction::ZExt:
2449 case Instruction::SExt:
2450 case Instruction::FPTrunc:
2451 case Instruction::FPExt:
2452 case Instruction::UIToFP:
2453 case Instruction::SIToFP:
2454 case Instruction::FPToUI:
2455 case Instruction::FPToSI:
2456 return false;
2457 case Instruction::Trunc:
2458 case Instruction::PtrToAddr:
2459 case Instruction::PtrToInt:
2460 case Instruction::IntToPtr:
2461 case Instruction::BitCast:
2462 case Instruction::AddrSpaceCast:
2463 return true;
2464 default:
2465 llvm_unreachable("Argument must be cast opcode");
2466 }
2467}
2468
2469bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2470 switch (Opcode) {
2471 case Instruction::ZExt:
2472 case Instruction::SExt:
2473 case Instruction::FPTrunc:
2474 case Instruction::FPExt:
2475 case Instruction::UIToFP:
2476 case Instruction::SIToFP:
2477 case Instruction::FPToUI:
2478 case Instruction::FPToSI:
2479 return false;
2480 case Instruction::Trunc:
2481 case Instruction::PtrToAddr:
2482 case Instruction::PtrToInt:
2483 case Instruction::IntToPtr:
2484 case Instruction::BitCast:
2485 case Instruction::AddrSpaceCast:
2486 return true;
2487 default:
2488 llvm_unreachable("Argument must be cast opcode");
2489 }
2490}
2491
2493 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2494 // Note that a non-inbounds gep is used, as null isn't within any object.
2495 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2497 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2498 GEPIdx);
2499 return getPtrToInt(GEP,
2500 Type::getInt64Ty(Ty->getContext()));
2501}
2502
2504 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2505 // Note that a non-inbounds gep is used, as null isn't within any object.
2506 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2507 Constant *NullPtr =
2509 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2510 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2511 Constant *Indices[2] = {Zero, One};
2512 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2513 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2514}
2515
2517 ArrayRef<Value *> Idxs,
2518 GEPNoWrapFlags NW,
2519 std::optional<ConstantRange> InRange,
2520 Type *OnlyIfReducedTy) {
2521 assert(Ty && "Must specify element type");
2522 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2523
2524 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2525 return FC; // Fold a few common cases.
2526
2527 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2528 ;
2529
2530 // Get the result type of the getelementptr!
2532 if (OnlyIfReducedTy == ReqTy)
2533 return nullptr;
2534
2535 auto EltCount = ElementCount::getFixed(0);
2536 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2537 EltCount = VecTy->getElementCount();
2538
2539 // Look up the constant in the table first to ensure uniqueness
2540 std::vector<Constant*> ArgVec;
2541 ArgVec.reserve(1 + Idxs.size());
2542 ArgVec.push_back(C);
2543 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2544 for (; GTI != GTE; ++GTI) {
2545 auto *Idx = cast<Constant>(GTI.getOperand());
2546 assert(
2547 (!isa<VectorType>(Idx->getType()) ||
2548 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2549 "getelementptr index type missmatch");
2550
2551 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2552 Idx = Idx->getSplatValue();
2553 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2554 !Idx->getType()->isVectorTy()) {
2555 Idx = ConstantVector::getSplat(EltCount, Idx);
2556 }
2557 ArgVec.push_back(Idx);
2558 }
2559
2560 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2561 {}, Ty, InRange);
2562
2563 LLVMContextImpl *pImpl = C->getContext().pImpl;
2564 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2565}
2566
2568 Type *OnlyIfReducedTy) {
2569 assert(Val->getType()->isVectorTy() &&
2570 "Tried to create extractelement operation on non-vector type!");
2571 assert(Idx->getType()->isIntegerTy() &&
2572 "Extractelement index must be an integer type!");
2573
2575 return FC; // Fold a few common cases.
2576
2577 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2578 if (OnlyIfReducedTy == ReqTy)
2579 return nullptr;
2580
2581 // Look up the constant in the table first to ensure uniqueness
2582 Constant *ArgVec[] = { Val, Idx };
2583 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2584
2585 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2586 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2587}
2588
2590 Constant *Idx, Type *OnlyIfReducedTy) {
2591 assert(Val->getType()->isVectorTy() &&
2592 "Tried to create insertelement operation on non-vector type!");
2593 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2594 "Insertelement types must match!");
2595 assert(Idx->getType()->isIntegerTy() &&
2596 "Insertelement index must be i32 type!");
2597
2598 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2599 return FC; // Fold a few common cases.
2600
2601 if (OnlyIfReducedTy == Val->getType())
2602 return nullptr;
2603
2604 // Look up the constant in the table first to ensure uniqueness
2605 Constant *ArgVec[] = { Val, Elt, Idx };
2606 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2607
2608 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2609 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2610}
2611
2613 ArrayRef<int> Mask,
2614 Type *OnlyIfReducedTy) {
2616 "Invalid shuffle vector constant expr operands!");
2617
2618 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2619 return FC; // Fold a few common cases.
2620
2621 unsigned NElts = Mask.size();
2622 auto V1VTy = cast<VectorType>(V1->getType());
2623 Type *EltTy = V1VTy->getElementType();
2624 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2625 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2626
2627 if (OnlyIfReducedTy == ShufTy)
2628 return nullptr;
2629
2630 // Look up the constant in the table first to ensure uniqueness
2631 Constant *ArgVec[] = {V1, V2};
2632 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2633
2634 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2635 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2636}
2637
2639 assert(C->getType()->isIntOrIntVectorTy() &&
2640 "Cannot NEG a nonintegral value!");
2641 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2642}
2643
2645 assert(C->getType()->isIntOrIntVectorTy() &&
2646 "Cannot NOT a nonintegral value!");
2647 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2648}
2649
2651 bool HasNUW, bool HasNSW) {
2652 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2654 return get(Instruction::Add, C1, C2, Flags);
2655}
2656
2658 bool HasNUW, bool HasNSW) {
2659 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2661 return get(Instruction::Sub, C1, C2, Flags);
2662}
2663
2665 return get(Instruction::Xor, C1, C2);
2666}
2667
2669 Type *Ty = C->getType();
2670 const APInt *IVal;
2671 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2672 return ConstantInt::get(Ty, IVal->logBase2());
2673
2674 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2675 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2676 if (!VecTy)
2677 return nullptr;
2678
2680 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2681 Constant *Elt = C->getAggregateElement(I);
2682 if (!Elt)
2683 return nullptr;
2684 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2685 if (isa<UndefValue>(Elt)) {
2686 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2687 continue;
2688 }
2689 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2690 return nullptr;
2691 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2692 }
2693
2694 return ConstantVector::get(Elts);
2695}
2696
2698 bool AllowRHSConstant, bool NSZ) {
2699 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2700
2701 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2702 if (Instruction::isCommutative(Opcode)) {
2703 switch (Opcode) {
2704 case Instruction::Add: // X + 0 = X
2705 case Instruction::Or: // X | 0 = X
2706 case Instruction::Xor: // X ^ 0 = X
2707 return Constant::getNullValue(Ty);
2708 case Instruction::Mul: // X * 1 = X
2709 return ConstantInt::get(Ty, 1);
2710 case Instruction::And: // X & -1 = X
2711 return Constant::getAllOnesValue(Ty);
2712 case Instruction::FAdd: // X + -0.0 = X
2713 return ConstantFP::getZero(Ty, !NSZ);
2714 case Instruction::FMul: // X * 1.0 = X
2715 return ConstantFP::get(Ty, 1.0);
2716 default:
2717 llvm_unreachable("Every commutative binop has an identity constant");
2718 }
2719 }
2720
2721 // Non-commutative opcodes: AllowRHSConstant must be set.
2722 if (!AllowRHSConstant)
2723 return nullptr;
2724
2725 switch (Opcode) {
2726 case Instruction::Sub: // X - 0 = X
2727 case Instruction::Shl: // X << 0 = X
2728 case Instruction::LShr: // X >>u 0 = X
2729 case Instruction::AShr: // X >> 0 = X
2730 case Instruction::FSub: // X - 0.0 = X
2731 return Constant::getNullValue(Ty);
2732 case Instruction::SDiv: // X / 1 = X
2733 case Instruction::UDiv: // X /u 1 = X
2734 return ConstantInt::get(Ty, 1);
2735 case Instruction::FDiv: // X / 1.0 = X
2736 return ConstantFP::get(Ty, 1.0);
2737 default:
2738 return nullptr;
2739 }
2740}
2741
2743 switch (ID) {
2744 case Intrinsic::umax:
2745 return Constant::getNullValue(Ty);
2746 case Intrinsic::umin:
2747 return Constant::getAllOnesValue(Ty);
2748 case Intrinsic::smax:
2750 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2751 case Intrinsic::smin:
2753 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2754 default:
2755 return nullptr;
2756 }
2757}
2758
2760 bool AllowRHSConstant, bool NSZ) {
2761 if (I->isBinaryOp())
2762 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2764 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2765 return nullptr;
2766}
2767
2769 bool AllowLHSConstant) {
2770 switch (Opcode) {
2771 default:
2772 break;
2773
2774 case Instruction::Or: // -1 | X = -1
2775 return Constant::getAllOnesValue(Ty);
2776
2777 case Instruction::And: // 0 & X = 0
2778 case Instruction::Mul: // 0 * X = 0
2779 return Constant::getNullValue(Ty);
2780 }
2781
2782 // AllowLHSConstant must be set.
2783 if (!AllowLHSConstant)
2784 return nullptr;
2785
2786 switch (Opcode) {
2787 default:
2788 return nullptr;
2789 case Instruction::Shl: // 0 << X = 0
2790 case Instruction::LShr: // 0 >>l X = 0
2791 case Instruction::AShr: // 0 >>a X = 0
2792 case Instruction::SDiv: // 0 /s X = 0
2793 case Instruction::UDiv: // 0 /u X = 0
2794 case Instruction::URem: // 0 %u X = 0
2795 case Instruction::SRem: // 0 %s X = 0
2796 return Constant::getNullValue(Ty);
2797 }
2798}
2799
2800/// Remove the constant from the constant table.
2801void ConstantExpr::destroyConstantImpl() {
2802 getType()->getContext().pImpl->ExprConstants.remove(this);
2803}
2804
2805const char *ConstantExpr::getOpcodeName() const {
2807}
2808
2809GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2810 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2811 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2812 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2813 SrcElementTy(SrcElementTy),
2814 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2815 InRange(std::move(InRange)) {
2816 Op<0>() = C;
2817 Use *OperandList = getOperandList();
2818 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2819 OperandList[i+1] = IdxList[i];
2820}
2821
2823 return SrcElementTy;
2824}
2825
2827 return ResElementTy;
2828}
2829
2830std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2831 return InRange;
2832}
2833
2834//===----------------------------------------------------------------------===//
2835// ConstantData* implementations
2836
2839 return ATy->getElementType();
2840 return cast<VectorType>(getType())->getElementType();
2841}
2842
2846
2848 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2849 return true;
2850 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2851 switch (IT->getBitWidth()) {
2852 case 8:
2853 case 16:
2854 case 32:
2855 case 64:
2856 return true;
2857 default: break;
2858 }
2859 }
2860 return false;
2861}
2862
2865 return AT->getNumElements();
2866 return cast<FixedVectorType>(getType())->getNumElements();
2867}
2868
2872
2873/// Return the start of the specified element.
2874const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
2875 assert(Elt < getNumElements() && "Invalid Elt");
2876 return DataElements + Elt * getElementByteSize();
2877}
2878
2879/// Return true if the array is empty or all zeros.
2880static bool isAllZeros(StringRef Arr) {
2881 for (char I : Arr)
2882 if (I != 0)
2883 return false;
2884 return true;
2885}
2886
2887/// This is the underlying implementation of all of the
2888/// ConstantDataSequential::get methods. They all thunk down to here, providing
2889/// the correct element type. We take the bytes in as a StringRef because
2890/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2892#ifndef NDEBUG
2893 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2894 assert(isElementTypeCompatible(ATy->getElementType()));
2895 else
2897#endif
2898 // If the elements are all zero or there are no elements, return a CAZ, which
2899 // is more dense and canonical.
2900 if (isAllZeros(Elements))
2901 return ConstantAggregateZero::get(Ty);
2902
2903 // Do a lookup to see if we have already formed one of these.
2904 auto &Slot =
2905 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
2906
2907 // The bucket can point to a linked list of different CDS's that have the same
2908 // body but different types. For example, 0,0,0,1 could be a 4 element array
2909 // of i8, or a 1-element array of i32. They'll both end up in the same
2910 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2911 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2912 for (; *Entry; Entry = &(*Entry)->Next)
2913 if ((*Entry)->getType() == Ty)
2914 return Entry->get();
2915
2916 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2917 // and return it.
2918 if (isa<ArrayType>(Ty)) {
2919 // Use reset because std::make_unique can't access the constructor.
2920 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2921 return Entry->get();
2922 }
2923
2925 // Use reset because std::make_unique can't access the constructor.
2926 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2927 return Entry->get();
2928}
2929
2930void ConstantDataSequential::destroyConstantImpl() {
2931 // Remove the constant from the StringMap.
2934
2935 auto Slot = CDSConstants.find(getRawDataValues());
2936
2937 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2938
2939 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2940
2941 // Remove the entry from the hash table.
2942 if (!(*Entry)->Next) {
2943 // If there is only one value in the bucket (common case) it must be this
2944 // entry, and removing the entry should remove the bucket completely.
2945 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2946 getContext().pImpl->CDSConstants.erase(Slot);
2947 return;
2948 }
2949
2950 // Otherwise, there are multiple entries linked off the bucket, unlink the
2951 // node we care about but keep the bucket around.
2952 while (true) {
2953 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2954 assert(Node && "Didn't find entry in its uniquing hash table!");
2955 // If we found our entry, unlink it from the list and we're done.
2956 if (Node.get() == this) {
2957 Node = std::move(Node->Next);
2958 return;
2959 }
2960
2961 Entry = &Node->Next;
2962 }
2963}
2964
2965/// getFP() constructors - Return a constant of array type with a float
2966/// element type taken from argument `ElementType', and count taken from
2967/// argument `Elts'. The amount of bits of the contained type must match the
2968/// number of bits of the type contained in the passed in ArrayRef.
2969/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2970/// that this can return a ConstantAggregateZero object.
2972 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2973 "Element type is not a 16-bit float type");
2974 Type *Ty = ArrayType::get(ElementType, Elts.size());
2975 const char *Data = reinterpret_cast<const char *>(Elts.data());
2976 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2977}
2979 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2980 Type *Ty = ArrayType::get(ElementType, Elts.size());
2981 const char *Data = reinterpret_cast<const char *>(Elts.data());
2982 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2983}
2985 assert(ElementType->isDoubleTy() &&
2986 "Element type is not a 64-bit float type");
2987 Type *Ty = ArrayType::get(ElementType, Elts.size());
2988 const char *Data = reinterpret_cast<const char *>(Elts.data());
2989 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2990}
2991
2993 StringRef Str, bool AddNull) {
2994 if (!AddNull) {
2995 const uint8_t *Data = Str.bytes_begin();
2996 return get(Context, ArrayRef(Data, Str.size()));
2997 }
2998
2999 SmallVector<uint8_t, 64> ElementVals;
3000 ElementVals.append(Str.begin(), Str.end());
3001 ElementVals.push_back(0);
3002 return get(Context, ElementVals);
3003}
3004
3005/// get() constructors - Return a constant with vector type with an element
3006/// count and element type matching the ArrayRef passed in. Note that this
3007/// can return a ConstantAggregateZero object.
3009 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3010 const char *Data = reinterpret_cast<const char *>(Elts.data());
3011 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3012}
3014 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3015 const char *Data = reinterpret_cast<const char *>(Elts.data());
3016 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3017}
3019 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3020 const char *Data = reinterpret_cast<const char *>(Elts.data());
3021 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3022}
3024 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3025 const char *Data = reinterpret_cast<const char *>(Elts.data());
3026 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3027}
3029 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3030 const char *Data = reinterpret_cast<const char *>(Elts.data());
3031 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3032}
3034 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3035 const char *Data = reinterpret_cast<const char *>(Elts.data());
3036 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3037}
3038
3039/// getFP() constructors - Return a constant of vector type with a float
3040/// element type taken from argument `ElementType', and count taken from
3041/// argument `Elts'. The amount of bits of the contained type must match the
3042/// number of bits of the type contained in the passed in ArrayRef.
3043/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3044/// that this can return a ConstantAggregateZero object.
3046 ArrayRef<uint16_t> Elts) {
3047 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3048 "Element type is not a 16-bit float type");
3049 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3050 const char *Data = reinterpret_cast<const char *>(Elts.data());
3051 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3052}
3054 ArrayRef<uint32_t> Elts) {
3055 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3056 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3057 const char *Data = reinterpret_cast<const char *>(Elts.data());
3058 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3059}
3061 ArrayRef<uint64_t> Elts) {
3062 assert(ElementType->isDoubleTy() &&
3063 "Element type is not a 64-bit float type");
3064 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3065 const char *Data = reinterpret_cast<const char *>(Elts.data());
3066 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3067}
3068
3070 assert(isElementTypeCompatible(V->getType()) &&
3071 "Element type not compatible with ConstantData");
3072 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3073 if (CI->getType()->isIntegerTy(8)) {
3074 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3075 return get(V->getContext(), Elts);
3076 }
3077 if (CI->getType()->isIntegerTy(16)) {
3078 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3079 return get(V->getContext(), Elts);
3080 }
3081 if (CI->getType()->isIntegerTy(32)) {
3082 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3083 return get(V->getContext(), Elts);
3084 }
3085 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3086 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3087 return get(V->getContext(), Elts);
3088 }
3089
3090 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3091 if (CFP->getType()->isHalfTy()) {
3093 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3094 return getFP(V->getType(), Elts);
3095 }
3096 if (CFP->getType()->isBFloatTy()) {
3098 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3099 return getFP(V->getType(), Elts);
3100 }
3101 if (CFP->getType()->isFloatTy()) {
3103 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3104 return getFP(V->getType(), Elts);
3105 }
3106 if (CFP->getType()->isDoubleTy()) {
3108 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3109 return getFP(V->getType(), Elts);
3110 }
3111 }
3113}
3114
3117 "Accessor can only be used when element is an integer");
3118 const char *EltPtr = getElementPointer(Elt);
3119
3120 // The data is stored in host byte order, make sure to cast back to the right
3121 // type to load with the right endianness.
3122 switch (getElementType()->getIntegerBitWidth()) {
3123 default: llvm_unreachable("Invalid bitwidth for CDS");
3124 case 8:
3125 return *reinterpret_cast<const uint8_t *>(EltPtr);
3126 case 16:
3127 return *reinterpret_cast<const uint16_t *>(EltPtr);
3128 case 32:
3129 return *reinterpret_cast<const uint32_t *>(EltPtr);
3130 case 64:
3131 return *reinterpret_cast<const uint64_t *>(EltPtr);
3132 }
3133}
3134
3137 "Accessor can only be used when element is an integer");
3138 const char *EltPtr = getElementPointer(Elt);
3139
3140 // The data is stored in host byte order, make sure to cast back to the right
3141 // type to load with the right endianness.
3142 switch (getElementType()->getIntegerBitWidth()) {
3143 default: llvm_unreachable("Invalid bitwidth for CDS");
3144 case 8: {
3145 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3146 return APInt(8, EltVal);
3147 }
3148 case 16: {
3149 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3150 return APInt(16, EltVal);
3151 }
3152 case 32: {
3153 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3154 return APInt(32, EltVal);
3155 }
3156 case 64: {
3157 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3158 return APInt(64, EltVal);
3159 }
3160 }
3161}
3162
3164 const char *EltPtr = getElementPointer(Elt);
3165
3166 switch (getElementType()->getTypeID()) {
3167 default:
3168 llvm_unreachable("Accessor can only be used when element is float/double!");
3169 case Type::HalfTyID: {
3170 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3171 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3172 }
3173 case Type::BFloatTyID: {
3174 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3175 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3176 }
3177 case Type::FloatTyID: {
3178 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3179 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3180 }
3181 case Type::DoubleTyID: {
3182 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3183 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3184 }
3185 }
3186}
3187
3189 assert(getElementType()->isFloatTy() &&
3190 "Accessor can only be used when element is a 'float'");
3191 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3192}
3193
3195 assert(getElementType()->isDoubleTy() &&
3196 "Accessor can only be used when element is a 'float'");
3197 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3198}
3199
3201 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3202 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3203 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3204
3205 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3206}
3207
3208bool ConstantDataSequential::isString(unsigned CharSize) const {
3209 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3210}
3211
3213 if (!isString())
3214 return false;
3215
3216 StringRef Str = getAsString();
3217
3218 // The last value must be nul.
3219 if (Str.back() != 0) return false;
3220
3221 // Other elements must be non-nul.
3222 return !Str.drop_back().contains(0);
3223}
3224
3225bool ConstantDataVector::isSplatData() const {
3226 const char *Base = getRawDataValues().data();
3227
3228 // Compare elements 1+ to the 0'th element.
3229 unsigned EltSize = getElementByteSize();
3230 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3231 if (memcmp(Base, Base+i*EltSize, EltSize))
3232 return false;
3233
3234 return true;
3235}
3236
3238 if (!IsSplatSet) {
3239 IsSplatSet = true;
3240 IsSplat = isSplatData();
3241 }
3242 return IsSplat;
3243}
3244
3246 // If they're all the same, return the 0th one as a representative.
3247 return isSplat() ? getElementAsConstant(0) : nullptr;
3248}
3249
3250//===----------------------------------------------------------------------===//
3251// handleOperandChange implementations
3252
3253/// Update this constant array to change uses of
3254/// 'From' to be uses of 'To'. This must update the uniquing data structures
3255/// etc.
3256///
3257/// Note that we intentionally replace all uses of From with To here. Consider
3258/// a large array that uses 'From' 1000 times. By handling this case all here,
3259/// ConstantArray::handleOperandChange is only invoked once, and that
3260/// single invocation handles all 1000 uses. Handling them one at a time would
3261/// work, but would be really slow because it would have to unique each updated
3262/// array instance.
3263///
3265 Value *Replacement = nullptr;
3266 switch (getValueID()) {
3267 default:
3268 llvm_unreachable("Not a constant!");
3269#define HANDLE_CONSTANT(Name) \
3270 case Value::Name##Val: \
3271 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3272 break;
3273#include "llvm/IR/Value.def"
3274 }
3275
3276 // If handleOperandChangeImpl returned nullptr, then it handled
3277 // replacing itself and we don't want to delete or replace anything else here.
3278 if (!Replacement)
3279 return;
3280
3281 // I do need to replace this with an existing value.
3282 assert(Replacement != this && "I didn't contain From!");
3283
3284 // Everyone using this now uses the replacement.
3285 replaceAllUsesWith(Replacement);
3286
3287 // Delete the old constant!
3289}
3290
3291Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3292 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3293 Constant *ToC = cast<Constant>(To);
3294
3296 Values.reserve(getNumOperands()); // Build replacement array.
3297
3298 // Fill values with the modified operands of the constant array. Also,
3299 // compute whether this turns into an all-zeros array.
3300 unsigned NumUpdated = 0;
3301
3302 // Keep track of whether all the values in the array are "ToC".
3303 bool AllSame = true;
3304 Use *OperandList = getOperandList();
3305 unsigned OperandNo = 0;
3306 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3307 Constant *Val = cast<Constant>(O->get());
3308 if (Val == From) {
3309 OperandNo = (O - OperandList);
3310 Val = ToC;
3311 ++NumUpdated;
3312 }
3313 Values.push_back(Val);
3314 AllSame &= Val == ToC;
3315 }
3316
3317 if (AllSame && ToC->isNullValue())
3319
3320 if (AllSame && isa<UndefValue>(ToC))
3321 return UndefValue::get(getType());
3322
3323 // Check for any other type of constant-folding.
3324 if (Constant *C = getImpl(getType(), Values))
3325 return C;
3326
3327 // Update to the new value.
3329 Values, this, From, ToC, NumUpdated, OperandNo);
3330}
3331
3332Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3333 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3334 Constant *ToC = cast<Constant>(To);
3335
3336 Use *OperandList = getOperandList();
3337
3339 Values.reserve(getNumOperands()); // Build replacement struct.
3340
3341 // Fill values with the modified operands of the constant struct. Also,
3342 // compute whether this turns into an all-zeros struct.
3343 unsigned NumUpdated = 0;
3344 bool AllSame = true;
3345 unsigned OperandNo = 0;
3346 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3347 Constant *Val = cast<Constant>(O->get());
3348 if (Val == From) {
3349 OperandNo = (O - OperandList);
3350 Val = ToC;
3351 ++NumUpdated;
3352 }
3353 Values.push_back(Val);
3354 AllSame &= Val == ToC;
3355 }
3356
3357 if (AllSame && ToC->isNullValue())
3359
3360 if (AllSame && isa<UndefValue>(ToC))
3361 return UndefValue::get(getType());
3362
3363 // Update to the new value.
3365 Values, this, From, ToC, NumUpdated, OperandNo);
3366}
3367
3368Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3369 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3370 Constant *ToC = cast<Constant>(To);
3371
3373 Values.reserve(getNumOperands()); // Build replacement array...
3374 unsigned NumUpdated = 0;
3375 unsigned OperandNo = 0;
3376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3377 Constant *Val = getOperand(i);
3378 if (Val == From) {
3379 OperandNo = i;
3380 ++NumUpdated;
3381 Val = ToC;
3382 }
3383 Values.push_back(Val);
3384 }
3385
3386 if (Constant *C = getImpl(Values))
3387 return C;
3388
3389 // Update to the new value.
3391 Values, this, From, ToC, NumUpdated, OperandNo);
3392}
3393
3394Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3395 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3396 Constant *To = cast<Constant>(ToV);
3397
3399 unsigned NumUpdated = 0;
3400 unsigned OperandNo = 0;
3401 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3402 Constant *Op = getOperand(i);
3403 if (Op == From) {
3404 OperandNo = i;
3405 ++NumUpdated;
3406 Op = To;
3407 }
3408 NewOps.push_back(Op);
3409 }
3410 assert(NumUpdated && "I didn't contain From!");
3411
3412 if (Constant *C = getWithOperands(NewOps, getType(), true))
3413 return C;
3414
3415 // Update to the new value.
3416 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3417 NewOps, this, From, To, NumUpdated, OperandNo);
3418}
3419
3421 SmallVector<Value *, 4> ValueOperands(operands());
3422 ArrayRef<Value*> Ops(ValueOperands);
3423
3424 switch (getOpcode()) {
3425 case Instruction::Trunc:
3426 case Instruction::PtrToAddr:
3427 case Instruction::PtrToInt:
3428 case Instruction::IntToPtr:
3429 case Instruction::BitCast:
3430 case Instruction::AddrSpaceCast:
3432 getType(), "");
3433 case Instruction::InsertElement:
3434 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3435 case Instruction::ExtractElement:
3436 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3437 case Instruction::ShuffleVector:
3438 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3439
3440 case Instruction::GetElementPtr: {
3441 const auto *GO = cast<GEPOperator>(this);
3442 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3443 Ops.slice(1), GO->getNoWrapFlags(), "");
3444 }
3445 default:
3446 assert(getNumOperands() == 2 && "Must be binary operator?");
3448 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3454 }
3457 return BO;
3458 }
3459}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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")))
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
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)
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt)
static Constant * getIntSequenceIfElementsMatch(ArrayRef< Constant * > V)
static Constant * getSequenceIfElementsMatch(Constant *C, ArrayRef< Constant * > V)
static bool ConstHasGlobalValuePredicate(const Constant *C, bool(*Predicate)(const GlobalValue *))
Check if C contains a GlobalValue for which Predicate is true.
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.
static bool containsUndefinedElement(const Constant *C, function_ref< bool(const Constant *)> HasFn)
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...
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...
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
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static bool isUndef(const MachineInstr &MI)
Merge contiguous icmps into a memcmp
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
#define T
uint64_t IntrinsicInst * II
static unsigned getNumElements(Type *Ty)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & BFloat()
Definition APFloat.h:295
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
static const fltSemantics & IEEEquad()
Definition APFloat.h:298
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:317
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:299
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1102
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1110
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6063
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6089
const fltSemantics & getSemantics() const
Definition APFloat.h:1439
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1080
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1091
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1061
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:234
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:209
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:219
unsigned logBase2() const
Definition APInt.h:1761
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:440
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
const T * data() const
Definition ArrayRef.h:144
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:690
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
BinaryConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to impleme...
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
The address of a basic block.
Definition Constants.h:899
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
BasicBlock * getBasicBlock() const
Definition Constants.h:934
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
CastConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to implement...
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI 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.
All zero aggregate value.
Definition Constants.h:359
LLVM_ABI ElementCount getElementCount() const
Return the number of elements in the array, vector, or struct.
LLVM_ABI Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
LLVM_ABI Constant * getElementValue(Constant *C) const
Return a zero of the right value for the specified GEP index if we can, otherwise return null (e....
LLVM_ABI Constant * getStructElement(unsigned Elt) const
If this CAZ has struct type, return a zero with the right element type for the specified element.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
Base class for aggregate constants (with operands).
Definition Constants.h:408
LLVM_ABI ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V, AllocInfo AllocInfo)
ConstantArray - Constant Array Declarations.
Definition Constants.h:433
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:435
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:452
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:702
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
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:715
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:668
LLVM_ABI Constant * getElementAsConstant(uint64_t i) const
Return a Constant for a specified index's element.
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI float getElementAsFloat(uint64_t i) const
If this is an sequential container of floats, return the specified element as a float.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI APInt getElementAsAPInt(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element as an APInt...
static LLVM_ABI Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
LLVM_ABI double getElementAsDouble(uint64_t i) const
If this is an sequential container of doubles, return the specified element as a double.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
LLVM_ABI bool isCString() const
This method returns true if the array "isString", ends with a null byte, and does not contains any ot...
LLVM_ABI StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:776
LLVM_ABI Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value,...
static LLVM_ABI Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
LLVM_ABI bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value.
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
Base class for constants with no operands.
Definition Constants.h:56
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1120
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
ConstantExpr(Type *ty, unsigned Opcode, AllocInfo AllocInfo)
Definition Constants.h:1128
static LLVM_ABI Constant * getAlignOf(Type *Ty)
getAlignOf constant expr - computes the alignment of a type in a target independent way (Note: the re...
friend struct ConstantExprKeyType
Definition Constants.h:1121
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getTruncOrBitCast(Constant *C, Type *Ty)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
LLVM_ABI bool isCast() const
Return true if this is a convert constant expression.
static LLVM_ABI Constant * getIdentity(Instruction *I, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary or intrinsic Instruction.
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
LLVM_ABI Constant * getShuffleMaskForBitcode() const
Assert that this is a shufflevector and return the mask.
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
friend class Constant
Definition Constants.h:1122
LLVM_ABI const char * getOpcodeName() const
Return a string representation for an opcode.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getSizeOf(Type *Ty)
getSizeOf constant expr - computes the (alloc) size of a type (in address-units, not bits) in a targe...
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1387
static LLVM_ABI Constant * getIntrinsicIdentity(Intrinsic::ID, Type *Ty)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI 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.
static LLVM_ABI bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
LLVM_ABI ArrayRef< int > getShuffleMask() const
Assert that this is a shufflevector and return the mask.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition Constants.h:1327
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1274
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI 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...
Constant * getWithOperands(ArrayRef< Constant * > Ops) const
This returns the current constant expression with the operands replaced with the specified values.
Definition Constants.h:1345
LLVM_ABI Instruction * getAsInstruction() const
Returns an Instruction which implements the same operation as this ConstantExpr.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:277
static LLVM_ABI Constant * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
friend class Constant
Definition Constants.h:278
static LLVM_ABI Constant * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
LLVM_ABI 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 ...
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V.
friend class Constant
Definition Constants.h:88
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
A constant pointer value that points to null.
Definition Constants.h:558
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
PointerType * getType() const
Specialize the getType() method to always return an PointerType, which reduces the amount of casting ...
Definition Constants.h:574
A signed pointer, in the ptrauth sense.
Definition Constants.h:1032
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1072
friend struct ConstantPtrAuthKeyType
Definition Constants.h:1033
LLVM_ABI bool isKnownCompatibleWith(const Value *Key, const Value *Discriminator, const DataLayout &DL) const
Check whether an authentication operation with key Key and (possibly blended) discriminator Discrimin...
LLVM_ABI bool hasSpecialAddressDiscriminator(uint64_t Value) const
Whether the address uses a special address discriminator.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
friend class Constant
Definition Constants.h:1034
LLVM_ABI ConstantPtrAuth * getWithSameSchema(Constant *Pointer) const
Produce a new ptrauth expression signing the given value using the same schema as is stored in one.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1062
bool hasAddressDiscriminator() const
Whether there is any non-null address discriminator.
Definition Constants.h:1077
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1065
This class represents a range of values.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:467
static LLVM_ABI StructType * getTypeForElements(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct type to use for a constant with the specified set of elements.
StructType * getType() const
Specialization - reduce amount of casting.
Definition Constants.h:504
static LLVM_ABI ConstantTargetNone * get(TargetExtType *T)
Static factory methods - Return objects of the specified value.
TargetExtType * getType() const
Specialize the getType() method to always return an TargetExtType, which reduces the amount of castin...
Definition Constants.h:887
A constant token which is empty.
Definition Constants.h:850
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
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:517
friend class Constant
Definition Constants.h:519
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:540
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI 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...
LLVM_ABI bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
LLVM_ABI bool containsUndefElement() const
Return true if this is a vector constant that includes any strictly undef (not poison) elements.
static LLVM_ABI Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
LLVM_ABI ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool hasZeroLiveUses() const
Return true if the constant has no live uses.
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
LLVM_ABI bool isManifestConstant() const
Return true if a constant is ConstantData or a ConstantAggregate or ConstantExpr that contain only Co...
LLVM_ABI bool isNegativeZeroValue() const
Return true if the value is what would be returned by getZeroValueForNegation.
Definition Constants.cpp:56
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Constant(Type *ty, ValueTy vty, AllocInfo AllocInfo)
Definition Constant.h:45
LLVM_ABI bool hasOneLiveUse() const
Return true if the constant has exactly one live use.
LLVM_ABI bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry (eith...
LLVM_ABI bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
LLVM_ABI bool containsConstantExpression() const
Return true if this is a fixed width vector constant that includes any constant expressions.
LLVM_ABI bool isFiniteNonZeroFP() const
Return true if this is a finite and non-zero floating-point scalar constant or a fixed width vector c...
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
LLVM_ABI bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
LLVM_ABI bool needsDynamicRelocation() const
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNaN() const
Return true if this is a floating-point NaN constant or a vector floating-point constant with all NaN...
LLVM_ABI bool isMinSignedValue() const
Return true if the value is the smallest signed value.
LLVM_ABI bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
LLVM_ABI bool isThreadDependent() const
Return true if the value can vary between threads.
LLVM_ABI bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition Constants.cpp:76
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
LLVM_ABI bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:90
LLVM_ABI bool isNotOneValue() const
Return true if the value is not the one value, or, for vectors, does not contain one value elements.
LLVM_ABI bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
LLVM_ABI bool containsUndefOrPoisonElement() const
Return true if this is a vector constant that includes any undef or poison elements.
LLVM_ABI bool containsPoisonElement() const
Return true if this is a vector constant that includes any poison elements.
LLVM_ABI void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:952
GlobalValue * getGlobalValue() const
Definition Constants.h:973
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:310
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="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:803
Represents flags for the getelementptr instruction/expression.
unsigned getRaw() const
GetElementPtrConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
std::optional< ConstantRange > getInRange() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
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="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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.
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="", InsertPosition InsertBefore=nullptr)
LLVM_ABI 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
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
const char * getOpcodeName() const
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:319
A wrapper class for inspecting calls to intrinsic functions.
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< APInt, std::unique_ptr< ConstantInt > > IntConstants
std::unique_ptr< ConstantTokenNone > TheNoneToken
VectorConstantsTy VectorConstants
DenseMap< const GlobalValue *, NoCFIValue * > NoCFIValues
DenseMap< const BasicBlock *, BlockAddress * > BlockAddresses
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
StringMap< std::unique_ptr< ConstantDataSequential > > CDSConstants
StructConstantsTy StructConstants
ConstantUniqueMap< ConstantPtrAuth > ConstantPtrAuths
DenseMap< TargetExtType *, std::unique_ptr< ConstantTargetNone > > CTNConstants
ConstantUniqueMap< ConstantExpr > ExprConstants
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition Constants.h:991
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
PointerType * getType() const
NoCFIValue is always a pointer.
Definition Constants.h:1015
GlobalValue * getGlobalValue() const
Definition Constants.h:1010
Class to represent pointers.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1468
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
friend class Constant
Definition Constants.h:1469
LLVM_ABI PoisonValue * getStructElement(unsigned Elt) const
If this poison has struct type, return a poison with the right element type for the specified element...
LLVM_ABI PoisonValue * getSequentialElement() const
If this poison has array or vector type, return a poison with the right element type.
LLVM_ABI PoisonValue * getElementValue(Constant *C) const
Return an poison of the right value for the specified GEP index if we can, otherwise return null (e....
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:332
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 LLVM_ABI 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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
Class to represent struct types.
static LLVM_ABI 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:414
Class to represent target extensions types, which are generally unintrospectable from target-independ...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:297
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:74
@ HalfTyID
16-bit floating point type
Definition Type.h:56
@ TargetExtTyID
Target extension type.
Definition Type.h:78
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:76
@ FloatTyID
32-bit floating point type
Definition Type.h:58
@ StructTyID
Structures.
Definition Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:75
@ 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:67
@ PointerTyID
Pointers.
Definition Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:61
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:126
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:198
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:296
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:231
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:285
'undef' values are things that do not have specified contents.
Definition Constants.h:1420
LLVM_ABI UndefValue * getElementValue(Constant *C) const
Return an undef of the right value for the specified GEP index if we can, otherwise return null (e....
LLVM_ABI UndefValue * getStructElement(unsigned Elt) const
If this undef has struct type, return a undef with the right element type for the specified element.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
friend class Constant
Definition Constants.h:1421
LLVM_ABI unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
LLVM_ABI UndefValue * getSequentialElement() const
If this Undef has array or vector type, return a undef with the right element type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use * getOperandList() const
Definition User.h:225
op_range operands()
Definition User.h:292
User(Type *ty, unsigned vty, AllocInfo AllocInfo)
Definition User.h:119
op_iterator op_begin()
Definition User.h:284
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Use & Op()
Definition User.h:196
Value * getOperand(unsigned i) const
Definition User.h:232
unsigned getNumOperands() const
Definition User.h:254
iterator_range< value_op_iterator > operand_values()
Definition User.h:316
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
user_iterator_impl< const User > const_user_iterator
Definition Value.h:392
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:53
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition Value.h:85
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:705
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:713
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
iterator_range< user_iterator > users()
Definition Value.h:426
User * user_back()
Definition Value.h:412
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:701
bool use_empty() const
Definition Value.h:346
user_iterator user_end()
Definition Value.h:410
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1099
iterator_range< use_iterator > uses()
Definition Value.h:380
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:838
ValueTy
Concrete subclass of this.
Definition Value.h:524
Base class of all SIMD vector types.
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
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.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
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:1725
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
gep_type_iterator gep_type_end(const User *GEP)
void deleteConstant(Constant *C)
LLVM_ABI Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, std::optional< ConstantRange > InRange, ArrayRef< Value * > Idxs)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1835
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:248
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
#define N
#define NC
Definition regutils.h:42
Summary of memprof metadata on allocations.
Information about how a User object was allocated, to be passed into the User constructor.
Definition User.h:79