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_MAX integers
188 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
189 return CI->isMaxValue(/*isSigned=*/true);
190
191 // Check for FP which are bitcasted from INT_MAX integers
192 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
193 return CFP->getValueAPF().bitcastToAPInt().isMaxSignedValue();
194
195 // Check for splats of INT_MAX values.
196 if (getType()->isVectorTy())
197 if (const auto *SplatVal = getSplatValue())
198 return SplatVal->isMaxSignedValue();
199
200 return false;
201}
202
204 // Check for INT_MIN integers
205 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
206 return !CI->isMinValue(/*isSigned=*/true);
207
208 // Check for FP which are bitcasted from INT_MIN integers
209 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
210 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
211
212 // Check that vectors don't contain INT_MIN
213 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
214 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
216 if (!Elt || !Elt->isNotMinSignedValue())
217 return false;
218 }
219 return true;
220 }
221
222 // Check for splats that aren't INT_MIN
223 if (getType()->isVectorTy())
224 if (const auto *SplatVal = getSplatValue())
225 return SplatVal->isNotMinSignedValue();
226
227 // It *may* contain INT_MIN, we can't tell.
228 return false;
229}
230
232 if (auto *CFP = dyn_cast<ConstantFP>(this))
233 return CFP->getValueAPF().isFiniteNonZero();
234
235 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
236 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
238 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
239 return false;
240 }
241 return true;
242 }
243
244 if (getType()->isVectorTy())
245 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
246 return SplatCFP->isFiniteNonZeroFP();
247
248 // It *may* contain finite non-zero, we can't tell.
249 return false;
250}
251
253 if (auto *CFP = dyn_cast<ConstantFP>(this))
254 return CFP->getValueAPF().isNormal();
255
256 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
257 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
259 if (!CFP || !CFP->getValueAPF().isNormal())
260 return false;
261 }
262 return true;
263 }
264
265 if (getType()->isVectorTy())
266 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
267 return SplatCFP->isNormalFP();
268
269 // It *may* contain a normal fp value, we can't tell.
270 return false;
271}
272
274 if (auto *CFP = dyn_cast<ConstantFP>(this))
275 return CFP->getValueAPF().getExactInverse(nullptr);
276
277 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
278 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
280 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
281 return false;
282 }
283 return true;
284 }
285
286 if (getType()->isVectorTy())
287 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
288 return SplatCFP->hasExactInverseFP();
289
290 // It *may* have an exact inverse fp value, we can't tell.
291 return false;
292}
293
294bool Constant::isNaN() const {
295 if (auto *CFP = dyn_cast<ConstantFP>(this))
296 return CFP->isNaN();
297
298 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
299 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
301 if (!CFP || !CFP->isNaN())
302 return false;
303 }
304 return true;
305 }
306
307 if (getType()->isVectorTy())
308 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
309 return SplatCFP->isNaN();
310
311 // It *may* be NaN, we can't tell.
312 return false;
313}
314
316 // Are they fully identical?
317 if (this == Y)
318 return true;
319
320 // The input value must be a vector constant with the same type.
321 auto *VTy = dyn_cast<VectorType>(getType());
322 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
323 return false;
324
325 // TODO: Compare pointer constants?
326 if (!(VTy->getElementType()->isIntegerTy() ||
327 VTy->getElementType()->isFloatingPointTy()))
328 return false;
329
330 // They may still be identical element-wise (if they have `undef`s).
331 // Bitcast to integer to allow exact bitwise comparison for all types.
332 Type *IntTy = VectorType::getInteger(VTy);
333 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
336 return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));
337}
338
339static bool
341 function_ref<bool(const Constant *)> HasFn) {
342 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
343 if (HasFn(C))
344 return true;
346 return false;
347 if (isa<ScalableVectorType>(C->getType()))
348 return false;
349
350 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
351 i != e; ++i) {
352 if (Constant *Elem = C->getAggregateElement(i))
353 if (HasFn(Elem))
354 return true;
355 }
356 }
357
358 return false;
359}
360
363 this, [&](const auto *C) { return isa<UndefValue>(C); });
364}
365
368 this, [&](const auto *C) { return isa<PoisonValue>(C); });
369}
370
372 return containsUndefinedElement(this, [&](const auto *C) {
373 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
374 });
375}
376
378 if (isa<ConstantInt>(this) || isa<ConstantFP>(this))
379 return false;
380
381 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
382 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
384 return true;
385 }
386 return false;
387}
388
389/// Constructor to create a '0' constant of arbitrary type.
391 switch (Ty->getTypeID()) {
393 return ConstantInt::get(Ty, 0);
394 case Type::HalfTyID:
395 case Type::BFloatTyID:
396 case Type::FloatTyID:
397 case Type::DoubleTyID:
399 case Type::FP128TyID:
401 return ConstantFP::get(Ty->getContext(),
402 APFloat::getZero(Ty->getFltSemantics()));
405 case Type::StructTyID:
406 case Type::ArrayTyID:
410 case Type::TokenTyID:
411 return ConstantTokenNone::get(Ty->getContext());
414 default:
415 // Function, Label, or Opaque type?
416 llvm_unreachable("Cannot create a null constant of that type!");
417 }
418}
419
421 Type *ScalarTy = Ty->getScalarType();
422
423 // Create the base integer constant.
424 Constant *C = ConstantInt::get(Ty->getContext(), V);
425
426 // Convert an integer to a pointer, if necessary.
427 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
429
430 // Broadcast a scalar to a vector, if necessary.
431 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
432 C = ConstantVector::getSplat(VTy->getElementCount(), C);
433
434 return C;
435}
436
438 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
439 return ConstantInt::get(Ty->getContext(),
440 APInt::getAllOnes(ITy->getBitWidth()));
441
442 if (Ty->isFloatingPointTy()) {
443 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
444 return ConstantFP::get(Ty->getContext(), FL);
445 }
446
447 VectorType *VTy = cast<VectorType>(Ty);
448 return ConstantVector::getSplat(VTy->getElementCount(),
449 getAllOnesValue(VTy->getElementType()));
450}
451
453 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
454 "Must be an aggregate/vector constant");
455
456 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
457 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
458
459 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
460 return Elt < CAZ->getElementCount().getKnownMinValue()
461 ? CAZ->getElementValue(Elt)
462 : nullptr;
463
464 if (const auto *CI = dyn_cast<ConstantInt>(this))
465 return Elt < cast<VectorType>(getType())
466 ->getElementCount()
467 .getKnownMinValue()
468 ? ConstantInt::get(getContext(), CI->getValue())
469 : nullptr;
470
471 if (const auto *CFP = dyn_cast<ConstantFP>(this))
472 return Elt < cast<VectorType>(getType())
473 ->getElementCount()
474 .getKnownMinValue()
475 ? ConstantFP::get(getContext(), CFP->getValue())
476 : nullptr;
477
478 // FIXME: getNumElements() will fail for non-fixed vector types.
480 return nullptr;
481
482 if (const auto *PV = dyn_cast<PoisonValue>(this))
483 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
484
485 if (const auto *UV = dyn_cast<UndefValue>(this))
486 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
487
488 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
489 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
490 : nullptr;
491
492 return nullptr;
493}
494
496 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
498 // Check if the constant fits into an uint64_t.
499 if (CI->getValue().getActiveBits() > 64)
500 return nullptr;
501 return getAggregateElement(CI->getZExtValue());
502 }
503 return nullptr;
504}
505
507 /// First call destroyConstantImpl on the subclass. This gives the subclass
508 /// a chance to remove the constant from any maps/pools it's contained in.
509 switch (getValueID()) {
510 default:
511 llvm_unreachable("Not a constant!");
512#define HANDLE_CONSTANT(Name) \
513 case Value::Name##Val: \
514 cast<Name>(this)->destroyConstantImpl(); \
515 break;
516#include "llvm/IR/Value.def"
517 }
518
519 // When a Constant is destroyed, there may be lingering
520 // references to the constant by other constants in the constant pool. These
521 // constants are implicitly dependent on the module that is being deleted,
522 // but they don't know that. Because we only find out when the CPV is
523 // deleted, we must now notify all of our users (that should only be
524 // Constants) that they are, in fact, invalid now and should be deleted.
525 //
526 while (!use_empty()) {
527 Value *V = user_back();
528#ifndef NDEBUG // Only in -g mode...
529 if (!isa<Constant>(V)) {
530 dbgs() << "While deleting: " << *this
531 << "\n\nUse still stuck around after Def is destroyed: " << *V
532 << "\n\n";
533 }
534#endif
535 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
536 cast<Constant>(V)->destroyConstant();
537
538 // The constant should remove itself from our use list...
539 assert((use_empty() || user_back() != V) && "Constant not removed!");
540 }
541
542 // Value has no outstanding references it is safe to delete it now...
543 deleteConstant(this);
544}
545
547 switch (C->getValueID()) {
548 case Constant::ConstantIntVal:
549 delete static_cast<ConstantInt *>(C);
550 break;
551 case Constant::ConstantFPVal:
552 delete static_cast<ConstantFP *>(C);
553 break;
554 case Constant::ConstantAggregateZeroVal:
555 delete static_cast<ConstantAggregateZero *>(C);
556 break;
557 case Constant::ConstantArrayVal:
558 delete static_cast<ConstantArray *>(C);
559 break;
560 case Constant::ConstantStructVal:
561 delete static_cast<ConstantStruct *>(C);
562 break;
563 case Constant::ConstantVectorVal:
564 delete static_cast<ConstantVector *>(C);
565 break;
566 case Constant::ConstantPointerNullVal:
567 delete static_cast<ConstantPointerNull *>(C);
568 break;
569 case Constant::ConstantDataArrayVal:
570 delete static_cast<ConstantDataArray *>(C);
571 break;
572 case Constant::ConstantDataVectorVal:
573 delete static_cast<ConstantDataVector *>(C);
574 break;
575 case Constant::ConstantTokenNoneVal:
576 delete static_cast<ConstantTokenNone *>(C);
577 break;
578 case Constant::BlockAddressVal:
579 delete static_cast<BlockAddress *>(C);
580 break;
581 case Constant::DSOLocalEquivalentVal:
582 delete static_cast<DSOLocalEquivalent *>(C);
583 break;
584 case Constant::NoCFIValueVal:
585 delete static_cast<NoCFIValue *>(C);
586 break;
587 case Constant::ConstantPtrAuthVal:
588 delete static_cast<ConstantPtrAuth *>(C);
589 break;
590 case Constant::UndefValueVal:
591 delete static_cast<UndefValue *>(C);
592 break;
593 case Constant::PoisonValueVal:
594 delete static_cast<PoisonValue *>(C);
595 break;
596 case Constant::ConstantExprVal:
598 delete static_cast<CastConstantExpr *>(C);
599 else if (isa<BinaryConstantExpr>(C))
600 delete static_cast<BinaryConstantExpr *>(C);
602 delete static_cast<ExtractElementConstantExpr *>(C);
604 delete static_cast<InsertElementConstantExpr *>(C);
606 delete static_cast<ShuffleVectorConstantExpr *>(C);
608 delete static_cast<GetElementPtrConstantExpr *>(C);
609 else
610 llvm_unreachable("Unexpected constant expr");
611 break;
612 default:
613 llvm_unreachable("Unexpected constant");
614 }
615}
616
617/// Check if C contains a GlobalValue for which Predicate is true.
618static bool
620 bool (*Predicate)(const GlobalValue *)) {
623 WorkList.push_back(C);
624 Visited.insert(C);
625
626 while (!WorkList.empty()) {
627 const Constant *WorkItem = WorkList.pop_back_val();
628 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
629 if (Predicate(GV))
630 return true;
631 for (const Value *Op : WorkItem->operands()) {
632 const Constant *ConstOp = dyn_cast<Constant>(Op);
633 if (!ConstOp)
634 continue;
635 if (Visited.insert(ConstOp).second)
636 WorkList.push_back(ConstOp);
637 }
638 }
639 return false;
640}
641
643 auto DLLImportPredicate = [](const GlobalValue *GV) {
644 return GV->isThreadLocal();
645 };
646 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
647}
648
650 auto DLLImportPredicate = [](const GlobalValue *GV) {
651 return GV->hasDLLImportStorageClass();
652 };
653 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
654}
655
657 for (const User *U : users()) {
658 const Constant *UC = dyn_cast<Constant>(U);
659 if (!UC || isa<GlobalValue>(UC))
660 return true;
661
662 if (UC->isConstantUsed())
663 return true;
664 }
665 return false;
666}
667
669 return getRelocationInfo() == GlobalRelocation;
670}
671
673 return getRelocationInfo() != NoRelocation;
674}
675
676Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
677 if (isa<GlobalValue>(this))
678 return GlobalRelocation; // Global reference.
679
680 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
681 return BA->getFunction()->getRelocationInfo();
682
683 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
684 if (CE->getOpcode() == Instruction::Sub) {
685 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
686 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
687 if (LHS && RHS &&
688 (LHS->getOpcode() == Instruction::PtrToInt ||
689 LHS->getOpcode() == Instruction::PtrToAddr) &&
690 (RHS->getOpcode() == Instruction::PtrToInt ||
691 RHS->getOpcode() == Instruction::PtrToAddr)) {
692 Constant *LHSOp0 = LHS->getOperand(0);
693 Constant *RHSOp0 = RHS->getOperand(0);
694
695 // While raw uses of blockaddress need to be relocated, differences
696 // between two of them don't when they are for labels in the same
697 // function. This is a common idiom when creating a table for the
698 // indirect goto extension, so we handle it efficiently here.
699 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
700 cast<BlockAddress>(LHSOp0)->getFunction() ==
702 return NoRelocation;
703
704 // Relative pointers do not need to be dynamically relocated.
705 if (auto *RHSGV =
707 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
708 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
709 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
710 return LocalRelocation;
711 } else if (isa<DSOLocalEquivalent>(LHS)) {
712 if (RHSGV->isDSOLocal())
713 return LocalRelocation;
714 }
715 }
716 }
717 }
718 }
719
720 PossibleRelocationsTy Result = NoRelocation;
721 for (const Value *Op : operands())
722 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
723
724 return Result;
725}
726
727/// Return true if the specified constantexpr is dead. This involves
728/// recursively traversing users of the constantexpr.
729/// If RemoveDeadUsers is true, also remove dead users at the same time.
730static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
731 if (isa<GlobalValue>(C)) return false; // Cannot remove this
732
733 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
734 while (I != E) {
736 if (!User) return false; // Non-constant usage;
737 if (!constantIsDead(User, RemoveDeadUsers))
738 return false; // Constant wasn't dead
739
740 // Just removed User, so the iterator was invalidated.
741 // Since we return immediately upon finding a live user, we can always
742 // restart from user_begin().
743 if (RemoveDeadUsers)
744 I = C->user_begin();
745 else
746 ++I;
747 }
748
749 if (RemoveDeadUsers) {
750 // If C is only used by metadata, it should not be preserved but should
751 // have its uses replaced.
753 const_cast<Constant *>(C)->destroyConstant();
754 }
755
756 return true;
757}
758
761 Value::const_user_iterator LastNonDeadUser = E;
762 while (I != E) {
764 if (!User) {
765 LastNonDeadUser = I;
766 ++I;
767 continue;
768 }
769
770 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
771 // If the constant wasn't dead, remember that this was the last live use
772 // and move on to the next constant.
773 LastNonDeadUser = I;
774 ++I;
775 continue;
776 }
777
778 // If the constant was dead, then the iterator is invalidated.
779 if (LastNonDeadUser == E)
780 I = user_begin();
781 else
782 I = std::next(LastNonDeadUser);
783 }
784}
785
786bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
787
788bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
789
790bool Constant::hasNLiveUses(unsigned N) const {
791 unsigned NumUses = 0;
792 for (const Use &U : uses()) {
793 const Constant *User = dyn_cast<Constant>(U.getUser());
794 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
795 ++NumUses;
796
797 if (NumUses > N)
798 return false;
799 }
800 }
801 return NumUses == N;
802}
803
805 assert(C && Replacement && "Expected non-nullptr constant arguments");
806 Type *Ty = C->getType();
807 if (match(C, m_Undef())) {
808 assert(Ty == Replacement->getType() && "Expected matching types");
809 return Replacement;
810 }
811
812 // Don't know how to deal with this constant.
813 auto *VTy = dyn_cast<FixedVectorType>(Ty);
814 if (!VTy)
815 return C;
816
817 unsigned NumElts = VTy->getNumElements();
818 SmallVector<Constant *, 32> NewC(NumElts);
819 for (unsigned i = 0; i != NumElts; ++i) {
820 Constant *EltC = C->getAggregateElement(i);
821 assert((!EltC || EltC->getType() == Replacement->getType()) &&
822 "Expected matching types");
823 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
824 }
825 return ConstantVector::get(NewC);
826}
827
829 assert(C && Other && "Expected non-nullptr constant arguments");
830 if (match(C, m_Undef()))
831 return C;
832
833 Type *Ty = C->getType();
834 if (match(Other, m_Undef()))
835 return UndefValue::get(Ty);
836
837 auto *VTy = dyn_cast<FixedVectorType>(Ty);
838 if (!VTy)
839 return C;
840
841 Type *EltTy = VTy->getElementType();
842 unsigned NumElts = VTy->getNumElements();
843 assert(isa<FixedVectorType>(Other->getType()) &&
844 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
845 "Type mismatch");
846
847 bool FoundExtraUndef = false;
848 SmallVector<Constant *, 32> NewC(NumElts);
849 for (unsigned I = 0; I != NumElts; ++I) {
850 NewC[I] = C->getAggregateElement(I);
851 Constant *OtherEltC = Other->getAggregateElement(I);
852 assert(NewC[I] && OtherEltC && "Unknown vector element");
853 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
854 NewC[I] = UndefValue::get(EltTy);
855 FoundExtraUndef = true;
856 }
857 }
858 if (FoundExtraUndef)
859 return ConstantVector::get(NewC);
860 return C;
861}
862
864 if (isa<UndefValue>(this))
865 return false;
866 if (isa<ConstantData>(this))
867 return true;
868 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
869 for (const Value *Op : operand_values())
871 return false;
872 return true;
873 }
874 return false;
875}
876
877//===----------------------------------------------------------------------===//
878// ConstantInt
879//===----------------------------------------------------------------------===//
880
881ConstantInt::ConstantInt(Type *Ty, const APInt &V)
882 : ConstantData(Ty, ConstantIntVal), Val(V) {
883 assert(V.getBitWidth() ==
884 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
885 "Invalid constant for type");
886}
887
888ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
889 LLVMContextImpl *pImpl = Context.pImpl;
890 if (!pImpl->TheTrueVal)
891 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
892 return pImpl->TheTrueVal;
893}
894
895ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
896 LLVMContextImpl *pImpl = Context.pImpl;
897 if (!pImpl->TheFalseVal)
898 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
899 return pImpl->TheFalseVal;
900}
901
902ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
903 return V ? getTrue(Context) : getFalse(Context);
904}
905
907 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
908 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
909 if (auto *VTy = dyn_cast<VectorType>(Ty))
910 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
911 return TrueC;
912}
913
915 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
916 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
917 if (auto *VTy = dyn_cast<VectorType>(Ty))
918 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
919 return FalseC;
920}
921
923 return V ? getTrue(Ty) : getFalse(Ty);
924}
925
926// Get a ConstantInt from an APInt.
927ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
928 // get an existing value or the insertion position
929 LLVMContextImpl *pImpl = Context.pImpl;
930 std::unique_ptr<ConstantInt> &Slot =
931 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
932 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
933 : pImpl->IntConstants[V];
934 if (!Slot) {
935 // Get the corresponding integer type for the bit width of the value.
936 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
937 Slot.reset(new ConstantInt(ITy, V));
938 }
939 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
940 return Slot.get();
941}
942
943// Get a ConstantInt vector with each lane set to the same APInt.
944ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
945 const APInt &V) {
946 // Get an existing value or the insertion position.
947 std::unique_ptr<ConstantInt> &Slot =
948 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
949 if (!Slot) {
950 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
951 VectorType *VTy = VectorType::get(ITy, EC);
952 Slot.reset(new ConstantInt(VTy, V));
953 }
954
955#ifndef NDEBUG
956 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
957 VectorType *VTy = VectorType::get(ITy, EC);
958 assert(Slot->getType() == VTy);
959#endif
960 return Slot.get();
961}
962
963Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
964 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
965
966 // For vectors, broadcast the value.
967 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
968 return ConstantVector::getSplat(VTy->getElementCount(), C);
969
970 return C;
971}
972
973ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
974 // TODO: Avoid implicit trunc?
975 // See https://github.com/llvm/llvm-project/issues/112510.
976 return get(Ty->getContext(),
977 APInt(Ty->getBitWidth(), V, isSigned, /*implicitTrunc=*/true));
978}
979
980Constant *ConstantInt::get(Type *Ty, const APInt& V) {
981 ConstantInt *C = get(Ty->getContext(), V);
982 assert(C->getType() == Ty->getScalarType() &&
983 "ConstantInt type doesn't match the type implied by its value!");
984
985 // For vectors, broadcast the value.
986 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
987 return ConstantVector::getSplat(VTy->getElementCount(), C);
988
989 return C;
990}
991
992ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
993 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
994}
995
996/// Remove the constant from the constant table.
997void ConstantInt::destroyConstantImpl() {
998 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
999}
1000
1001//===----------------------------------------------------------------------===//
1002// ConstantFP
1003//===----------------------------------------------------------------------===//
1004
1005Constant *ConstantFP::get(Type *Ty, double V) {
1006 LLVMContext &Context = Ty->getContext();
1007
1008 APFloat FV(V);
1009 bool ignored;
1010 FV.convert(Ty->getScalarType()->getFltSemantics(),
1012 Constant *C = get(Context, FV);
1013
1014 // For vectors, broadcast the value.
1015 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1016 return ConstantVector::getSplat(VTy->getElementCount(), C);
1017
1018 return C;
1019}
1020
1021Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
1022 ConstantFP *C = get(Ty->getContext(), V);
1023 assert(C->getType() == Ty->getScalarType() &&
1024 "ConstantFP type doesn't match the type implied by its value!");
1025
1026 // For vectors, broadcast the value.
1027 if (auto *VTy = dyn_cast<VectorType>(Ty))
1028 return ConstantVector::getSplat(VTy->getElementCount(), C);
1029
1030 return C;
1031}
1032
1033Constant *ConstantFP::get(Type *Ty, StringRef Str) {
1034 LLVMContext &Context = Ty->getContext();
1035
1036 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1037 Constant *C = get(Context, FV);
1038
1039 // For vectors, broadcast the value.
1040 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1041 return ConstantVector::getSplat(VTy->getElementCount(), C);
1042
1043 return C;
1044}
1045
1046Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1047 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1048 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1049 Constant *C = get(Ty->getContext(), NaN);
1050
1051 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1052 return ConstantVector::getSplat(VTy->getElementCount(), C);
1053
1054 return C;
1055}
1056
1057Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1058 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1059 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1060 Constant *C = get(Ty->getContext(), NaN);
1061
1062 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1063 return ConstantVector::getSplat(VTy->getElementCount(), C);
1064
1065 return C;
1066}
1067
1068Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1069 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1070 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1071 Constant *C = get(Ty->getContext(), NaN);
1072
1073 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1074 return ConstantVector::getSplat(VTy->getElementCount(), C);
1075
1076 return C;
1077}
1078
1079Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1080 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1081 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1082 Constant *C = get(Ty->getContext(), NegZero);
1083
1084 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1085 return ConstantVector::getSplat(VTy->getElementCount(), C);
1086
1087 return C;
1088}
1089
1090
1091// ConstantFP accessors.
1092ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1093 LLVMContextImpl* pImpl = Context.pImpl;
1094
1095 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1096
1097 if (!Slot) {
1098 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1099 Slot.reset(new ConstantFP(Ty, V));
1100 }
1101
1102 return Slot.get();
1103}
1104
1105// Get a ConstantFP vector with each lane set to the same APFloat.
1106ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1107 const APFloat &V) {
1108 // Get an existing value or the insertion position.
1109 std::unique_ptr<ConstantFP> &Slot =
1110 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1111 if (!Slot) {
1112 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1113 VectorType *VTy = VectorType::get(EltTy, EC);
1114 Slot.reset(new ConstantFP(VTy, V));
1115 }
1116
1117#ifndef NDEBUG
1118 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1119 VectorType *VTy = VectorType::get(EltTy, EC);
1120 assert(Slot->getType() == VTy);
1121#endif
1122 return Slot.get();
1123}
1124
1126 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1127 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1128
1129 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1130 return ConstantVector::getSplat(VTy->getElementCount(), C);
1131
1132 return C;
1133}
1134
1135ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1136 : ConstantData(Ty, ConstantFPVal), Val(V) {
1137 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1138 "FP type Mismatch");
1139}
1140
1142 return Val.bitwiseIsEqual(V);
1143}
1144
1145/// Remove the constant from the constant table.
1146void ConstantFP::destroyConstantImpl() {
1147 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1148}
1149
1150//===----------------------------------------------------------------------===//
1151// ConstantAggregateZero Implementation
1152//===----------------------------------------------------------------------===//
1153
1155 if (auto *AT = dyn_cast<ArrayType>(getType()))
1156 return Constant::getNullValue(AT->getElementType());
1157 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1158}
1159
1161 return Constant::getNullValue(getType()->getStructElementType(Elt));
1162}
1163
1169
1172 return getSequentialElement();
1173 return getStructElement(Idx);
1174}
1175
1177 Type *Ty = getType();
1178 if (auto *AT = dyn_cast<ArrayType>(Ty))
1179 return ElementCount::getFixed(AT->getNumElements());
1180 if (auto *VT = dyn_cast<VectorType>(Ty))
1181 return VT->getElementCount();
1182 return ElementCount::getFixed(Ty->getStructNumElements());
1183}
1184
1185//===----------------------------------------------------------------------===//
1186// UndefValue Implementation
1187//===----------------------------------------------------------------------===//
1188
1191 return UndefValue::get(ATy->getElementType());
1192 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1193}
1194
1195UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1196 return UndefValue::get(getType()->getStructElementType(Elt));
1197}
1198
1201 return getSequentialElement();
1202 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1203}
1204
1205UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1207 return getSequentialElement();
1208 return getStructElement(Idx);
1209}
1210
1212 Type *Ty = getType();
1213 if (auto *AT = dyn_cast<ArrayType>(Ty))
1214 return AT->getNumElements();
1215 if (auto *VT = dyn_cast<VectorType>(Ty))
1216 return cast<FixedVectorType>(VT)->getNumElements();
1217 return Ty->getStructNumElements();
1218}
1219
1220//===----------------------------------------------------------------------===//
1221// PoisonValue Implementation
1222//===----------------------------------------------------------------------===//
1223
1226 return PoisonValue::get(ATy->getElementType());
1227 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1228}
1229
1230PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1231 return PoisonValue::get(getType()->getStructElementType(Elt));
1232}
1233
1236 return getSequentialElement();
1237 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1238}
1239
1240PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1242 return getSequentialElement();
1243 return getStructElement(Idx);
1244}
1245
1246//===----------------------------------------------------------------------===//
1247// ConstantXXX Classes
1248//===----------------------------------------------------------------------===//
1249
1250template <typename ItTy, typename EltTy>
1251static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1252 for (; Start != End; ++Start)
1253 if (*Start != Elt)
1254 return false;
1255 return true;
1256}
1257
1258template <typename SequentialTy, typename ElementTy>
1260 assert(!V.empty() && "Cannot get empty int sequence.");
1261
1263 for (Constant *C : V)
1264 if (auto *CI = dyn_cast<ConstantInt>(C))
1265 Elts.push_back(CI->getZExtValue());
1266 else
1267 return nullptr;
1268 return SequentialTy::get(V[0]->getContext(), Elts);
1269}
1270
1271template <typename SequentialTy, typename ElementTy>
1273 assert(!V.empty() && "Cannot get empty FP sequence.");
1274
1276 for (Constant *C : V)
1277 if (auto *CFP = dyn_cast<ConstantFP>(C))
1278 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1279 else
1280 return nullptr;
1281 return SequentialTy::getFP(V[0]->getType(), Elts);
1282}
1283
1284template <typename SequenceTy>
1287 // We speculatively build the elements here even if it turns out that there is
1288 // a constantexpr or something else weird, since it is so uncommon for that to
1289 // happen.
1290 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1291 if (CI->getType()->isIntegerTy(8))
1293 else if (CI->getType()->isIntegerTy(16))
1295 else if (CI->getType()->isIntegerTy(32))
1297 else if (CI->getType()->isIntegerTy(64))
1299 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1300 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1302 else if (CFP->getType()->isFloatTy())
1304 else if (CFP->getType()->isDoubleTy())
1306 }
1307
1308 return nullptr;
1309}
1310
1314 : Constant(T, VT, AllocInfo) {
1315 llvm::copy(V, op_begin());
1316
1317 // Check that types match, unless this is an opaque struct.
1318 if (auto *ST = dyn_cast<StructType>(T)) {
1319 if (ST->isOpaque())
1320 return;
1321 for (unsigned I = 0, E = V.size(); I != E; ++I)
1322 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1323 "Initializer for struct element doesn't match!");
1324 }
1325}
1326
1327ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1329 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1330 assert(V.size() == T->getNumElements() &&
1331 "Invalid initializer for constant array");
1332}
1333
1335 if (Constant *C = getImpl(Ty, V))
1336 return C;
1337 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1338}
1339
1340Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1341 // Empty arrays are canonicalized to ConstantAggregateZero.
1342 if (V.empty())
1343 return ConstantAggregateZero::get(Ty);
1344
1345 for (Constant *C : V) {
1346 assert(C->getType() == Ty->getElementType() &&
1347 "Wrong type in array element initializer");
1348 (void)C;
1349 }
1350
1351 // If this is an all-zero array, return a ConstantAggregateZero object. If
1352 // all undef, return an UndefValue, if "all simple", then return a
1353 // ConstantDataArray.
1354 Constant *C = V[0];
1355 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1356 return PoisonValue::get(Ty);
1357
1358 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1359 return UndefValue::get(Ty);
1360
1361 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1362 return ConstantAggregateZero::get(Ty);
1363
1364 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1365 // the element type is compatible with ConstantDataVector. If so, use it.
1368
1369 // Otherwise, we really do want to create a ConstantArray.
1370 return nullptr;
1371}
1372
1375 bool Packed) {
1376 unsigned VecSize = V.size();
1377 SmallVector<Type*, 16> EltTypes(VecSize);
1378 for (unsigned i = 0; i != VecSize; ++i)
1379 EltTypes[i] = V[i]->getType();
1380
1381 return StructType::get(Context, EltTypes, Packed);
1382}
1383
1384
1386 bool Packed) {
1387 assert(!V.empty() &&
1388 "ConstantStruct::getTypeForElements cannot be called on empty list");
1389 return getTypeForElements(V[0]->getContext(), V, Packed);
1390}
1391
1392ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1394 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1395 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1396 "Invalid initializer for constant struct");
1397}
1398
1399// ConstantStruct accessors.
1401 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1402 "Incorrect # elements specified to ConstantStruct::get");
1403
1404 // Create a ConstantAggregateZero value if all elements are zeros.
1405 bool isZero = true;
1406 bool isUndef = false;
1407 bool isPoison = false;
1408
1409 if (!V.empty()) {
1410 isUndef = isa<UndefValue>(V[0]);
1411 isPoison = isa<PoisonValue>(V[0]);
1412 isZero = V[0]->isNullValue();
1413 // PoisonValue inherits UndefValue, so its check is not necessary.
1414 if (isUndef || isZero) {
1415 for (Constant *C : V) {
1416 if (!C->isNullValue())
1417 isZero = false;
1418 if (!isa<PoisonValue>(C))
1419 isPoison = false;
1421 isUndef = false;
1422 }
1423 }
1424 }
1425 if (isZero)
1426 return ConstantAggregateZero::get(ST);
1427 if (isPoison)
1428 return PoisonValue::get(ST);
1429 if (isUndef)
1430 return UndefValue::get(ST);
1431
1432 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1433}
1434
1435ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1437 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1438 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1439 "Invalid initializer for constant vector");
1440}
1441
1442// ConstantVector accessors.
1444 if (Constant *C = getImpl(V))
1445 return C;
1446 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1447 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1448}
1449
1450Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1451 assert(!V.empty() && "Vectors can't be empty");
1452 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1453
1454 // If this is an all-undef or all-zero vector, return a
1455 // ConstantAggregateZero or UndefValue.
1456 Constant *C = V[0];
1457 bool isZero = C->isNullValue();
1458 bool isUndef = isa<UndefValue>(C);
1459 bool isPoison = isa<PoisonValue>(C);
1462
1463 if (isZero || isUndef || isSplatFP || isSplatInt) {
1464 for (unsigned i = 1, e = V.size(); i != e; ++i)
1465 if (V[i] != C) {
1466 isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;
1467 break;
1468 }
1469 }
1470
1471 if (isZero)
1473 if (isPoison)
1474 return PoisonValue::get(T);
1475 if (isUndef)
1476 return UndefValue::get(T);
1477 if (isSplatFP)
1478 return ConstantFP::get(C->getContext(), T->getElementCount(),
1479 cast<ConstantFP>(C)->getValue());
1480 if (isSplatInt)
1481 return ConstantInt::get(C->getContext(), T->getElementCount(),
1482 cast<ConstantInt>(C)->getValue());
1483
1484 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1485 // the element type is compatible with ConstantDataVector. If so, use it.
1488
1489 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1490 // the operand list contains a ConstantExpr or something else strange.
1491 return nullptr;
1492}
1493
1495 if (!EC.isScalable()) {
1496 // Maintain special handling of zero.
1497 if (!V->isNullValue()) {
1499 return ConstantInt::get(V->getContext(), EC,
1500 cast<ConstantInt>(V)->getValue());
1502 return ConstantFP::get(V->getContext(), EC,
1503 cast<ConstantFP>(V)->getValue());
1504 }
1505
1506 // If this splat is compatible with ConstantDataVector, use it instead of
1507 // ConstantVector.
1508 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1510 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1511
1512 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1513 return get(Elts);
1514 }
1515
1516 // Maintain special handling of zero.
1517 if (!V->isNullValue()) {
1519 return ConstantInt::get(V->getContext(), EC,
1520 cast<ConstantInt>(V)->getValue());
1522 return ConstantFP::get(V->getContext(), EC,
1523 cast<ConstantFP>(V)->getValue());
1524 }
1525
1526 Type *VTy = VectorType::get(V->getType(), EC);
1527
1528 if (V->isNullValue())
1529 return ConstantAggregateZero::get(VTy);
1530 if (isa<PoisonValue>(V))
1531 return PoisonValue::get(VTy);
1532 if (isa<UndefValue>(V))
1533 return UndefValue::get(VTy);
1534
1535 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1536
1537 // Move scalar into vector.
1538 Constant *PoisonV = PoisonValue::get(VTy);
1539 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1540 // Build shuffle mask to perform the splat.
1541 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1542 // Splat.
1543 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1544}
1545
1546ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1547 LLVMContextImpl *pImpl = Context.pImpl;
1548 if (!pImpl->TheNoneToken)
1549 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1550 return pImpl->TheNoneToken.get();
1551}
1552
1553/// Remove the constant from the constant table.
1554void ConstantTokenNone::destroyConstantImpl() {
1555 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1556}
1557
1558// Utility function for determining if a ConstantExpr is a CastOp or not. This
1559// can't be inline because we don't want to #include Instruction.h into
1560// Constant.h
1562
1566
1568 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1569}
1570
1572 bool OnlyIfReduced, Type *SrcTy) const {
1573 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1574
1575 // If no operands changed return self.
1576 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1577 return const_cast<ConstantExpr*>(this);
1578
1579 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1580 switch (getOpcode()) {
1581 case Instruction::Trunc:
1582 case Instruction::ZExt:
1583 case Instruction::SExt:
1584 case Instruction::FPTrunc:
1585 case Instruction::FPExt:
1586 case Instruction::UIToFP:
1587 case Instruction::SIToFP:
1588 case Instruction::FPToUI:
1589 case Instruction::FPToSI:
1590 case Instruction::PtrToAddr:
1591 case Instruction::PtrToInt:
1592 case Instruction::IntToPtr:
1593 case Instruction::BitCast:
1594 case Instruction::AddrSpaceCast:
1595 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1596 case Instruction::InsertElement:
1597 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1598 OnlyIfReducedTy);
1599 case Instruction::ExtractElement:
1600 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1601 case Instruction::ShuffleVector:
1603 OnlyIfReducedTy);
1604 case Instruction::GetElementPtr: {
1605 auto *GEPO = cast<GEPOperator>(this);
1606 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1608 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1609 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1610 }
1611 default:
1612 assert(getNumOperands() == 2 && "Must be binary operator?");
1614 OnlyIfReducedTy);
1615 }
1616}
1617
1618
1619//===----------------------------------------------------------------------===//
1620// isValueValidForType implementations
1621
1623 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1624 if (Ty->isIntegerTy(1))
1625 return Val == 0 || Val == 1;
1626 return isUIntN(NumBits, Val);
1627}
1628
1630 unsigned NumBits = Ty->getIntegerBitWidth();
1631 if (Ty->isIntegerTy(1))
1632 return Val == 0 || Val == 1 || Val == -1;
1633 return isIntN(NumBits, Val);
1634}
1635
1637 // convert modifies in place, so make a copy.
1638 APFloat Val2 = APFloat(Val);
1639 bool losesInfo;
1640 switch (Ty->getTypeID()) {
1641 default:
1642 return false; // These can't be represented as floating point!
1643
1644 // FIXME rounding mode needs to be more flexible
1645 case Type::HalfTyID: {
1646 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1647 return true;
1649 return !losesInfo;
1650 }
1651 case Type::BFloatTyID: {
1652 if (&Val2.getSemantics() == &APFloat::BFloat())
1653 return true;
1655 return !losesInfo;
1656 }
1657 case Type::FloatTyID: {
1658 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1659 return true;
1661 return !losesInfo;
1662 }
1663 case Type::DoubleTyID: {
1664 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1665 &Val2.getSemantics() == &APFloat::BFloat() ||
1666 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1667 &Val2.getSemantics() == &APFloat::IEEEdouble())
1668 return true;
1670 return !losesInfo;
1671 }
1672 case Type::X86_FP80TyID:
1673 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1674 &Val2.getSemantics() == &APFloat::BFloat() ||
1675 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1676 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1678 case Type::FP128TyID:
1679 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1680 &Val2.getSemantics() == &APFloat::BFloat() ||
1681 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1682 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1683 &Val2.getSemantics() == &APFloat::IEEEquad();
1685 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1686 &Val2.getSemantics() == &APFloat::BFloat() ||
1687 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1688 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1690 }
1691}
1692
1693
1694//===----------------------------------------------------------------------===//
1695// Factory Function Implementation
1696
1697ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1698 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1699 "Cannot create an aggregate zero of non-aggregate type!");
1700
1701 std::unique_ptr<ConstantAggregateZero> &Entry =
1702 Ty->getContext().pImpl->CAZConstants[Ty];
1703 if (!Entry)
1704 Entry.reset(new ConstantAggregateZero(Ty));
1705
1706 return Entry.get();
1707}
1708
1709/// Remove the constant from the constant table.
1710void ConstantAggregateZero::destroyConstantImpl() {
1712}
1713
1714/// Remove the constant from the constant table.
1715void ConstantArray::destroyConstantImpl() {
1717}
1718
1719
1720//---- ConstantStruct::get() implementation...
1721//
1722
1723/// Remove the constant from the constant table.
1724void ConstantStruct::destroyConstantImpl() {
1726}
1727
1728/// Remove the constant from the constant table.
1729void ConstantVector::destroyConstantImpl() {
1731}
1732
1733Constant *Constant::getSplatValue(bool AllowPoison) const {
1734 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1735 if (isa<PoisonValue>(this))
1736 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1738 return getNullValue(cast<VectorType>(getType())->getElementType());
1739 if (auto *CI = dyn_cast<ConstantInt>(this))
1740 return ConstantInt::get(getContext(), CI->getValue());
1741 if (auto *CFP = dyn_cast<ConstantFP>(this))
1742 return ConstantFP::get(getContext(), CFP->getValue());
1744 return CV->getSplatValue();
1745 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1746 return CV->getSplatValue(AllowPoison);
1747
1748 // Check if this is a constant expression splat of the form returned by
1749 // ConstantVector::getSplat()
1750 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1751 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1752 isa<UndefValue>(Shuf->getOperand(1))) {
1753
1754 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1755 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1756 isa<UndefValue>(IElt->getOperand(0))) {
1757
1758 ArrayRef<int> Mask = Shuf->getShuffleMask();
1759 Constant *SplatVal = IElt->getOperand(1);
1760 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1761
1762 if (Index && Index->getValue() == 0 &&
1763 llvm::all_of(Mask, [](int I) { return I == 0; }))
1764 return SplatVal;
1765 }
1766 }
1767
1768 return nullptr;
1769}
1770
1771Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1772 // Check out first element.
1773 Constant *Elt = getOperand(0);
1774 // Then make sure all remaining elements point to the same value.
1775 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1776 Constant *OpC = getOperand(I);
1777 if (OpC == Elt)
1778 continue;
1779
1780 // Strict mode: any mismatch is not a splat.
1781 if (!AllowPoison)
1782 return nullptr;
1783
1784 // Allow poison mode: ignore poison elements.
1785 if (isa<PoisonValue>(OpC))
1786 continue;
1787
1788 // If we do not have a defined element yet, use the current operand.
1789 if (isa<PoisonValue>(Elt))
1790 Elt = OpC;
1791
1792 if (OpC != Elt)
1793 return nullptr;
1794 }
1795 return Elt;
1796}
1797
1799 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1800 return CI->getValue();
1801 // Scalable vectors can use a ConstantExpr to build a splat.
1802 if (isa<ConstantExpr>(this))
1803 return cast<ConstantInt>(this->getSplatValue())->getValue();
1804 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1805 // calling getSplatValue in release builds.
1806 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1807 const Constant *C = this->getAggregateElement(0U);
1808 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1809 return cast<ConstantInt>(C)->getValue();
1810}
1811
1813 if (auto *CI = dyn_cast<ConstantInt>(this))
1814 return ConstantRange(CI->getValue());
1815
1816 unsigned BitWidth = getType()->getScalarSizeInBits();
1817 if (!getType()->isVectorTy())
1818 return ConstantRange::getFull(BitWidth);
1819
1820 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1821 getSplatValue(/*AllowPoison=*/true)))
1822 return ConstantRange(CI->getValue());
1823
1824 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1825 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1826 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1827 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1828 return CR;
1829 }
1830
1831 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1832 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1833 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1834 Constant *Elem = CV->getOperand(I);
1835 if (!Elem)
1836 return ConstantRange::getFull(BitWidth);
1837 if (isa<PoisonValue>(Elem))
1838 continue;
1839 auto *CI = dyn_cast<ConstantInt>(Elem);
1840 if (!CI)
1841 return ConstantRange::getFull(BitWidth);
1842 CR = CR.unionWith(CI->getValue());
1843 }
1844 return CR;
1845 }
1846
1847 return ConstantRange::getFull(BitWidth);
1848}
1849
1850//---- ConstantPointerNull::get() implementation.
1851//
1852
1853ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1854 std::unique_ptr<ConstantPointerNull> &Entry =
1855 Ty->getContext().pImpl->CPNConstants[Ty];
1856 if (!Entry)
1857 Entry.reset(new ConstantPointerNull(Ty));
1858
1859 return Entry.get();
1860}
1861
1862/// Remove the constant from the constant table.
1863void ConstantPointerNull::destroyConstantImpl() {
1865}
1866
1867//---- ConstantTargetNone::get() implementation.
1868//
1869
1870ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1871 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1872 "Target extension type not allowed to have a zeroinitializer");
1873 std::unique_ptr<ConstantTargetNone> &Entry =
1874 Ty->getContext().pImpl->CTNConstants[Ty];
1875 if (!Entry)
1876 Entry.reset(new ConstantTargetNone(Ty));
1877
1878 return Entry.get();
1879}
1880
1881/// Remove the constant from the constant table.
1882void ConstantTargetNone::destroyConstantImpl() {
1884}
1885
1886UndefValue *UndefValue::get(Type *Ty) {
1887 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1888 if (!Entry)
1889 Entry.reset(new UndefValue(Ty));
1890
1891 return Entry.get();
1892}
1893
1894/// Remove the constant from the constant table.
1895void UndefValue::destroyConstantImpl() {
1896 // Free the constant and any dangling references to it.
1897 if (getValueID() == UndefValueVal) {
1898 getContext().pImpl->UVConstants.erase(getType());
1899 } else if (getValueID() == PoisonValueVal) {
1900 getContext().pImpl->PVConstants.erase(getType());
1901 }
1902 llvm_unreachable("Not a undef or a poison!");
1903}
1904
1905PoisonValue *PoisonValue::get(Type *Ty) {
1906 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1907 if (!Entry)
1908 Entry.reset(new PoisonValue(Ty));
1909
1910 return Entry.get();
1911}
1912
1913/// Remove the constant from the constant table.
1914void PoisonValue::destroyConstantImpl() {
1915 // Free the constant and any dangling references to it.
1916 getContext().pImpl->PVConstants.erase(getType());
1917}
1918
1919BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
1920 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
1921 if (!BA)
1922 BA = new BlockAddress(Ty, BB);
1923 return BA;
1924}
1925
1926BlockAddress *BlockAddress::get(BasicBlock *BB) {
1927 assert(BB->getParent() && "Block must have a parent");
1928 return get(BB->getParent()->getType(), BB);
1929}
1930
1932 assert(BB->getParent() == F && "Block not part of specified function");
1933 return get(BB->getParent()->getType(), BB);
1934}
1935
1936BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
1937 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
1938 setOperand(0, BB);
1939 BB->setHasAddressTaken(true);
1940}
1941
1942BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1943 if (!BB->hasAddressTaken())
1944 return nullptr;
1945
1946 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
1947 assert(BA && "Refcount and block address map disagree!");
1948 return BA;
1949}
1950
1951/// Remove the constant from the constant table.
1952void BlockAddress::destroyConstantImpl() {
1954 getBasicBlock()->setHasAddressTaken(false);
1955}
1956
1957Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1958 assert(From == getBasicBlock());
1959 BasicBlock *NewBB = cast<BasicBlock>(To);
1960
1961 // See if the 'new' entry already exists, if not, just update this in place
1962 // and return early.
1963 BlockAddress *&NewBA = getContext().pImpl->BlockAddresses[NewBB];
1964 if (NewBA)
1965 return NewBA;
1966
1967 getBasicBlock()->setHasAddressTaken(false);
1968
1969 // Remove the old entry, this can't cause the map to rehash (just a
1970 // tombstone will get added).
1972 NewBA = this;
1973 setOperand(0, NewBB);
1974 getBasicBlock()->setHasAddressTaken(true);
1975
1976 // If we just want to keep the existing value, then return null.
1977 // Callers know that this means we shouldn't delete this value.
1978 return nullptr;
1979}
1980
1981DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1982 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1983 if (!Equiv)
1984 Equiv = new DSOLocalEquivalent(GV);
1985
1986 assert(Equiv->getGlobalValue() == GV &&
1987 "DSOLocalFunction does not match the expected global value");
1988 return Equiv;
1989}
1990
1991DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1992 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
1993 setOperand(0, GV);
1994}
1995
1996/// Remove the constant from the constant table.
1997void DSOLocalEquivalent::destroyConstantImpl() {
1998 const GlobalValue *GV = getGlobalValue();
1999 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2000}
2001
2002Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2003 assert(From == getGlobalValue() && "Changing value does not match operand.");
2004 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2005
2006 // The replacement is with another global value.
2007 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
2008 DSOLocalEquivalent *&NewEquiv =
2010 if (NewEquiv)
2011 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2012 }
2013
2014 // If the argument is replaced with a null value, just replace this constant
2015 // with a null value.
2016 if (cast<Constant>(To)->isNullValue())
2017 return To;
2018
2019 // The replacement could be a bitcast or an alias to another function. We can
2020 // replace it with a bitcast to the dso_local_equivalent of that function.
2022 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
2023 if (NewEquiv)
2024 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2025
2026 // Replace this with the new one.
2028 NewEquiv = this;
2029 setOperand(0, Func);
2030
2031 if (Func->getType() != getType()) {
2032 // It is ok to mutate the type here because this constant should always
2033 // reflect the type of the function it's holding.
2034 mutateType(Func->getType());
2035 }
2036 return nullptr;
2037}
2038
2040 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2041 if (!NC)
2042 NC = new NoCFIValue(GV);
2043
2044 assert(NC->getGlobalValue() == GV &&
2045 "NoCFIValue does not match the expected global value");
2046 return NC;
2047}
2048
2049NoCFIValue::NoCFIValue(GlobalValue *GV)
2050 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2051 setOperand(0, GV);
2052}
2053
2054/// Remove the constant from the constant table.
2055void NoCFIValue::destroyConstantImpl() {
2056 const GlobalValue *GV = getGlobalValue();
2057 GV->getContext().pImpl->NoCFIValues.erase(GV);
2058}
2059
2060Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2061 assert(From == getGlobalValue() && "Changing value does not match operand.");
2062
2063 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2064 assert(GV && "Can only replace the operands with a global value");
2065
2066 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
2067 if (NewNC)
2068 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2069
2071 NewNC = this;
2072 setOperand(0, GV);
2073
2074 if (GV->getType() != getType())
2075 mutateType(GV->getType());
2076
2077 return nullptr;
2078}
2079
2080//---- ConstantPtrAuth::get() implementations.
2081//
2082
2084 ConstantInt *Disc, Constant *AddrDisc) {
2085 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc};
2086 ConstantPtrAuthKeyType MapKey(ArgVec);
2087 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2088 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2089}
2090
2091ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2092 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator());
2093}
2094
2095ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2096 ConstantInt *Disc, Constant *AddrDisc)
2097 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2098 assert(Ptr->getType()->isPointerTy());
2099 assert(Key->getBitWidth() == 32);
2100 assert(Disc->getBitWidth() == 64);
2101 assert(AddrDisc->getType()->isPointerTy());
2102 setOperand(0, Ptr);
2103 setOperand(1, Key);
2104 setOperand(2, Disc);
2105 setOperand(3, AddrDisc);
2106}
2107
2108/// Remove the constant from the constant table.
2109void ConstantPtrAuth::destroyConstantImpl() {
2110 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2111}
2112
2113Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2114 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2115 Constant *To = cast<Constant>(ToV);
2116
2118 Values.reserve(getNumOperands());
2119
2120 unsigned NumUpdated = 0;
2121
2122 Use *OperandList = getOperandList();
2123 unsigned OperandNo = 0;
2124 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2125 Constant *Val = cast<Constant>(O->get());
2126 if (Val == From) {
2127 OperandNo = (O - OperandList);
2128 Val = To;
2129 ++NumUpdated;
2130 }
2131 Values.push_back(Val);
2132 }
2133
2134 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2135 Values, this, From, To, NumUpdated, OperandNo);
2136}
2137
2139 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2140 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2141 return false;
2142
2143 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2144 if (!IntVal)
2145 return false;
2146
2147 return IntVal->getValue() == Value;
2148}
2149
2151 const Value *Discriminator,
2152 const DataLayout &DL) const {
2153 // If the keys are different, there's no chance for this to be compatible.
2154 if (getKey() != Key)
2155 return false;
2156
2157 // We can have 3 kinds of discriminators:
2158 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2159 // - address-only: `i64 0, ptr p` vs. `ptr p`
2160 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2161
2162 // If this constant has a simple discriminator (integer, no address), easy:
2163 // it's compatible iff the provided full discriminator is also a simple
2164 // discriminator, identical to our integer discriminator.
2166 return getDiscriminator() == Discriminator;
2167
2168 // Otherwise, we can isolate address and integer discriminator components.
2169 const Value *AddrDiscriminator = nullptr;
2170
2171 // This constant may or may not have an integer discriminator (instead of 0).
2172 if (!getDiscriminator()->isNullValue()) {
2173 // If it does, there's an implicit blend. We need to have a matching blend
2174 // intrinsic in the provided full discriminator.
2175 if (!match(Discriminator,
2177 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2178 return false;
2179 } else {
2180 // Otherwise, interpret the provided full discriminator as address-only.
2181 AddrDiscriminator = Discriminator;
2182 }
2183
2184 // Either way, we can now focus on comparing the address discriminators.
2185
2186 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2187 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2188 AddrDiscriminator = Cast->getPointerOperand();
2189
2190 // Beyond that, we're only interested in compatible pointers.
2191 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2192 return false;
2193
2194 // These are often the same constant GEP, making them trivially equivalent.
2195 if (getAddrDiscriminator() == AddrDiscriminator)
2196 return true;
2197
2198 // Finally, they may be equivalent base+offset expressions.
2199 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2201 DL, Off1, /*AllowNonInbounds=*/true);
2202
2203 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2204 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2205 DL, Off2, /*AllowNonInbounds=*/true);
2206
2207 return Base1 == Base2 && Off1 == Off2;
2208}
2209
2210//---- ConstantExpr::get() implementations.
2211//
2212
2213/// This is a utility function to handle folding of casts and lookup of the
2214/// cast in the ExprConstants map. It is used by the various get* methods below.
2216 bool OnlyIfReduced = false) {
2217 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2218 // Fold a few common cases
2219 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2220 return FC;
2221
2222 if (OnlyIfReduced)
2223 return nullptr;
2224
2225 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2226
2227 // Look up the constant in the table first to ensure uniqueness.
2229
2230 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2231}
2232
2234 bool OnlyIfReduced) {
2236 assert(Instruction::isCast(opc) && "opcode out of range");
2238 "Cast opcode not supported as constant expression");
2239 assert(C && Ty && "Null arguments to getCast");
2240 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2241
2242 switch (opc) {
2243 default:
2244 llvm_unreachable("Invalid cast opcode");
2245 case Instruction::Trunc:
2246 return getTrunc(C, Ty, OnlyIfReduced);
2247 case Instruction::PtrToAddr:
2248 return getPtrToAddr(C, Ty, OnlyIfReduced);
2249 case Instruction::PtrToInt:
2250 return getPtrToInt(C, Ty, OnlyIfReduced);
2251 case Instruction::IntToPtr:
2252 return getIntToPtr(C, Ty, OnlyIfReduced);
2253 case Instruction::BitCast:
2254 return getBitCast(C, Ty, OnlyIfReduced);
2255 case Instruction::AddrSpaceCast:
2256 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2257 }
2258}
2259
2261 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2262 return getBitCast(C, Ty);
2263 return getTrunc(C, Ty);
2264}
2265
2267 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2268 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2269 "Invalid cast");
2270
2271 if (Ty->isIntOrIntVectorTy())
2272 return getPtrToInt(S, Ty);
2273
2274 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2275 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2276 return getAddrSpaceCast(S, Ty);
2277
2278 return getBitCast(S, Ty);
2279}
2280
2282 Type *Ty) {
2283 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2284 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2285
2286 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2287 return getAddrSpaceCast(S, Ty);
2288
2289 return getBitCast(S, Ty);
2290}
2291
2292Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2293#ifndef NDEBUG
2294 bool fromVec = isa<VectorType>(C->getType());
2295 bool toVec = isa<VectorType>(Ty);
2296#endif
2297 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2298 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2299 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2300 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2301 "SrcTy must be larger than DestTy for Trunc!");
2302
2303 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2304}
2305
2307 bool OnlyIfReduced) {
2308 assert(C->getType()->isPtrOrPtrVectorTy() &&
2309 "PtrToAddr source must be pointer or pointer vector");
2310 assert(DstTy->isIntOrIntVectorTy() &&
2311 "PtrToAddr destination must be integer or integer vector");
2312 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2313 if (isa<VectorType>(C->getType()))
2314 assert(cast<VectorType>(C->getType())->getElementCount() ==
2315 cast<VectorType>(DstTy)->getElementCount() &&
2316 "Invalid cast between a different number of vector elements");
2317 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2318}
2319
2321 bool OnlyIfReduced) {
2322 assert(C->getType()->isPtrOrPtrVectorTy() &&
2323 "PtrToInt source must be pointer or pointer vector");
2324 assert(DstTy->isIntOrIntVectorTy() &&
2325 "PtrToInt destination must be integer or integer vector");
2326 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2327 if (isa<VectorType>(C->getType()))
2328 assert(cast<VectorType>(C->getType())->getElementCount() ==
2329 cast<VectorType>(DstTy)->getElementCount() &&
2330 "Invalid cast between a different number of vector elements");
2331 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2332}
2333
2335 bool OnlyIfReduced) {
2336 assert(C->getType()->isIntOrIntVectorTy() &&
2337 "IntToPtr source must be integer or integer vector");
2338 assert(DstTy->isPtrOrPtrVectorTy() &&
2339 "IntToPtr destination must be a pointer or pointer vector");
2340 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2341 if (isa<VectorType>(C->getType()))
2342 assert(cast<VectorType>(C->getType())->getElementCount() ==
2343 cast<VectorType>(DstTy)->getElementCount() &&
2344 "Invalid cast between a different number of vector elements");
2345 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2346}
2347
2349 bool OnlyIfReduced) {
2350 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2351 "Invalid constantexpr bitcast!");
2352
2353 // It is common to ask for a bitcast of a value to its own type, handle this
2354 // speedily.
2355 if (C->getType() == DstTy) return C;
2356
2357 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2358}
2359
2361 bool OnlyIfReduced) {
2362 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2363 "Invalid constantexpr addrspacecast!");
2364 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2365}
2366
2367Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2368 unsigned Flags, Type *OnlyIfReducedTy) {
2369 // Check the operands for consistency first.
2371 "Invalid opcode in binary constant expression");
2372 assert(isSupportedBinOp(Opcode) &&
2373 "Binop not supported as constant expression");
2374 assert(C1->getType() == C2->getType() &&
2375 "Operand types in binary constant expression should match");
2376
2377#ifndef NDEBUG
2378 switch (Opcode) {
2379 case Instruction::Add:
2380 case Instruction::Sub:
2381 case Instruction::Mul:
2383 "Tried to create an integer operation on a non-integer type!");
2384 break;
2385 case Instruction::And:
2386 case Instruction::Or:
2387 case Instruction::Xor:
2389 "Tried to create a logical operation on a non-integral type!");
2390 break;
2391 default:
2392 break;
2393 }
2394#endif
2395
2396 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2397 return FC;
2398
2399 if (OnlyIfReducedTy == C1->getType())
2400 return nullptr;
2401
2402 Constant *ArgVec[] = {C1, C2};
2403 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2404
2405 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2406 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2407}
2408
2409bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2410 switch (Opcode) {
2411 case Instruction::UDiv:
2412 case Instruction::SDiv:
2413 case Instruction::URem:
2414 case Instruction::SRem:
2415 case Instruction::FAdd:
2416 case Instruction::FSub:
2417 case Instruction::FMul:
2418 case Instruction::FDiv:
2419 case Instruction::FRem:
2420 case Instruction::And:
2421 case Instruction::Or:
2422 case Instruction::LShr:
2423 case Instruction::AShr:
2424 case Instruction::Shl:
2425 case Instruction::Mul:
2426 return false;
2427 case Instruction::Add:
2428 case Instruction::Sub:
2429 case Instruction::Xor:
2430 return true;
2431 default:
2432 llvm_unreachable("Argument must be binop opcode");
2433 }
2434}
2435
2436bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2437 switch (Opcode) {
2438 case Instruction::UDiv:
2439 case Instruction::SDiv:
2440 case Instruction::URem:
2441 case Instruction::SRem:
2442 case Instruction::FAdd:
2443 case Instruction::FSub:
2444 case Instruction::FMul:
2445 case Instruction::FDiv:
2446 case Instruction::FRem:
2447 case Instruction::And:
2448 case Instruction::Or:
2449 case Instruction::LShr:
2450 case Instruction::AShr:
2451 case Instruction::Shl:
2452 case Instruction::Mul:
2453 return false;
2454 case Instruction::Add:
2455 case Instruction::Sub:
2456 case Instruction::Xor:
2457 return true;
2458 default:
2459 llvm_unreachable("Argument must be binop opcode");
2460 }
2461}
2462
2463bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2464 switch (Opcode) {
2465 case Instruction::ZExt:
2466 case Instruction::SExt:
2467 case Instruction::FPTrunc:
2468 case Instruction::FPExt:
2469 case Instruction::UIToFP:
2470 case Instruction::SIToFP:
2471 case Instruction::FPToUI:
2472 case Instruction::FPToSI:
2473 return false;
2474 case Instruction::Trunc:
2475 case Instruction::PtrToAddr:
2476 case Instruction::PtrToInt:
2477 case Instruction::IntToPtr:
2478 case Instruction::BitCast:
2479 case Instruction::AddrSpaceCast:
2480 return true;
2481 default:
2482 llvm_unreachable("Argument must be cast opcode");
2483 }
2484}
2485
2486bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2487 switch (Opcode) {
2488 case Instruction::ZExt:
2489 case Instruction::SExt:
2490 case Instruction::FPTrunc:
2491 case Instruction::FPExt:
2492 case Instruction::UIToFP:
2493 case Instruction::SIToFP:
2494 case Instruction::FPToUI:
2495 case Instruction::FPToSI:
2496 return false;
2497 case Instruction::Trunc:
2498 case Instruction::PtrToAddr:
2499 case Instruction::PtrToInt:
2500 case Instruction::IntToPtr:
2501 case Instruction::BitCast:
2502 case Instruction::AddrSpaceCast:
2503 return true;
2504 default:
2505 llvm_unreachable("Argument must be cast opcode");
2506 }
2507}
2508
2510 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2511 // Note that a non-inbounds gep is used, as null isn't within any object.
2512 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2514 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2515 GEPIdx);
2516 return getPtrToInt(GEP,
2517 Type::getInt64Ty(Ty->getContext()));
2518}
2519
2521 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2522 // Note that a non-inbounds gep is used, as null isn't within any object.
2523 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2524 Constant *NullPtr =
2526 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2527 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2528 Constant *Indices[2] = {Zero, One};
2529 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2530 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2531}
2532
2534 ArrayRef<Value *> Idxs,
2535 GEPNoWrapFlags NW,
2536 std::optional<ConstantRange> InRange,
2537 Type *OnlyIfReducedTy) {
2538 assert(Ty && "Must specify element type");
2539 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2540
2541 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2542 return FC; // Fold a few common cases.
2543
2544 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2545 ;
2546
2547 // Get the result type of the getelementptr!
2549 if (OnlyIfReducedTy == ReqTy)
2550 return nullptr;
2551
2552 auto EltCount = ElementCount::getFixed(0);
2553 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2554 EltCount = VecTy->getElementCount();
2555
2556 // Look up the constant in the table first to ensure uniqueness
2557 std::vector<Constant*> ArgVec;
2558 ArgVec.reserve(1 + Idxs.size());
2559 ArgVec.push_back(C);
2560 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2561 for (; GTI != GTE; ++GTI) {
2562 auto *Idx = cast<Constant>(GTI.getOperand());
2563 assert(
2564 (!isa<VectorType>(Idx->getType()) ||
2565 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2566 "getelementptr index type missmatch");
2567
2568 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2569 Idx = Idx->getSplatValue();
2570 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2571 !Idx->getType()->isVectorTy()) {
2572 Idx = ConstantVector::getSplat(EltCount, Idx);
2573 }
2574 ArgVec.push_back(Idx);
2575 }
2576
2577 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2578 {}, Ty, InRange);
2579
2580 LLVMContextImpl *pImpl = C->getContext().pImpl;
2581 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2582}
2583
2585 Type *OnlyIfReducedTy) {
2586 assert(Val->getType()->isVectorTy() &&
2587 "Tried to create extractelement operation on non-vector type!");
2588 assert(Idx->getType()->isIntegerTy() &&
2589 "Extractelement index must be an integer type!");
2590
2592 return FC; // Fold a few common cases.
2593
2594 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2595 if (OnlyIfReducedTy == ReqTy)
2596 return nullptr;
2597
2598 // Look up the constant in the table first to ensure uniqueness
2599 Constant *ArgVec[] = { Val, Idx };
2600 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2601
2602 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2603 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2604}
2605
2607 Constant *Idx, Type *OnlyIfReducedTy) {
2608 assert(Val->getType()->isVectorTy() &&
2609 "Tried to create insertelement operation on non-vector type!");
2610 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2611 "Insertelement types must match!");
2612 assert(Idx->getType()->isIntegerTy() &&
2613 "Insertelement index must be i32 type!");
2614
2615 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2616 return FC; // Fold a few common cases.
2617
2618 if (OnlyIfReducedTy == Val->getType())
2619 return nullptr;
2620
2621 // Look up the constant in the table first to ensure uniqueness
2622 Constant *ArgVec[] = { Val, Elt, Idx };
2623 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2624
2625 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2626 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2627}
2628
2630 ArrayRef<int> Mask,
2631 Type *OnlyIfReducedTy) {
2633 "Invalid shuffle vector constant expr operands!");
2634
2635 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2636 return FC; // Fold a few common cases.
2637
2638 unsigned NElts = Mask.size();
2639 auto V1VTy = cast<VectorType>(V1->getType());
2640 Type *EltTy = V1VTy->getElementType();
2641 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2642 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2643
2644 if (OnlyIfReducedTy == ShufTy)
2645 return nullptr;
2646
2647 // Look up the constant in the table first to ensure uniqueness
2648 Constant *ArgVec[] = {V1, V2};
2649 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2650
2651 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2652 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2653}
2654
2656 assert(C->getType()->isIntOrIntVectorTy() &&
2657 "Cannot NEG a nonintegral value!");
2658 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2659}
2660
2662 assert(C->getType()->isIntOrIntVectorTy() &&
2663 "Cannot NOT a nonintegral value!");
2664 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2665}
2666
2668 bool HasNUW, bool HasNSW) {
2669 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2671 return get(Instruction::Add, C1, C2, Flags);
2672}
2673
2675 bool HasNUW, bool HasNSW) {
2676 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2678 return get(Instruction::Sub, C1, C2, Flags);
2679}
2680
2682 return get(Instruction::Xor, C1, C2);
2683}
2684
2686 Type *Ty = C->getType();
2687 const APInt *IVal;
2688 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2689 return ConstantInt::get(Ty, IVal->logBase2());
2690
2691 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2692 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2693 if (!VecTy)
2694 return nullptr;
2695
2697 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2698 Constant *Elt = C->getAggregateElement(I);
2699 if (!Elt)
2700 return nullptr;
2701 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2702 if (isa<UndefValue>(Elt)) {
2703 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2704 continue;
2705 }
2706 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2707 return nullptr;
2708 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2709 }
2710
2711 return ConstantVector::get(Elts);
2712}
2713
2715 bool AllowRHSConstant, bool NSZ) {
2716 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2717
2718 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2719 if (Instruction::isCommutative(Opcode)) {
2720 switch (Opcode) {
2721 case Instruction::Add: // X + 0 = X
2722 case Instruction::Or: // X | 0 = X
2723 case Instruction::Xor: // X ^ 0 = X
2724 return Constant::getNullValue(Ty);
2725 case Instruction::Mul: // X * 1 = X
2726 return ConstantInt::get(Ty, 1);
2727 case Instruction::And: // X & -1 = X
2728 return Constant::getAllOnesValue(Ty);
2729 case Instruction::FAdd: // X + -0.0 = X
2730 return ConstantFP::getZero(Ty, !NSZ);
2731 case Instruction::FMul: // X * 1.0 = X
2732 return ConstantFP::get(Ty, 1.0);
2733 default:
2734 llvm_unreachable("Every commutative binop has an identity constant");
2735 }
2736 }
2737
2738 // Non-commutative opcodes: AllowRHSConstant must be set.
2739 if (!AllowRHSConstant)
2740 return nullptr;
2741
2742 switch (Opcode) {
2743 case Instruction::Sub: // X - 0 = X
2744 case Instruction::Shl: // X << 0 = X
2745 case Instruction::LShr: // X >>u 0 = X
2746 case Instruction::AShr: // X >> 0 = X
2747 case Instruction::FSub: // X - 0.0 = X
2748 return Constant::getNullValue(Ty);
2749 case Instruction::SDiv: // X / 1 = X
2750 case Instruction::UDiv: // X /u 1 = X
2751 return ConstantInt::get(Ty, 1);
2752 case Instruction::FDiv: // X / 1.0 = X
2753 return ConstantFP::get(Ty, 1.0);
2754 default:
2755 return nullptr;
2756 }
2757}
2758
2760 switch (ID) {
2761 case Intrinsic::umax:
2762 return Constant::getNullValue(Ty);
2763 case Intrinsic::umin:
2764 return Constant::getAllOnesValue(Ty);
2765 case Intrinsic::smax:
2767 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2768 case Intrinsic::smin:
2770 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2771 default:
2772 return nullptr;
2773 }
2774}
2775
2777 bool AllowRHSConstant, bool NSZ) {
2778 if (I->isBinaryOp())
2779 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2781 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2782 return nullptr;
2783}
2784
2786 bool AllowLHSConstant) {
2787 switch (Opcode) {
2788 default:
2789 break;
2790
2791 case Instruction::Or: // -1 | X = -1
2792 return Constant::getAllOnesValue(Ty);
2793
2794 case Instruction::And: // 0 & X = 0
2795 case Instruction::Mul: // 0 * X = 0
2796 return Constant::getNullValue(Ty);
2797 }
2798
2799 // AllowLHSConstant must be set.
2800 if (!AllowLHSConstant)
2801 return nullptr;
2802
2803 switch (Opcode) {
2804 default:
2805 return nullptr;
2806 case Instruction::Shl: // 0 << X = 0
2807 case Instruction::LShr: // 0 >>l X = 0
2808 case Instruction::AShr: // 0 >>a X = 0
2809 case Instruction::SDiv: // 0 /s X = 0
2810 case Instruction::UDiv: // 0 /u X = 0
2811 case Instruction::URem: // 0 %u X = 0
2812 case Instruction::SRem: // 0 %s X = 0
2813 return Constant::getNullValue(Ty);
2814 }
2815}
2816
2817/// Remove the constant from the constant table.
2818void ConstantExpr::destroyConstantImpl() {
2819 getType()->getContext().pImpl->ExprConstants.remove(this);
2820}
2821
2822const char *ConstantExpr::getOpcodeName() const {
2824}
2825
2826GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2827 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2828 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2829 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2830 SrcElementTy(SrcElementTy),
2831 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2832 InRange(std::move(InRange)) {
2833 Op<0>() = C;
2834 Use *OperandList = getOperandList();
2835 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2836 OperandList[i+1] = IdxList[i];
2837}
2838
2840 return SrcElementTy;
2841}
2842
2844 return ResElementTy;
2845}
2846
2847std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2848 return InRange;
2849}
2850
2851//===----------------------------------------------------------------------===//
2852// ConstantData* implementations
2853
2856 return ATy->getElementType();
2857 return cast<VectorType>(getType())->getElementType();
2858}
2859
2863
2865 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2866 return true;
2867 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2868 switch (IT->getBitWidth()) {
2869 case 8:
2870 case 16:
2871 case 32:
2872 case 64:
2873 return true;
2874 default: break;
2875 }
2876 }
2877 return false;
2878}
2879
2882 return AT->getNumElements();
2883 return cast<FixedVectorType>(getType())->getNumElements();
2884}
2885
2889
2890/// Return the start of the specified element.
2891const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
2892 assert(Elt < getNumElements() && "Invalid Elt");
2893 return DataElements + Elt * getElementByteSize();
2894}
2895
2896/// Return true if the array is empty or all zeros.
2897static bool isAllZeros(StringRef Arr) {
2898 for (char I : Arr)
2899 if (I != 0)
2900 return false;
2901 return true;
2902}
2903
2904/// This is the underlying implementation of all of the
2905/// ConstantDataSequential::get methods. They all thunk down to here, providing
2906/// the correct element type. We take the bytes in as a StringRef because
2907/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2909#ifndef NDEBUG
2910 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2911 assert(isElementTypeCompatible(ATy->getElementType()));
2912 else
2914#endif
2915 // If the elements are all zero or there are no elements, return a CAZ, which
2916 // is more dense and canonical.
2917 if (isAllZeros(Elements))
2918 return ConstantAggregateZero::get(Ty);
2919
2920 // Do a lookup to see if we have already formed one of these.
2921 auto &Slot =
2922 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
2923
2924 // The bucket can point to a linked list of different CDS's that have the same
2925 // body but different types. For example, 0,0,0,1 could be a 4 element array
2926 // of i8, or a 1-element array of i32. They'll both end up in the same
2927 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2928 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2929 for (; *Entry; Entry = &(*Entry)->Next)
2930 if ((*Entry)->getType() == Ty)
2931 return Entry->get();
2932
2933 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2934 // and return it.
2935 if (isa<ArrayType>(Ty)) {
2936 // Use reset because std::make_unique can't access the constructor.
2937 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2938 return Entry->get();
2939 }
2940
2942 // Use reset because std::make_unique can't access the constructor.
2943 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2944 return Entry->get();
2945}
2946
2947void ConstantDataSequential::destroyConstantImpl() {
2948 // Remove the constant from the StringMap.
2951
2952 auto Slot = CDSConstants.find(getRawDataValues());
2953
2954 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2955
2956 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2957
2958 // Remove the entry from the hash table.
2959 if (!(*Entry)->Next) {
2960 // If there is only one value in the bucket (common case) it must be this
2961 // entry, and removing the entry should remove the bucket completely.
2962 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2963 getContext().pImpl->CDSConstants.erase(Slot);
2964 return;
2965 }
2966
2967 // Otherwise, there are multiple entries linked off the bucket, unlink the
2968 // node we care about but keep the bucket around.
2969 while (true) {
2970 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2971 assert(Node && "Didn't find entry in its uniquing hash table!");
2972 // If we found our entry, unlink it from the list and we're done.
2973 if (Node.get() == this) {
2974 Node = std::move(Node->Next);
2975 return;
2976 }
2977
2978 Entry = &Node->Next;
2979 }
2980}
2981
2982/// getFP() constructors - Return a constant of array type with a float
2983/// element type taken from argument `ElementType', and count taken from
2984/// argument `Elts'. The amount of bits of the contained type must match the
2985/// number of bits of the type contained in the passed in ArrayRef.
2986/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2987/// that this can return a ConstantAggregateZero object.
2989 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2990 "Element type is not a 16-bit float type");
2991 Type *Ty = ArrayType::get(ElementType, Elts.size());
2992 const char *Data = reinterpret_cast<const char *>(Elts.data());
2993 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2994}
2996 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2997 Type *Ty = ArrayType::get(ElementType, Elts.size());
2998 const char *Data = reinterpret_cast<const char *>(Elts.data());
2999 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3000}
3002 assert(ElementType->isDoubleTy() &&
3003 "Element type is not a 64-bit float type");
3004 Type *Ty = ArrayType::get(ElementType, Elts.size());
3005 const char *Data = reinterpret_cast<const char *>(Elts.data());
3006 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3007}
3008
3010 StringRef Str, bool AddNull) {
3011 if (!AddNull) {
3012 const uint8_t *Data = Str.bytes_begin();
3013 return get(Context, ArrayRef(Data, Str.size()));
3014 }
3015
3016 SmallVector<uint8_t, 64> ElementVals;
3017 ElementVals.append(Str.begin(), Str.end());
3018 ElementVals.push_back(0);
3019 return get(Context, ElementVals);
3020}
3021
3022/// get() constructors - Return a constant with vector type with an element
3023/// count and element type matching the ArrayRef passed in. Note that this
3024/// can return a ConstantAggregateZero object.
3026 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3027 const char *Data = reinterpret_cast<const char *>(Elts.data());
3028 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3029}
3031 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3032 const char *Data = reinterpret_cast<const char *>(Elts.data());
3033 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3034}
3036 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3037 const char *Data = reinterpret_cast<const char *>(Elts.data());
3038 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3039}
3041 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3042 const char *Data = reinterpret_cast<const char *>(Elts.data());
3043 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3044}
3046 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3047 const char *Data = reinterpret_cast<const char *>(Elts.data());
3048 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3049}
3051 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3052 const char *Data = reinterpret_cast<const char *>(Elts.data());
3053 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3054}
3055
3056/// getFP() constructors - Return a constant of vector type with a float
3057/// element type taken from argument `ElementType', and count taken from
3058/// argument `Elts'. The amount of bits of the contained type must match the
3059/// number of bits of the type contained in the passed in ArrayRef.
3060/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3061/// that this can return a ConstantAggregateZero object.
3063 ArrayRef<uint16_t> Elts) {
3064 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3065 "Element type is not a 16-bit float type");
3066 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3067 const char *Data = reinterpret_cast<const char *>(Elts.data());
3068 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3069}
3071 ArrayRef<uint32_t> Elts) {
3072 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3073 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3074 const char *Data = reinterpret_cast<const char *>(Elts.data());
3075 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3076}
3078 ArrayRef<uint64_t> Elts) {
3079 assert(ElementType->isDoubleTy() &&
3080 "Element type is not a 64-bit float type");
3081 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3082 const char *Data = reinterpret_cast<const char *>(Elts.data());
3083 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3084}
3085
3087 assert(isElementTypeCompatible(V->getType()) &&
3088 "Element type not compatible with ConstantData");
3089 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3090 if (CI->getType()->isIntegerTy(8)) {
3091 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3092 return get(V->getContext(), Elts);
3093 }
3094 if (CI->getType()->isIntegerTy(16)) {
3095 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3096 return get(V->getContext(), Elts);
3097 }
3098 if (CI->getType()->isIntegerTy(32)) {
3099 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3100 return get(V->getContext(), Elts);
3101 }
3102 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3103 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3104 return get(V->getContext(), Elts);
3105 }
3106
3107 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3108 if (CFP->getType()->isHalfTy()) {
3110 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3111 return getFP(V->getType(), Elts);
3112 }
3113 if (CFP->getType()->isBFloatTy()) {
3115 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3116 return getFP(V->getType(), Elts);
3117 }
3118 if (CFP->getType()->isFloatTy()) {
3120 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3121 return getFP(V->getType(), Elts);
3122 }
3123 if (CFP->getType()->isDoubleTy()) {
3125 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3126 return getFP(V->getType(), Elts);
3127 }
3128 }
3130}
3131
3134 "Accessor can only be used when element is an integer");
3135 const char *EltPtr = getElementPointer(Elt);
3136
3137 // The data is stored in host byte order, make sure to cast back to the right
3138 // type to load with the right endianness.
3139 switch (getElementType()->getIntegerBitWidth()) {
3140 default: llvm_unreachable("Invalid bitwidth for CDS");
3141 case 8:
3142 return *reinterpret_cast<const uint8_t *>(EltPtr);
3143 case 16:
3144 return *reinterpret_cast<const uint16_t *>(EltPtr);
3145 case 32:
3146 return *reinterpret_cast<const uint32_t *>(EltPtr);
3147 case 64:
3148 return *reinterpret_cast<const uint64_t *>(EltPtr);
3149 }
3150}
3151
3154 "Accessor can only be used when element is an integer");
3155 const char *EltPtr = getElementPointer(Elt);
3156
3157 // The data is stored in host byte order, make sure to cast back to the right
3158 // type to load with the right endianness.
3159 switch (getElementType()->getIntegerBitWidth()) {
3160 default: llvm_unreachable("Invalid bitwidth for CDS");
3161 case 8: {
3162 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3163 return APInt(8, EltVal);
3164 }
3165 case 16: {
3166 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3167 return APInt(16, EltVal);
3168 }
3169 case 32: {
3170 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3171 return APInt(32, EltVal);
3172 }
3173 case 64: {
3174 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3175 return APInt(64, EltVal);
3176 }
3177 }
3178}
3179
3181 const char *EltPtr = getElementPointer(Elt);
3182
3183 switch (getElementType()->getTypeID()) {
3184 default:
3185 llvm_unreachable("Accessor can only be used when element is float/double!");
3186 case Type::HalfTyID: {
3187 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3188 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3189 }
3190 case Type::BFloatTyID: {
3191 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3192 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3193 }
3194 case Type::FloatTyID: {
3195 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3196 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3197 }
3198 case Type::DoubleTyID: {
3199 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3200 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3201 }
3202 }
3203}
3204
3206 assert(getElementType()->isFloatTy() &&
3207 "Accessor can only be used when element is a 'float'");
3208 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3209}
3210
3212 assert(getElementType()->isDoubleTy() &&
3213 "Accessor can only be used when element is a 'float'");
3214 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3215}
3216
3218 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3219 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3220 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3221
3222 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3223}
3224
3225bool ConstantDataSequential::isString(unsigned CharSize) const {
3226 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3227}
3228
3230 if (!isString())
3231 return false;
3232
3233 StringRef Str = getAsString();
3234
3235 // The last value must be nul.
3236 if (Str.back() != 0) return false;
3237
3238 // Other elements must be non-nul.
3239 return !Str.drop_back().contains(0);
3240}
3241
3242bool ConstantDataVector::isSplatData() const {
3243 const char *Base = getRawDataValues().data();
3244
3245 // Compare elements 1+ to the 0'th element.
3246 unsigned EltSize = getElementByteSize();
3247 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3248 if (memcmp(Base, Base+i*EltSize, EltSize))
3249 return false;
3250
3251 return true;
3252}
3253
3255 if (!IsSplatSet) {
3256 IsSplatSet = true;
3257 IsSplat = isSplatData();
3258 }
3259 return IsSplat;
3260}
3261
3263 // If they're all the same, return the 0th one as a representative.
3264 return isSplat() ? getElementAsConstant(0) : nullptr;
3265}
3266
3267//===----------------------------------------------------------------------===//
3268// handleOperandChange implementations
3269
3270/// Update this constant array to change uses of
3271/// 'From' to be uses of 'To'. This must update the uniquing data structures
3272/// etc.
3273///
3274/// Note that we intentionally replace all uses of From with To here. Consider
3275/// a large array that uses 'From' 1000 times. By handling this case all here,
3276/// ConstantArray::handleOperandChange is only invoked once, and that
3277/// single invocation handles all 1000 uses. Handling them one at a time would
3278/// work, but would be really slow because it would have to unique each updated
3279/// array instance.
3280///
3282 Value *Replacement = nullptr;
3283 switch (getValueID()) {
3284 default:
3285 llvm_unreachable("Not a constant!");
3286#define HANDLE_CONSTANT(Name) \
3287 case Value::Name##Val: \
3288 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3289 break;
3290#include "llvm/IR/Value.def"
3291 }
3292
3293 // If handleOperandChangeImpl returned nullptr, then it handled
3294 // replacing itself and we don't want to delete or replace anything else here.
3295 if (!Replacement)
3296 return;
3297
3298 // I do need to replace this with an existing value.
3299 assert(Replacement != this && "I didn't contain From!");
3300
3301 // Everyone using this now uses the replacement.
3302 replaceAllUsesWith(Replacement);
3303
3304 // Delete the old constant!
3306}
3307
3308Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3309 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3310 Constant *ToC = cast<Constant>(To);
3311
3313 Values.reserve(getNumOperands()); // Build replacement array.
3314
3315 // Fill values with the modified operands of the constant array. Also,
3316 // compute whether this turns into an all-zeros array.
3317 unsigned NumUpdated = 0;
3318
3319 // Keep track of whether all the values in the array are "ToC".
3320 bool AllSame = true;
3321 Use *OperandList = getOperandList();
3322 unsigned OperandNo = 0;
3323 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3324 Constant *Val = cast<Constant>(O->get());
3325 if (Val == From) {
3326 OperandNo = (O - OperandList);
3327 Val = ToC;
3328 ++NumUpdated;
3329 }
3330 Values.push_back(Val);
3331 AllSame &= Val == ToC;
3332 }
3333
3334 if (AllSame && ToC->isNullValue())
3336
3337 if (AllSame && isa<UndefValue>(ToC))
3338 return UndefValue::get(getType());
3339
3340 // Check for any other type of constant-folding.
3341 if (Constant *C = getImpl(getType(), Values))
3342 return C;
3343
3344 // Update to the new value.
3346 Values, this, From, ToC, NumUpdated, OperandNo);
3347}
3348
3349Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3350 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3351 Constant *ToC = cast<Constant>(To);
3352
3353 Use *OperandList = getOperandList();
3354
3356 Values.reserve(getNumOperands()); // Build replacement struct.
3357
3358 // Fill values with the modified operands of the constant struct. Also,
3359 // compute whether this turns into an all-zeros struct.
3360 unsigned NumUpdated = 0;
3361 bool AllSame = true;
3362 unsigned OperandNo = 0;
3363 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3364 Constant *Val = cast<Constant>(O->get());
3365 if (Val == From) {
3366 OperandNo = (O - OperandList);
3367 Val = ToC;
3368 ++NumUpdated;
3369 }
3370 Values.push_back(Val);
3371 AllSame &= Val == ToC;
3372 }
3373
3374 if (AllSame && ToC->isNullValue())
3376
3377 if (AllSame && isa<UndefValue>(ToC))
3378 return UndefValue::get(getType());
3379
3380 // Update to the new value.
3382 Values, this, From, ToC, NumUpdated, OperandNo);
3383}
3384
3385Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3386 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3387 Constant *ToC = cast<Constant>(To);
3388
3390 Values.reserve(getNumOperands()); // Build replacement array...
3391 unsigned NumUpdated = 0;
3392 unsigned OperandNo = 0;
3393 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3394 Constant *Val = getOperand(i);
3395 if (Val == From) {
3396 OperandNo = i;
3397 ++NumUpdated;
3398 Val = ToC;
3399 }
3400 Values.push_back(Val);
3401 }
3402
3403 if (Constant *C = getImpl(Values))
3404 return C;
3405
3406 // Update to the new value.
3408 Values, this, From, ToC, NumUpdated, OperandNo);
3409}
3410
3411Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3412 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3413 Constant *To = cast<Constant>(ToV);
3414
3416 unsigned NumUpdated = 0;
3417 unsigned OperandNo = 0;
3418 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3419 Constant *Op = getOperand(i);
3420 if (Op == From) {
3421 OperandNo = i;
3422 ++NumUpdated;
3423 Op = To;
3424 }
3425 NewOps.push_back(Op);
3426 }
3427 assert(NumUpdated && "I didn't contain From!");
3428
3429 if (Constant *C = getWithOperands(NewOps, getType(), true))
3430 return C;
3431
3432 // Update to the new value.
3433 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3434 NewOps, this, From, To, NumUpdated, OperandNo);
3435}
3436
3438 SmallVector<Value *, 4> ValueOperands(operands());
3439 ArrayRef<Value*> Ops(ValueOperands);
3440
3441 switch (getOpcode()) {
3442 case Instruction::Trunc:
3443 case Instruction::PtrToAddr:
3444 case Instruction::PtrToInt:
3445 case Instruction::IntToPtr:
3446 case Instruction::BitCast:
3447 case Instruction::AddrSpaceCast:
3449 getType(), "");
3450 case Instruction::InsertElement:
3451 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3452 case Instruction::ExtractElement:
3453 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3454 case Instruction::ShuffleVector:
3455 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3456
3457 case Instruction::GetElementPtr: {
3458 const auto *GO = cast<GEPOperator>(this);
3459 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3460 Ops.slice(1), GO->getNoWrapFlags(), "");
3461 }
3462 default:
3463 assert(getNumOperands() == 2 && "Must be binary operator?");
3465 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3471 }
3474 return BO;
3475 }
3476}
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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 const fltSemantics & IEEEquad()
Definition APFloat.h:298
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:317
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
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:6053
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6079
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:235
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
unsigned logBase2() const
Definition APInt.h:1762
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
const T * data() const
Definition ArrayRef.h:139
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 isMaxSignedValue() const
Return true if the value is the largest signed value.
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:309
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:802
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:318
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:413
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:297
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:296
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:125
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
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:197
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:295
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:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
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:285
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:284
'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:200
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