LLVM 24.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-int-for-scalable-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantInt's native scalable vector splat support."));
45
46//===----------------------------------------------------------------------===//
47// Constant Class
48//===----------------------------------------------------------------------===//
49
51 // Floating point values have an explicit -0.0 value.
52 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
53 return CFP->isZero() && CFP->isNegative();
54
55 // Equivalent for a vector of -0.0's.
56 if (getType()->isVectorTy())
57 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
58 return SplatCFP->isNegativeZeroValue();
59
60 // We've already handled true FP case; any other FP vectors can't represent -0.0.
61 if (getType()->isFPOrFPVectorTy())
62 return false;
63
64 // Otherwise, just use +0.0.
65 return isNullValue();
66}
67
69 // Check for -1 integers
70 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
71 return CI->isMinusOne();
72
73 // Check for MaxValue bytes
74 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
75 return CB->isMinusOne();
76
77 // Check for FP which are bitcasted from -1 integers
78 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
79 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
80
81 // Check for constant splat vectors of 1 values.
82 if (getType()->isVectorTy())
83 if (const auto *SplatVal = getSplatValue())
84 return SplatVal->isAllOnesValue();
85
86 return false;
87}
88
90 // Check for 1 integers
91 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
92 return CI->isOne();
93
94 // Check for 1 bytes
95 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
96 return CB->isOne();
97
98 // Check for FP which are bitcasted from 1 integers
99 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
100 return CFP->getValueAPF().bitcastToAPInt().isOne();
101
102 // Check for constant splat vectors of 1 values.
103 if (getType()->isVectorTy())
104 if (const auto *SplatVal = getSplatValue())
105 return SplatVal->isOneValue();
106
107 return false;
108}
109
111 // Check for 1 integers
112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
113 return !CI->isOneValue();
114
115 // Check for 1 bytes
116 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
117 return !CB->isOneValue();
118
119 // Check for FP which are bitcasted from 1 integers
120 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
121 return !CFP->getValueAPF().bitcastToAPInt().isOne();
122
123 // Check that vectors don't contain 1
124 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
125 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
127 if (!Elt || !Elt->isNotOneValue())
128 return false;
129 }
130 return true;
131 }
132
133 // Check for splats that don't contain 1
134 if (getType()->isVectorTy())
135 if (const auto *SplatVal = getSplatValue())
136 return SplatVal->isNotOneValue();
137
138 // It *may* contain 1, we can't tell.
139 return false;
140}
141
143 // Check for INT_MIN integers
144 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
145 return CI->isMinValue(/*isSigned=*/true);
146
147 // Check for FP which are bitcasted from INT_MIN integers
148 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
149 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
150
151 // Check for splats of INT_MIN values.
152 if (getType()->isVectorTy())
153 if (const auto *SplatVal = getSplatValue())
154 return SplatVal->isMinSignedValue();
155
156 return false;
157}
158
160 // Check for INT_MAX integers
161 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
162 return CI->isMaxValue(/*isSigned=*/true);
163
164 // Check for FP which are bitcasted from INT_MAX integers
165 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
166 return CFP->getValueAPF().bitcastToAPInt().isMaxSignedValue();
167
168 // Check for splats of INT_MAX values.
169 if (getType()->isVectorTy())
170 if (const auto *SplatVal = getSplatValue())
171 return SplatVal->isMaxSignedValue();
172
173 return false;
174}
175
177 // Check for INT_MIN integers
178 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
179 return !CI->isMinValue(/*isSigned=*/true);
180
181 // Check for FP which are bitcasted from INT_MIN integers
182 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
183 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
184
185 // Check that vectors don't contain INT_MIN
186 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
187 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
189 if (!Elt || !Elt->isNotMinSignedValue())
190 return false;
191 }
192 return true;
193 }
194
195 // Check for splats that aren't INT_MIN
196 if (getType()->isVectorTy())
197 if (const auto *SplatVal = getSplatValue())
198 return SplatVal->isNotMinSignedValue();
199
200 // It *may* contain INT_MIN, we can't tell.
201 return false;
202}
203
205 if (auto *CFP = dyn_cast<ConstantFP>(this))
206 return CFP->getValueAPF().isFiniteNonZero();
207
208 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
209 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
211 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
212 return false;
213 }
214 return true;
215 }
216
217 if (getType()->isVectorTy())
218 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
219 return SplatCFP->isFiniteNonZeroFP();
220
221 // It *may* contain finite non-zero, we can't tell.
222 return false;
223}
224
226 if (auto *CFP = dyn_cast<ConstantFP>(this))
227 return CFP->getValueAPF().isNormal();
228
229 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
230 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
232 if (!CFP || !CFP->getValueAPF().isNormal())
233 return false;
234 }
235 return true;
236 }
237
238 if (getType()->isVectorTy())
239 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
240 return SplatCFP->isNormalFP();
241
242 // It *may* contain a normal fp value, we can't tell.
243 return false;
244}
245
247 if (auto *CFP = dyn_cast<ConstantFP>(this))
248 return CFP->getValueAPF().getExactInverse(nullptr);
249
250 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
251 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
253 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
254 return false;
255 }
256 return true;
257 }
258
259 if (getType()->isVectorTy())
260 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
261 return SplatCFP->hasExactInverseFP();
262
263 // It *may* have an exact inverse fp value, we can't tell.
264 return false;
265}
266
267bool Constant::isNaN() const {
268 if (auto *CFP = dyn_cast<ConstantFP>(this))
269 return CFP->isNaN();
270
271 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
272 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
274 if (!CFP || !CFP->isNaN())
275 return false;
276 }
277 return true;
278 }
279
280 if (getType()->isVectorTy())
281 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
282 return SplatCFP->isNaN();
283
284 // It *may* be NaN, we can't tell.
285 return false;
286}
287
289 // Are they fully identical?
290 if (this == Y)
291 return true;
292
293 // The input value must be a vector constant with the same type.
294 auto *VTy = dyn_cast<VectorType>(getType());
295 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
296 return false;
297
298 // TODO: Compare pointer constants?
299 if (!(VTy->getElementType()->isIntegerTy() ||
300 VTy->getElementType()->isFloatingPointTy()))
301 return false;
302
303 // They may still be identical element-wise (if they have `undef`s).
304 // Bitcast to integer to allow exact bitwise comparison for all types.
305 Type *IntTy = VectorType::getInteger(VTy);
306 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
309 return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));
310}
311
312static bool
314 function_ref<bool(const Constant *)> HasFn) {
315 if (C->getType()->isVectorTy()) {
316 if (HasFn(C))
317 return true;
319 return false;
320
321 return C->containsMatchingVectorElement(HasFn);
322 }
323
324 return false;
325}
326
329 this, [&](const auto *C) { return isa<UndefValue>(C); });
330}
331
334 this, [&](const auto *C) { return isa<PoisonValue>(C); });
335}
336
338 return containsUndefinedElement(this, [&](const auto *C) {
339 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
340 });
341}
342
344 if (isa<ConstantInt>(this) || isa<ConstantFP>(this))
345 return false;
346
348}
349
351 function_ref<bool(Constant *)> PredFn) const {
352 auto *FVTy = dyn_cast<FixedVectorType>(getType());
353 if (!FVTy)
354 return false;
355
356 unsigned NumElts = FVTy->getNumElements();
357 for (unsigned I = 0; I != NumElts; ++I) {
359 if (Elem && PredFn(Elem))
360 return true;
361 }
362
363 return false;
364}
365
366/// Constructor to create a '0' constant of arbitrary type.
368 switch (Ty->getTypeID()) {
369 case Type::ByteTyID:
370 return ConstantByte::get(Ty, 0);
372 return ConstantInt::get(Ty, 0);
373 case Type::HalfTyID:
374 case Type::BFloatTyID:
375 case Type::FloatTyID:
376 case Type::DoubleTyID:
378 case Type::FP128TyID:
380 return ConstantFP::get(Ty->getContext(),
381 APFloat::getZero(Ty->getFltSemantics()));
386 Type *EltTy = cast<VectorType>(Ty)->getElementType();
387 if (EltTy->isFloatingPointTy())
388 return ConstantFP::get(Ty, APFloat::getZero(EltTy->getFltSemantics()));
389 if (EltTy->isPointerTy())
390 return ConstantPointerNull::get(Ty);
392 }
393 case Type::StructTyID:
394 case Type::ArrayTyID:
396 case Type::TokenTyID:
397 return ConstantTokenNone::get(Ty->getContext());
400 default:
401 // Function, Label, or Opaque type?
402 llvm_unreachable("Cannot create a null constant of that type!");
403 }
404}
405
407 Type *ScalarTy = Ty->getScalarType();
408
409 // Create the base integer constant.
410 Constant *C = ConstantInt::get(Ty->getContext(), V);
411
412 // Convert an integer to a pointer, if necessary.
413 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
415
416 // Convert an integer to a byte, if necessary.
417 if (ByteType *BTy = dyn_cast<ByteType>(ScalarTy))
419
420 // Broadcast a scalar to a vector, if necessary.
421 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
422 C = ConstantVector::getSplat(VTy->getElementCount(), C);
423
424 return C;
425}
426
428 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
429 return ConstantInt::get(Ty->getContext(),
430 APInt::getAllOnes(ITy->getBitWidth()));
431
432 if (Ty->isFloatingPointTy()) {
433 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
434 return ConstantFP::get(Ty->getContext(), FL);
435 }
436
437 if (ByteType *BTy = dyn_cast<ByteType>(Ty))
438 return ConstantByte::get(Ty->getContext(),
439 APInt::getAllOnes(BTy->getBitWidth()));
440
441 VectorType *VTy = cast<VectorType>(Ty);
442 return ConstantVector::getSplat(VTy->getElementCount(),
443 getAllOnesValue(VTy->getElementType()));
444}
445
447 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
448 "Must be an aggregate/vector constant");
449
450 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
451 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
452
453 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
454 return Elt < CAZ->getElementCount().getKnownMinValue()
455 ? CAZ->getElementValue(Elt)
456 : nullptr;
457
458 if (const auto *CI = dyn_cast<ConstantInt>(this))
459 return Elt < cast<VectorType>(getType())
460 ->getElementCount()
461 .getKnownMinValue()
462 ? ConstantInt::get(getContext(), CI->getValue())
463 : nullptr;
464
465 if (const auto *CB = dyn_cast<ConstantByte>(this))
466 return Elt < cast<VectorType>(getType())
467 ->getElementCount()
468 .getKnownMinValue()
469 ? ConstantByte::get(getContext(), CB->getValue())
470 : nullptr;
471
472 if (const auto *CFP = dyn_cast<ConstantFP>(this))
473 return Elt < cast<VectorType>(getType())
474 ->getElementCount()
475 .getKnownMinValue()
476 ? ConstantFP::get(getContext(), CFP->getValue())
477 : nullptr;
478
479 if (isa<ConstantPointerNull>(this)) {
480 auto *VT = cast<VectorType>(getType());
481 return Elt < VT->getElementCount().getKnownMinValue()
482 ? ConstantPointerNull::get(VT->getElementType())
483 : nullptr;
484 }
485
486 // FIXME: getNumElements() will fail for non-fixed vector types.
488 return nullptr;
489
490 if (const auto *PV = dyn_cast<PoisonValue>(this))
491 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
492
493 if (const auto *UV = dyn_cast<UndefValue>(this))
494 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
495
496 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
497 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
498 : nullptr;
499
500 return nullptr;
501}
502
504 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
505 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
506 // Check if the constant fits into an uint64_t.
507 if (CI->getValue().getActiveBits() > 64)
508 return nullptr;
509 return getAggregateElement(CI->getZExtValue());
510 }
511 return nullptr;
512}
513
515 /// First call destroyConstantImpl on the subclass. This gives the subclass
516 /// a chance to remove the constant from any maps/pools it's contained in.
517 switch (getValueID()) {
518 default:
519 llvm_unreachable("Not a constant!");
520#define HANDLE_CONSTANT(Name) \
521 case Value::Name##Val: \
522 cast<Name>(this)->destroyConstantImpl(); \
523 break;
524#include "llvm/IR/Value.def"
525 }
526
527 // When a Constant is destroyed, there may be lingering
528 // references to the constant by other constants in the constant pool. These
529 // constants are implicitly dependent on the module that is being deleted,
530 // but they don't know that. Because we only find out when the CPV is
531 // deleted, we must now notify all of our users (that should only be
532 // Constants) that they are, in fact, invalid now and should be deleted.
533 //
534 while (!use_empty()) {
535 Value *V = user_back();
536#ifndef NDEBUG // Only in -g mode...
537 if (!isa<Constant>(V)) {
538 dbgs() << "While deleting: " << *this
539 << "\n\nUse still stuck around after Def is destroyed: " << *V
540 << "\n\n";
541 }
542#endif
543 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
544 cast<Constant>(V)->destroyConstant();
545
546 // The constant should remove itself from our use list...
547 assert((use_empty() || user_back() != V) && "Constant not removed!");
548 }
549
550 // Value has no outstanding references it is safe to delete it now...
551 deleteConstant(this);
552}
553
555 switch (C->getValueID()) {
556 case Constant::ConstantIntVal:
557 delete static_cast<ConstantInt *>(C);
558 break;
559 case Constant::ConstantByteVal:
560 delete static_cast<ConstantByte *>(C);
561 break;
562 case Constant::ConstantFPVal:
563 delete static_cast<ConstantFP *>(C);
564 break;
565 case Constant::ConstantAggregateZeroVal:
566 delete static_cast<ConstantAggregateZero *>(C);
567 break;
568 case Constant::ConstantArrayVal:
569 delete static_cast<ConstantArray *>(C);
570 break;
571 case Constant::ConstantStructVal:
572 delete static_cast<ConstantStruct *>(C);
573 break;
574 case Constant::ConstantVectorVal:
575 delete static_cast<ConstantVector *>(C);
576 break;
577 case Constant::ConstantPointerNullVal:
578 delete static_cast<ConstantPointerNull *>(C);
579 break;
580 case Constant::ConstantDataArrayVal:
581 delete static_cast<ConstantDataArray *>(C);
582 break;
583 case Constant::ConstantDataVectorVal:
584 delete static_cast<ConstantDataVector *>(C);
585 break;
586 case Constant::ConstantTokenNoneVal:
587 delete static_cast<ConstantTokenNone *>(C);
588 break;
589 case Constant::BlockAddressVal:
590 delete static_cast<BlockAddress *>(C);
591 break;
592 case Constant::DSOLocalEquivalentVal:
593 delete static_cast<DSOLocalEquivalent *>(C);
594 break;
595 case Constant::NoCFIValueVal:
596 delete static_cast<NoCFIValue *>(C);
597 break;
598 case Constant::ConstantPtrAuthVal:
599 delete static_cast<ConstantPtrAuth *>(C);
600 break;
601 case Constant::UndefValueVal:
602 delete static_cast<UndefValue *>(C);
603 break;
604 case Constant::PoisonValueVal:
605 delete static_cast<PoisonValue *>(C);
606 break;
607 case Constant::ConstantExprVal:
609 delete static_cast<CastConstantExpr *>(C);
610 else if (isa<BinaryConstantExpr>(C))
611 delete static_cast<BinaryConstantExpr *>(C);
613 delete static_cast<ExtractElementConstantExpr *>(C);
615 delete static_cast<InsertElementConstantExpr *>(C);
617 delete static_cast<ShuffleVectorConstantExpr *>(C);
619 delete static_cast<GetElementPtrConstantExpr *>(C);
620 else
621 llvm_unreachable("Unexpected constant expr");
622 break;
623 default:
624 llvm_unreachable("Unexpected constant");
625 }
626}
627
628/// Check if C contains a GlobalValue for which Predicate is true.
629static bool
631 bool (*Predicate)(const GlobalValue *)) {
634 WorkList.push_back(C);
635 Visited.insert(C);
636
637 while (!WorkList.empty()) {
638 const Constant *WorkItem = WorkList.pop_back_val();
639 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
640 if (Predicate(GV))
641 return true;
642 for (const Value *Op : WorkItem->operands()) {
643 const Constant *ConstOp = dyn_cast<Constant>(Op);
644 if (!ConstOp)
645 continue;
646 if (Visited.insert(ConstOp).second)
647 WorkList.push_back(ConstOp);
648 }
649 }
650 return false;
651}
652
654 auto DLLImportPredicate = [](const GlobalValue *GV) {
655 return GV->isThreadLocal();
656 };
657 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
658}
659
661 auto DLLImportPredicate = [](const GlobalValue *GV) {
662 return GV->hasDLLImportStorageClass();
663 };
664 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
665}
666
668 for (const User *U : users()) {
669 const Constant *UC = dyn_cast<Constant>(U);
670 if (!UC || isa<GlobalValue>(UC))
671 return true;
672
673 if (UC->isConstantUsed())
674 return true;
675 }
676 return false;
677}
678
680 return getRelocationInfo() == GlobalRelocation;
681}
682
684 return getRelocationInfo() != NoRelocation;
685}
686
687Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
688 if (isa<GlobalValue>(this))
689 return GlobalRelocation; // Global reference.
690
691 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
692 return BA->getFunction()->getRelocationInfo();
693
694 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
695 if (CE->getOpcode() == Instruction::Sub) {
696 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
697 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
698 if (LHS && RHS &&
699 (LHS->getOpcode() == Instruction::PtrToInt ||
700 LHS->getOpcode() == Instruction::PtrToAddr) &&
701 (RHS->getOpcode() == Instruction::PtrToInt ||
702 RHS->getOpcode() == Instruction::PtrToAddr)) {
703 Constant *LHSOp0 = LHS->getOperand(0);
704 Constant *RHSOp0 = RHS->getOperand(0);
705
706 // While raw uses of blockaddress need to be relocated, differences
707 // between two of them don't when they are for labels in the same
708 // function. This is a common idiom when creating a table for the
709 // indirect goto extension, so we handle it efficiently here.
710 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
711 cast<BlockAddress>(LHSOp0)->getFunction() ==
713 return NoRelocation;
714
715 // Relative pointers do not need to be dynamically relocated.
716 if (auto *RHSGV =
718 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
719 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
720 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
721 return LocalRelocation;
722 } else if (isa<DSOLocalEquivalent>(LHS)) {
723 if (RHSGV->isDSOLocal())
724 return LocalRelocation;
725 }
726 }
727 }
728 }
729 }
730
731 PossibleRelocationsTy Result = NoRelocation;
732 for (const Value *Op : operands())
733 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
734
735 return Result;
736}
737
738/// Return true if the specified constantexpr is dead. This involves
739/// recursively traversing users of the constantexpr.
740/// If RemoveDeadUsers is true, also remove dead users at the same time.
741static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
742 if (isa<GlobalValue>(C)) return false; // Cannot remove this
743
744 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
745 while (I != E) {
747 if (!User) return false; // Non-constant usage;
748 if (!constantIsDead(User, RemoveDeadUsers))
749 return false; // Constant wasn't dead
750
751 // Just removed User, so the iterator was invalidated.
752 // Since we return immediately upon finding a live user, we can always
753 // restart from user_begin().
754 if (RemoveDeadUsers)
755 I = C->user_begin();
756 else
757 ++I;
758 }
759
760 if (RemoveDeadUsers) {
761 // If C is only used by metadata, it should not be preserved but should
762 // have its uses replaced.
764 const_cast<Constant *>(C)->destroyConstant();
765 }
766
767 return true;
768}
769
772 Value::const_user_iterator LastNonDeadUser = E;
773 while (I != E) {
775 if (!User) {
776 LastNonDeadUser = I;
777 ++I;
778 continue;
779 }
780
781 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
782 // If the constant wasn't dead, remember that this was the last live use
783 // and move on to the next constant.
784 LastNonDeadUser = I;
785 ++I;
786 continue;
787 }
788
789 // If the constant was dead, then the iterator is invalidated.
790 if (LastNonDeadUser == E)
791 I = user_begin();
792 else
793 I = std::next(LastNonDeadUser);
794 }
795}
796
797bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
798
799bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
800
801bool Constant::hasNLiveUses(unsigned N) const {
802 unsigned NumUses = 0;
803 for (const Use &U : uses()) {
804 const Constant *User = dyn_cast<Constant>(U.getUser());
805 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
806 ++NumUses;
807
808 if (NumUses > N)
809 return false;
810 }
811 }
812 return NumUses == N;
813}
814
816 assert(C && Replacement && "Expected non-nullptr constant arguments");
817 Type *Ty = C->getType();
818 if (match(C, m_Undef())) {
819 assert(Ty == Replacement->getType() && "Expected matching types");
820 return Replacement;
821 }
822
823 // Don't know how to deal with this constant.
824 auto *VTy = dyn_cast<FixedVectorType>(Ty);
825 if (!VTy)
826 return C;
827
828 unsigned NumElts = VTy->getNumElements();
829 SmallVector<Constant *, 32> NewC(NumElts);
830 for (unsigned i = 0; i != NumElts; ++i) {
831 Constant *EltC = C->getAggregateElement(i);
832 assert((!EltC || EltC->getType() == Replacement->getType()) &&
833 "Expected matching types");
834 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
835 }
836 return ConstantVector::get(NewC);
837}
838
840 assert(C && Other && "Expected non-nullptr constant arguments");
841 if (match(C, m_Undef()))
842 return C;
843
844 Type *Ty = C->getType();
845 if (match(Other, m_Undef()))
846 return UndefValue::get(Ty);
847
848 auto *VTy = dyn_cast<FixedVectorType>(Ty);
849 if (!VTy)
850 return C;
851
852 Type *EltTy = VTy->getElementType();
853 unsigned NumElts = VTy->getNumElements();
854 assert(isa<FixedVectorType>(Other->getType()) &&
855 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
856 "Type mismatch");
857
858 bool FoundExtraUndef = false;
859 SmallVector<Constant *, 32> NewC(NumElts);
860 for (unsigned I = 0; I != NumElts; ++I) {
861 NewC[I] = C->getAggregateElement(I);
862 Constant *OtherEltC = Other->getAggregateElement(I);
863 assert(NewC[I] && OtherEltC && "Unknown vector element");
864 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
865 NewC[I] = UndefValue::get(EltTy);
866 FoundExtraUndef = true;
867 }
868 }
869 if (FoundExtraUndef)
870 return ConstantVector::get(NewC);
871 return C;
872}
873
875 if (isa<UndefValue>(this))
876 return false;
877 if (isa<ConstantData>(this))
878 return true;
879 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
880 for (const Value *Op : operand_values())
882 return false;
883 return true;
884 }
885 return false;
886}
887
888//===----------------------------------------------------------------------===//
889// ConstantInt
890//===----------------------------------------------------------------------===//
891
892ConstantInt::ConstantInt(Type *Ty, const APInt &V)
893 : ConstantData(Ty, ConstantIntVal), Val(V) {
894 assert(V.getBitWidth() ==
895 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
896 "Invalid constant for type");
897 if (V.isZero())
899}
900
901ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
902 LLVMContextImpl *pImpl = Context.pImpl;
903 if (!pImpl->TheTrueVal)
904 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
905 return pImpl->TheTrueVal;
906}
907
908ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
909 LLVMContextImpl *pImpl = Context.pImpl;
910 if (!pImpl->TheFalseVal)
911 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
912 return pImpl->TheFalseVal;
913}
914
915ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
916 return V ? getTrue(Context) : getFalse(Context);
917}
918
920 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
921 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
922 if (auto *VTy = dyn_cast<VectorType>(Ty))
923 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
924 return TrueC;
925}
926
928 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
929 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
930 if (auto *VTy = dyn_cast<VectorType>(Ty))
931 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
932 return FalseC;
933}
934
936 return V ? getTrue(Ty) : getFalse(Ty);
937}
938
939// Get a ConstantInt from an APInt.
940ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
941 // get an existing value or the insertion position
942 LLVMContextImpl *pImpl = Context.pImpl;
943 std::unique_ptr<ConstantInt> &Slot =
944 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
945 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
946 : pImpl->IntConstants[V];
947 if (!Slot) {
948 // Get the corresponding integer type for the bit width of the value.
949 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
950 Slot.reset(new ConstantInt(ITy, V));
951 }
952 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
953 return Slot.get();
954}
955
956// Get a ConstantInt vector with each lane set to the same APInt.
957ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
958 const APInt &V) {
959 // Get an existing value or the insertion position.
960 std::unique_ptr<ConstantInt> &Slot =
961 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
962 if (!Slot) {
963 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
964 VectorType *VTy = VectorType::get(ITy, EC);
965 Slot.reset(new ConstantInt(VTy, V));
966 }
967
968#ifndef NDEBUG
969 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
970 VectorType *VTy = VectorType::get(ITy, EC);
971 assert(Slot->getType() == VTy);
972#endif
973 return Slot.get();
974}
975
976Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
977 bool ImplicitTrunc) {
978 Constant *C =
979 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
980
981 // For vectors, broadcast the value.
982 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
983 return ConstantVector::getSplat(VTy->getElementCount(), C);
984
985 return C;
986}
987
988ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
989 bool ImplicitTrunc) {
990 return get(Ty->getContext(),
991 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
992}
993
994Constant *ConstantInt::get(Type *Ty, const APInt& V) {
995 ConstantInt *C = get(Ty->getContext(), V);
996 assert(C->getType() == Ty->getScalarType() &&
997 "ConstantInt type doesn't match the type implied by its value!");
998
999 // For vectors, broadcast the value.
1000 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1001 return ConstantVector::getSplat(VTy->getElementCount(), C);
1002
1003 return C;
1004}
1005
1006ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
1007 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1008}
1009
1010/// Remove the constant from the constant table.
1011void ConstantInt::destroyConstantImpl() {
1012 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// ConstantByte
1017//===----------------------------------------------------------------------===//
1018
1019ConstantByte::ConstantByte(Type *Ty, const APInt &V)
1020 : ConstantData(Ty, ConstantByteVal), Val(V) {
1021 assert(V.getBitWidth() ==
1022 cast<ByteType>(Ty->getScalarType())->getBitWidth() &&
1023 "Invalid constant for type");
1024 if (V.isZero())
1026}
1027
1028// Get a ConstantByte from an APInt.
1029ConstantByte *ConstantByte::get(LLVMContext &Context, const APInt &V) {
1030 // get an existing value or the insertion position
1031 LLVMContextImpl *pImpl = Context.pImpl;
1032 std::unique_ptr<ConstantByte> &Slot =
1033 V.isZero() ? pImpl->ByteZeroConstants[V.getBitWidth()]
1034 : V.isOne() ? pImpl->ByteOneConstants[V.getBitWidth()]
1035 : pImpl->ByteConstants[V];
1036 if (!Slot) {
1037 // Get the corresponding byte type for the bit width of the value.
1038 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1039 Slot.reset(new ConstantByte(BTy, V));
1040 }
1041 assert(Slot->getType() == ByteType::get(Context, V.getBitWidth()));
1042 return Slot.get();
1043}
1044
1045// Get a ConstantByte vector with each lane set to the same APInt.
1046ConstantByte *ConstantByte::get(LLVMContext &Context, ElementCount EC,
1047 const APInt &V) {
1048 // Get an existing value or the insertion position.
1049 std::unique_ptr<ConstantByte> &Slot =
1050 Context.pImpl->ByteSplatConstants[std::make_pair(EC, V)];
1051 if (!Slot) {
1052 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1053 VectorType *VTy = VectorType::get(BTy, EC);
1054 Slot.reset(new ConstantByte(VTy, V));
1055 }
1056
1057#ifndef NDEBUG
1058 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1059 VectorType *VTy = VectorType::get(BTy, EC);
1060 assert(Slot->getType() == VTy);
1061#endif
1062 return Slot.get();
1063}
1064
1065Constant *ConstantByte::get(Type *Ty, uint64_t V, bool isSigned,
1066 bool ImplicitTrunc) {
1067 Constant *C =
1068 get(cast<ByteType>(Ty->getScalarType()), V, isSigned, ImplicitTrunc);
1069
1070 // For vectors, broadcast the value.
1071 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1072 return ConstantVector::getSplat(VTy->getElementCount(), C);
1073
1074 return C;
1075}
1076
1077ConstantByte *ConstantByte::get(ByteType *Ty, uint64_t V, bool isSigned,
1078 bool ImplicitTrunc) {
1079 return get(Ty->getContext(),
1080 APInt(Ty->getBitWidth(), V, isSigned, ImplicitTrunc));
1081}
1082
1083Constant *ConstantByte::get(Type *Ty, const APInt &V) {
1084 ConstantByte *C = get(Ty->getContext(), V);
1085 assert(C->getType() == Ty->getScalarType() &&
1086 "ConstantByte type doesn't match the type implied by its value!");
1087
1088 // For vectors, broadcast the value.
1089 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1090 return ConstantVector::getSplat(VTy->getElementCount(), C);
1091
1092 return C;
1093}
1094
1095ConstantByte *ConstantByte::get(ByteType *Ty, StringRef Str, uint8_t radix) {
1096 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1097}
1098
1099/// Remove the constant from the constant table.
1100void ConstantByte::destroyConstantImpl() {
1101 llvm_unreachable("You can't ConstantByte->destroyConstantImpl()!");
1102}
1103
1104//===----------------------------------------------------------------------===//
1105// ConstantFP
1106//===----------------------------------------------------------------------===//
1107
1108ConstantFP *ConstantFP::get(Type *Ty, double V) {
1109 LLVMContext &Context = Ty->getContext();
1110
1111 APFloat FV(V);
1112 bool ignored;
1113 FV.convert(Ty->getScalarType()->getFltSemantics(),
1115
1116 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1117 return get(Context, VTy->getElementCount(), FV);
1118
1119 return get(Context, FV);
1120}
1121
1122ConstantFP *ConstantFP::get(Type *Ty, const APFloat &V) {
1123 LLVMContext &Context = Ty->getContext();
1124 assert(Ty->getScalarType() ==
1125 Type::getFloatingPointTy(Context, V.getSemantics()) &&
1126 "ConstantFP type doesn't match the type implied by its value!");
1127
1128 if (auto *VTy = dyn_cast<VectorType>(Ty))
1129 return get(Context, VTy->getElementCount(), V);
1130
1131 return get(Ty->getContext(), V);
1132}
1133
1134ConstantFP *ConstantFP::get(Type *Ty, StringRef Str) {
1135 LLVMContext &Context = Ty->getContext();
1136 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1137
1138 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1139 return get(Context, VTy->getElementCount(), FV);
1140
1141 return get(Context, FV);
1142}
1143
1144ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1145 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1146 return get(Ty, APFloat::getInf(Semantics, Negative));
1147}
1148
1149ConstantFP *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1150 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1151 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1152 return get(Ty, NaN);
1153}
1154
1155ConstantFP *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1156 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1157 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1158 return get(Ty, NaN);
1159}
1160
1161ConstantFP *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1162 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1163 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1164 return get(Ty, NaN);
1165}
1166
1167ConstantFP *ConstantFP::getZero(Type *Ty, bool Negative) {
1168 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1169 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1170 return get(Ty, NegZero);
1171}
1172
1173// ConstantFP accessors.
1174ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1175 LLVMContextImpl* pImpl = Context.pImpl;
1176
1177 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1178
1179 if (!Slot) {
1180 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1181 Slot.reset(new ConstantFP(Ty, V));
1182 }
1183
1184 return Slot.get();
1185}
1186
1187// Get a ConstantFP vector with each lane set to the same APFloat.
1188ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1189 const APFloat &V) {
1190 // Get an existing value or the insertion position.
1191 std::unique_ptr<ConstantFP> &Slot =
1192 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1193 if (!Slot) {
1194 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1195 VectorType *VTy = VectorType::get(EltTy, EC);
1196 Slot.reset(new ConstantFP(VTy, V));
1197 }
1198
1199#ifndef NDEBUG
1200 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1201 VectorType *VTy = VectorType::get(EltTy, EC);
1202 assert(Slot->getType() == VTy);
1203#endif
1204 return Slot.get();
1205}
1206
1207ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1208 : ConstantData(Ty, ConstantFPVal), Val(V) {
1209 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1210 "FP type Mismatch");
1211 // ppc_fp128 determine isZero using high order double only
1212 // so check the bitwise value to make sure all bits are zero.
1213 if (V.bitcastToAPInt().isZero())
1215}
1216
1218 return Val.bitwiseIsEqual(V);
1219}
1220
1221/// Remove the constant from the constant table.
1222void ConstantFP::destroyConstantImpl() {
1223 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1224}
1225
1226//===----------------------------------------------------------------------===//
1227// ConstantAggregateZero Implementation
1228//===----------------------------------------------------------------------===//
1229
1231 if (auto *AT = dyn_cast<ArrayType>(getType()))
1232 return Constant::getNullValue(AT->getElementType());
1233 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1234}
1235
1237 return Constant::getNullValue(getType()->getStructElementType(Elt));
1238}
1239
1245
1248 return getSequentialElement();
1249 return getStructElement(Idx);
1250}
1251
1253 Type *Ty = getType();
1254 if (auto *AT = dyn_cast<ArrayType>(Ty))
1255 return ElementCount::getFixed(AT->getNumElements());
1256 if (auto *VT = dyn_cast<VectorType>(Ty))
1257 return VT->getElementCount();
1258 return ElementCount::getFixed(Ty->getStructNumElements());
1259}
1260
1261//===----------------------------------------------------------------------===//
1262// UndefValue Implementation
1263//===----------------------------------------------------------------------===//
1264
1267 return UndefValue::get(ATy->getElementType());
1268 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1269}
1270
1271UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1272 return UndefValue::get(getType()->getStructElementType(Elt));
1273}
1274
1277 return getSequentialElement();
1278 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1279}
1280
1281UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1283 return getSequentialElement();
1284 return getStructElement(Idx);
1285}
1286
1288 Type *Ty = getType();
1289 if (auto *AT = dyn_cast<ArrayType>(Ty))
1290 return AT->getNumElements();
1291 if (auto *VT = dyn_cast<VectorType>(Ty))
1292 return cast<FixedVectorType>(VT)->getNumElements();
1293 return Ty->getStructNumElements();
1294}
1295
1296//===----------------------------------------------------------------------===//
1297// PoisonValue Implementation
1298//===----------------------------------------------------------------------===//
1299
1302 return PoisonValue::get(ATy->getElementType());
1303 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1304}
1305
1306PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1307 return PoisonValue::get(getType()->getStructElementType(Elt));
1308}
1309
1312 return getSequentialElement();
1313 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1314}
1315
1316PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1318 return getSequentialElement();
1319 return getStructElement(Idx);
1320}
1321
1322//===----------------------------------------------------------------------===//
1323// ConstantXXX Classes
1324//===----------------------------------------------------------------------===//
1325
1326template <typename ItTy, typename EltTy>
1327static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1328 for (; Start != End; ++Start)
1329 if (*Start != Elt)
1330 return false;
1331 return true;
1332}
1333
1334template <typename SequentialTy, typename ElementTy>
1336 assert(!V.empty() && "Cannot get empty int sequence.");
1337
1339 for (Constant *C : V)
1340 if (auto *CI = dyn_cast<ConstantInt>(C))
1341 Elts.push_back(CI->getZExtValue());
1342 else
1343 return nullptr;
1344 return SequentialTy::get(V[0]->getContext(), Elts);
1345}
1346
1347template <typename SequentialTy, typename ElementTy>
1349 assert(!V.empty() && "Cannot get empty byte sequence.");
1350
1352 for (Constant *C : V)
1353 if (auto *CI = dyn_cast<ConstantByte>(C))
1354 Elts.push_back(CI->getZExtValue());
1355 else
1356 return nullptr;
1357 return SequentialTy::getByte(V[0]->getType(), Elts);
1358}
1359
1360template <typename SequentialTy, typename ElementTy>
1362 assert(!V.empty() && "Cannot get empty FP sequence.");
1363
1365 for (Constant *C : V)
1366 if (auto *CFP = dyn_cast<ConstantFP>(C))
1367 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1368 else
1369 return nullptr;
1370 return SequentialTy::getFP(V[0]->getType(), Elts);
1371}
1372
1373template <typename SequenceTy>
1376 // We speculatively build the elements here even if it turns out that there is
1377 // a constantexpr or something else weird, since it is so uncommon for that to
1378 // happen.
1379 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1380 if (CI->getType()->isIntegerTy(8))
1382 else if (CI->getType()->isIntegerTy(16))
1384 else if (CI->getType()->isIntegerTy(32))
1386 else if (CI->getType()->isIntegerTy(64))
1388 } else if (ConstantByte *CB = dyn_cast<ConstantByte>(C)) {
1389 if (CB->getType()->isByteTy(8))
1391 else if (CB->getType()->isByteTy(16))
1393 else if (CB->getType()->isByteTy(32))
1395 else if (CB->getType()->isByteTy(64))
1397 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1398 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1400 else if (CFP->getType()->isFloatTy())
1402 else if (CFP->getType()->isDoubleTy())
1404 }
1405
1406 return nullptr;
1407}
1408
1412 : Constant(T, VT, AllocInfo) {
1413 llvm::copy(V, op_begin());
1414
1415 // Check that types match, unless this is an opaque struct.
1416 if (auto *ST = dyn_cast<StructType>(T)) {
1417 if (ST->isOpaque())
1418 return;
1419 for (unsigned I = 0, E = V.size(); I != E; ++I)
1420 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1421 "Initializer for struct element doesn't match!");
1422 }
1423}
1424
1425ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1427 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1428 assert(V.size() == T->getNumElements() &&
1429 "Invalid initializer for constant array");
1430}
1431
1433 if (Constant *C = getImpl(Ty, V))
1434 return C;
1435 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1436}
1437
1438Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1439 // Empty arrays are canonicalized to ConstantAggregateZero.
1440 if (V.empty())
1441 return ConstantAggregateZero::get(Ty);
1442
1443 for (Constant *C : V) {
1444 assert(C->getType() == Ty->getElementType() &&
1445 "Wrong type in array element initializer");
1446 (void)C;
1447 }
1448
1449 // If this is an all-zero array, return a ConstantAggregateZero object. If
1450 // all undef, return an UndefValue, if "all simple", then return a
1451 // ConstantDataArray.
1452 Constant *C = V[0];
1453 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1454 return PoisonValue::get(Ty);
1455
1456 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1457 return UndefValue::get(Ty);
1458
1459 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1460 return ConstantAggregateZero::get(Ty);
1461
1462 // Check to see if all of the elements are ConstantFP or ConstantInt or
1463 // ConstantByte and if the element type is compatible with ConstantDataVector.
1464 // If so, use it.
1467
1468 // Otherwise, we really do want to create a ConstantArray.
1469 return nullptr;
1470}
1471
1474 bool Packed) {
1475 unsigned VecSize = V.size();
1476 SmallVector<Type*, 16> EltTypes(VecSize);
1477 for (unsigned i = 0; i != VecSize; ++i)
1478 EltTypes[i] = V[i]->getType();
1479
1480 return StructType::get(Context, EltTypes, Packed);
1481}
1482
1483
1485 bool Packed) {
1486 assert(!V.empty() &&
1487 "ConstantStruct::getTypeForElements cannot be called on empty list");
1488 return getTypeForElements(V[0]->getContext(), V, Packed);
1489}
1490
1491ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1493 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1494 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1495 "Invalid initializer for constant struct");
1496}
1497
1498// ConstantStruct accessors.
1500 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1501 "Incorrect # elements specified to ConstantStruct::get");
1502
1503 // Create a ConstantAggregateZero value if all elements are zeros.
1504 bool isZero = true;
1505 bool isUndef = false;
1506 bool isPoison = false;
1507
1508 if (!V.empty()) {
1509 isUndef = isa<UndefValue>(V[0]);
1510 isPoison = isa<PoisonValue>(V[0]);
1511 isZero = V[0]->isNullValue();
1512 // PoisonValue inherits UndefValue, so its check is not necessary.
1513 if (isUndef || isZero) {
1514 for (Constant *C : V) {
1515 if (!C->isNullValue())
1516 isZero = false;
1517 if (!isa<PoisonValue>(C))
1518 isPoison = false;
1520 isUndef = false;
1521 }
1522 }
1523 }
1524 if (isZero)
1525 return ConstantAggregateZero::get(ST);
1526 if (isPoison)
1527 return PoisonValue::get(ST);
1528 if (isUndef)
1529 return UndefValue::get(ST);
1530
1531 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1532}
1533
1534ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1536 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1537 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1538 "Invalid initializer for constant vector");
1539}
1540
1541// ConstantVector accessors.
1543 if (Constant *C = getImpl(V))
1544 return C;
1545 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1546 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1547}
1548
1549Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1550 assert(!V.empty() && "Vectors can't be empty");
1551 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1552
1553 // If this is an all-undef or all-zero vector, return a
1554 // ConstantAggregateZero or UndefValue.
1555 Constant *C = V[0];
1556 bool isZero = C->isNullValue();
1557 bool isUndef = isa<UndefValue>(C);
1558 bool isPoison = isa<PoisonValue>(C);
1559 bool isSplatFP = isa<ConstantFP>(C);
1561 bool isSplatByte = isa<ConstantByte>(C);
1562 bool isSplatPtrNull = isa<ConstantPointerNull>(C);
1563
1564 if (isZero || isUndef || isSplatFP || isSplatInt || isSplatByte ||
1565 isSplatPtrNull) {
1566 for (unsigned i = 1, e = V.size(); i != e; ++i)
1567 if (V[i] != C) {
1568 isZero = isUndef = isPoison = isSplatFP = isSplatInt = isSplatByte =
1569 isSplatPtrNull = false;
1570 break;
1571 }
1572 }
1573
1574 if (isSplatPtrNull)
1576 if (isZero)
1578 if (isPoison)
1579 return PoisonValue::get(T);
1580 if (isUndef)
1581 return UndefValue::get(T);
1582 if (isSplatFP)
1583 return ConstantFP::get(C->getContext(), T->getElementCount(),
1584 cast<ConstantFP>(C)->getValue());
1585 if (isSplatInt)
1586 return ConstantInt::get(C->getContext(), T->getElementCount(),
1587 cast<ConstantInt>(C)->getValue());
1588 if (isSplatByte)
1589 return ConstantByte::get(C->getContext(), T->getElementCount(),
1590 cast<ConstantByte>(C)->getValue());
1591
1592 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1593 // the element type is compatible with ConstantDataVector. If so, use it.
1596
1597 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1598 // the operand list contains a ConstantExpr or something else strange.
1599 return nullptr;
1600}
1601
1603 if (isa<ConstantPointerNull>(V)) {
1604 VectorType *VTy = VectorType::get(V->getType(), EC);
1605 return ConstantPointerNull::get(VTy);
1606 }
1607
1608 if (auto *CB = dyn_cast<ConstantByte>(V))
1609 return ConstantByte::get(V->getContext(), EC, CB->getValue());
1610
1611 if (auto *CFP = dyn_cast<ConstantFP>(V))
1612 return ConstantFP::get(V->getContext(), EC, CFP->getValue());
1613
1614 if (!EC.isScalable()) {
1615 // Maintain special handling of zero.
1616 if (!V->isNullValue()) {
1618 return ConstantInt::get(V->getContext(), EC,
1619 cast<ConstantInt>(V)->getValue());
1620 }
1621
1622 // If this splat is compatible with ConstantDataVector, use it instead of
1623 // ConstantVector.
1624 if (isa<ConstantInt>(V) &&
1626 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1627
1628 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1629 return get(Elts);
1630 }
1631
1632 // Maintain special handling of zero.
1633 if (!V->isNullValue()) {
1635 return ConstantInt::get(V->getContext(), EC,
1636 cast<ConstantInt>(V)->getValue());
1637 }
1638
1639 Type *VTy = VectorType::get(V->getType(), EC);
1640
1641 if (V->isNullValue())
1642 return ConstantAggregateZero::get(VTy);
1643 if (isa<PoisonValue>(V))
1644 return PoisonValue::get(VTy);
1645 if (isa<UndefValue>(V))
1646 return UndefValue::get(VTy);
1647
1648 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1649
1650 // Move scalar into vector.
1651 Constant *PoisonV = PoisonValue::get(VTy);
1652 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1653 // Build shuffle mask to perform the splat.
1654 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1655 // Splat.
1656 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1657}
1658
1659ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1660 LLVMContextImpl *pImpl = Context.pImpl;
1661 if (!pImpl->TheNoneToken)
1662 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1663 return pImpl->TheNoneToken.get();
1664}
1665
1666/// Remove the constant from the constant table.
1667void ConstantTokenNone::destroyConstantImpl() {
1668 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1669}
1670
1671// Utility function for determining if a ConstantExpr is a CastOp or not. This
1672// can't be inline because we don't want to #include Instruction.h into
1673// Constant.h
1675
1679
1681 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1682}
1683
1685 bool OnlyIfReduced, Type *SrcTy) const {
1686 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1687
1688 // If no operands changed return self.
1689 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1690 return const_cast<ConstantExpr*>(this);
1691
1692 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1693 switch (getOpcode()) {
1694 case Instruction::Trunc:
1695 case Instruction::ZExt:
1696 case Instruction::SExt:
1697 case Instruction::FPTrunc:
1698 case Instruction::FPExt:
1699 case Instruction::UIToFP:
1700 case Instruction::SIToFP:
1701 case Instruction::FPToUI:
1702 case Instruction::FPToSI:
1703 case Instruction::PtrToAddr:
1704 case Instruction::PtrToInt:
1705 case Instruction::IntToPtr:
1706 case Instruction::BitCast:
1707 case Instruction::AddrSpaceCast:
1708 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1709 case Instruction::InsertElement:
1710 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1711 OnlyIfReducedTy);
1712 case Instruction::ExtractElement:
1713 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1714 case Instruction::ShuffleVector:
1716 OnlyIfReducedTy);
1717 case Instruction::GetElementPtr: {
1718 auto *GEPO = cast<GEPOperator>(this);
1719 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1721 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1722 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1723 }
1724 default:
1725 assert(getNumOperands() == 2 && "Must be binary operator?");
1727 OnlyIfReducedTy);
1728 }
1729}
1730
1731
1732//===----------------------------------------------------------------------===//
1733// isValueValidForType implementations
1734
1736 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1737 if (Ty->isIntegerTy(1))
1738 return Val == 0 || Val == 1;
1739 return isUIntN(NumBits, Val);
1740}
1741
1743 unsigned NumBits = Ty->getIntegerBitWidth();
1744 if (Ty->isIntegerTy(1))
1745 return Val == 0 || Val == 1 || Val == -1;
1746 return isIntN(NumBits, Val);
1747}
1748
1750 // convert modifies in place, so make a copy.
1751 APFloat Val2 = APFloat(Val);
1752 bool losesInfo;
1753 switch (Ty->getTypeID()) {
1754 default:
1755 return false; // These can't be represented as floating point!
1756
1757 // FIXME rounding mode needs to be more flexible
1758 case Type::HalfTyID: {
1759 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1760 return true;
1762 return !losesInfo;
1763 }
1764 case Type::BFloatTyID: {
1765 if (&Val2.getSemantics() == &APFloat::BFloat())
1766 return true;
1768 return !losesInfo;
1769 }
1770 case Type::FloatTyID: {
1771 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1772 return true;
1774 return !losesInfo;
1775 }
1776 case Type::DoubleTyID: {
1777 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1778 &Val2.getSemantics() == &APFloat::BFloat() ||
1779 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1780 &Val2.getSemantics() == &APFloat::IEEEdouble())
1781 return true;
1783 return !losesInfo;
1784 }
1785 case Type::X86_FP80TyID:
1786 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1787 &Val2.getSemantics() == &APFloat::BFloat() ||
1788 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1789 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1791 case Type::FP128TyID:
1792 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1793 &Val2.getSemantics() == &APFloat::BFloat() ||
1794 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1795 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1796 &Val2.getSemantics() == &APFloat::IEEEquad();
1798 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1799 &Val2.getSemantics() == &APFloat::BFloat() ||
1800 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1801 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1803 }
1804}
1805
1806
1807//===----------------------------------------------------------------------===//
1808// Factory Function Implementation
1809
1810ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1811 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1812 "Cannot create an aggregate zero of non-aggregate type!");
1813
1814 std::unique_ptr<ConstantAggregateZero> &Entry =
1815 Ty->getContext().pImpl->CAZConstants[Ty];
1816 if (!Entry)
1817 Entry.reset(new ConstantAggregateZero(Ty));
1818
1819 return Entry.get();
1820}
1821
1822/// Remove the constant from the constant table.
1823void ConstantAggregateZero::destroyConstantImpl() {
1825}
1826
1827/// Remove the constant from the constant table.
1828void ConstantArray::destroyConstantImpl() {
1830}
1831
1832
1833//---- ConstantStruct::get() implementation...
1834//
1835
1836/// Remove the constant from the constant table.
1837void ConstantStruct::destroyConstantImpl() {
1839}
1840
1841/// Remove the constant from the constant table.
1842void ConstantVector::destroyConstantImpl() {
1844}
1845
1846Constant *Constant::getSplatValue(bool AllowPoison) const {
1847 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1848 if (isa<PoisonValue>(this))
1849 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1851 return getNullValue(cast<VectorType>(getType())->getElementType());
1852 if (auto *CI = dyn_cast<ConstantInt>(this))
1853 return ConstantInt::get(getContext(), CI->getValue());
1854 if (auto *CB = dyn_cast<ConstantByte>(this))
1855 return ConstantByte::get(getContext(), CB->getValue());
1856 if (auto *CFP = dyn_cast<ConstantFP>(this))
1857 return ConstantFP::get(getContext(), CFP->getValue());
1858 if (auto *CPN = dyn_cast<ConstantPointerNull>(this))
1859 return ConstantPointerNull::get(CPN->getPointerType());
1861 return CV->getSplatValue();
1862 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1863 return CV->getSplatValue(AllowPoison);
1864
1865 // Check if this is a constant expression splat of the form returned by
1866 // ConstantVector::getSplat()
1867 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1868 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1869 isa<UndefValue>(Shuf->getOperand(1))) {
1870
1871 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1872 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1873 isa<UndefValue>(IElt->getOperand(0))) {
1874
1875 ArrayRef<int> Mask = Shuf->getShuffleMask();
1876 Constant *SplatVal = IElt->getOperand(1);
1877 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1878
1879 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1880 return SplatVal;
1881 }
1882 }
1883
1884 return nullptr;
1885}
1886
1887Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1888 // Check out first element.
1889 Constant *Elt = getOperand(0);
1890 // Then make sure all remaining elements point to the same value.
1891 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1892 Constant *OpC = getOperand(I);
1893 if (OpC == Elt)
1894 continue;
1895
1896 // Strict mode: any mismatch is not a splat.
1897 if (!AllowPoison)
1898 return nullptr;
1899
1900 // Allow poison mode: ignore poison elements.
1901 if (isa<PoisonValue>(OpC))
1902 continue;
1903
1904 // If we do not have a defined element yet, use the current operand.
1905 if (isa<PoisonValue>(Elt))
1906 Elt = OpC;
1907
1908 if (OpC != Elt)
1909 return nullptr;
1910 }
1911 return Elt;
1912}
1913
1915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1916 return CI->getValue();
1917 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
1918 return CB->getValue();
1919 // Scalable vectors can use a ConstantExpr to build a splat.
1920 if (isa<ConstantExpr>(this))
1921 return cast<ConstantInt>(this->getSplatValue())->getValue();
1922 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1923 // calling getSplatValue in release builds.
1924 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1925 const Constant *C = this->getAggregateElement(0U);
1926 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1927 return cast<ConstantInt>(C)->getValue();
1928}
1929
1931 if (auto *CI = dyn_cast<ConstantInt>(this))
1932 return ConstantRange(CI->getValue());
1933
1934 unsigned BitWidth = getType()->getScalarSizeInBits();
1935 if (!getType()->isVectorTy())
1936 return ConstantRange::getFull(BitWidth);
1937
1938 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1939 getSplatValue(/*AllowPoison=*/true)))
1940 return ConstantRange(CI->getValue());
1941
1942 if (auto *CB =
1943 dyn_cast_or_null<ConstantByte>(getSplatValue(/*AllowPoison=*/true)))
1944 return ConstantRange(CB->getValue());
1945
1946 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1947 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1948 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1949 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1950 return CR;
1951 }
1952
1953 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1954 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1955 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1956 Constant *Elem = CV->getOperand(I);
1957 if (!Elem)
1958 return ConstantRange::getFull(BitWidth);
1959 if (isa<PoisonValue>(Elem))
1960 continue;
1961 auto *CI = dyn_cast<ConstantInt>(Elem);
1962 auto *CB = dyn_cast<ConstantByte>(Elem);
1963 if (!CI && !CB)
1964 return ConstantRange::getFull(BitWidth);
1965 CR = CR.unionWith(CI ? CI->getValue() : CB->getValue());
1966 }
1967 return CR;
1968 }
1969
1970 return ConstantRange::getFull(BitWidth);
1971}
1972
1973//---- ConstantPointerNull::get() implementation.
1974//
1975
1976ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1977 return get(static_cast<Type *>(Ty));
1978}
1979
1980ConstantPointerNull *ConstantPointerNull::get(Type *Ty) {
1981 assert(Ty->isPtrOrPtrVectorTy() && "invalid type for null pointer constant");
1982 std::unique_ptr<ConstantPointerNull> &Entry =
1983 Ty->getContext().pImpl->CPNConstants[Ty];
1984 if (!Entry)
1985 Entry.reset(new ConstantPointerNull(Ty));
1986
1987 assert(Entry->getType() == Ty);
1988 return Entry.get();
1989}
1990
1991/// Remove the constant from the constant table.
1992void ConstantPointerNull::destroyConstantImpl() {
1994}
1995
1996//---- ConstantTargetNone::get() implementation.
1997//
1998
1999ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
2000 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
2001 "Target extension type not allowed to have a zeroinitializer");
2002 std::unique_ptr<ConstantTargetNone> &Entry =
2003 Ty->getContext().pImpl->CTNConstants[Ty];
2004 if (!Entry)
2005 Entry.reset(new ConstantTargetNone(Ty));
2006
2007 return Entry.get();
2008}
2009
2010/// Remove the constant from the constant table.
2011void ConstantTargetNone::destroyConstantImpl() {
2013}
2014
2015UndefValue *UndefValue::get(Type *Ty) {
2016 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
2017 if (!Entry)
2018 Entry.reset(new UndefValue(Ty));
2019
2020 return Entry.get();
2021}
2022
2023/// Remove the constant from the constant table.
2024void UndefValue::destroyConstantImpl() {
2025 // Free the constant and any dangling references to it.
2026 if (getValueID() == UndefValueVal) {
2027 getContext().pImpl->UVConstants.erase(getType());
2028 } else if (getValueID() == PoisonValueVal) {
2029 getContext().pImpl->PVConstants.erase(getType());
2030 }
2031 llvm_unreachable("Not a undef or a poison!");
2032}
2033
2034PoisonValue *PoisonValue::get(Type *Ty) {
2035 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
2036 if (!Entry)
2037 Entry.reset(new PoisonValue(Ty));
2038
2039 return Entry.get();
2040}
2041
2042/// Remove the constant from the constant table.
2043void PoisonValue::destroyConstantImpl() {
2044 // Free the constant and any dangling references to it.
2045 getContext().pImpl->PVConstants.erase(getType());
2046}
2047
2048BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
2049 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
2050 if (!BA)
2051 BA = new BlockAddress(Ty, BB);
2052 return BA;
2053}
2054
2055BlockAddress *BlockAddress::get(BasicBlock *BB) {
2056 assert(BB->getParent() && "Block must have a parent");
2057 return get(BB->getParent()->getType(), BB);
2058}
2059
2061 assert(BB->getParent() == F && "Block not part of specified function");
2062 return get(BB->getParent()->getType(), BB);
2063}
2064
2065BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
2066 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
2067 Block = BB;
2068 BB->setHasAddressTaken(true);
2069}
2070
2071BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
2072 if (!BB->hasAddressTaken())
2073 return nullptr;
2074
2075 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
2076 assert(BA && "Refcount and block address map disagree!");
2077 return BA;
2078}
2079
2080/// Remove the constant from the constant table.
2081void BlockAddress::destroyConstantImpl() {
2083 getBasicBlock()->setHasAddressTaken(false);
2084}
2085
2086Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
2087 assert(From == getBasicBlock());
2088 BasicBlock *NewBB = cast<BasicBlock>(To);
2089
2090 // See if the 'new' entry already exists, if not, just update this in place
2091 // and return early.
2092 if (BlockAddress *NewBA = getContext().pImpl->BlockAddresses.lookup(NewBB))
2093 return NewBA;
2094
2095 getBasicBlock()->setHasAddressTaken(false);
2096
2097 // erase invalidates iterators/references, hence the duplicate NewBB lookup.
2099 getContext().pImpl->BlockAddresses[NewBB] = this;
2100 Block = NewBB;
2101 getBasicBlock()->setHasAddressTaken(true);
2102
2103 // If we just want to keep the existing value, then return null.
2104 // Callers know that this means we shouldn't delete this value.
2105 return nullptr;
2106}
2107
2108DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
2109 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
2110 if (!Equiv)
2111 Equiv = new DSOLocalEquivalent(GV);
2112
2113 assert(Equiv->getGlobalValue() == GV &&
2114 "DSOLocalFunction does not match the expected global value");
2115 return Equiv;
2116}
2117
2118DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
2119 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
2120 setOperand(0, GV);
2121}
2122
2123/// Remove the constant from the constant table.
2124void DSOLocalEquivalent::destroyConstantImpl() {
2125 const GlobalValue *GV = getGlobalValue();
2126 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2127}
2128
2129Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2130 assert(From == getGlobalValue() && "Changing value does not match operand.");
2131 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2132
2133 // If the argument is replaced with a null value, just replace this constant
2134 // with a null value.
2136 return To;
2137
2138 // The replacement could be a bitcast to another GlobalValue. We can
2139 // replace it with a bitcast to the dso_local_equivalent of that GV.
2140 GlobalValue *GV = cast<GlobalValue>(To->stripPointerCasts());
2141 if (DSOLocalEquivalent *NewEquiv =
2142 getContext().pImpl->DSOLocalEquivalents.lookup(GV))
2143 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2144
2145 // erase invalidates iterators/references, hence the duplicate GV lookup.
2147 getContext().pImpl->DSOLocalEquivalents[GV] = this;
2148 setOperand(0, GV);
2149
2150 if (GV->getType() != getType()) {
2151 // It is ok to mutate the type here because this constant should always
2152 // reflect the type of the function it's holding.
2153 mutateType(GV->getType());
2154 }
2155 return nullptr;
2156}
2157
2159 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2160 if (!NC)
2161 NC = new NoCFIValue(GV);
2162
2163 assert(NC->getGlobalValue() == GV &&
2164 "NoCFIValue does not match the expected global value");
2165 return NC;
2166}
2167
2168NoCFIValue::NoCFIValue(GlobalValue *GV)
2169 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2170 setOperand(0, GV);
2171}
2172
2173/// Remove the constant from the constant table.
2174void NoCFIValue::destroyConstantImpl() {
2175 const GlobalValue *GV = getGlobalValue();
2176 GV->getContext().pImpl->NoCFIValues.erase(GV);
2177}
2178
2179Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2180 assert(From == getGlobalValue() && "Changing value does not match operand.");
2181
2182 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2183 assert(GV && "Can only replace the operands with a global value");
2184
2185 if (NoCFIValue *NewNC = getContext().pImpl->NoCFIValues.lookup(GV))
2186 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2187
2188 // erase invalidates iterators/references, hence the duplicate GV lookup.
2190 getContext().pImpl->NoCFIValues[GV] = this;
2191 setOperand(0, GV);
2192
2193 if (GV->getType() != getType())
2194 mutateType(GV->getType());
2195
2196 return nullptr;
2197}
2198
2199//---- ConstantPtrAuth::get() implementations.
2200//
2201
2203 ConstantInt *Disc, Constant *AddrDisc,
2204 Constant *DeactivationSymbol) {
2205 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2206 ConstantPtrAuthKeyType MapKey(ArgVec);
2207 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2208 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2209}
2210
2211ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2212 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2214}
2215
2216ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2217 ConstantInt *Disc, Constant *AddrDisc,
2218 Constant *DeactivationSymbol)
2219 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2220 assert(Ptr->getType()->isPointerTy());
2221 assert(Key->getBitWidth() == 32);
2222 assert(Disc->getBitWidth() == 64);
2223 assert(AddrDisc->getType()->isPointerTy());
2224 assert(DeactivationSymbol->getType()->isPointerTy());
2225 setOperand(0, Ptr);
2226 setOperand(1, Key);
2227 setOperand(2, Disc);
2228 setOperand(3, AddrDisc);
2229 setOperand(4, DeactivationSymbol);
2230}
2231
2232/// Remove the constant from the constant table.
2233void ConstantPtrAuth::destroyConstantImpl() {
2234 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2235}
2236
2237Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2238 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2239 Constant *To = cast<Constant>(ToV);
2240
2241 SmallVector<Constant *, 4> Values;
2242 Values.reserve(getNumOperands());
2243
2244 unsigned NumUpdated = 0;
2245
2246 Use *OperandList = getOperandList();
2247 unsigned OperandNo = 0;
2248 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2249 Constant *Val = cast<Constant>(O->get());
2250 if (Val == From) {
2251 OperandNo = (O - OperandList);
2252 Val = To;
2253 ++NumUpdated;
2254 }
2255 Values.push_back(Val);
2256 }
2257
2258 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2259 Values, this, From, To, NumUpdated, OperandNo);
2260}
2261
2263 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2264 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2265 return false;
2266
2267 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2268 if (!IntVal)
2269 return false;
2270
2271 return IntVal->getValue() == Value;
2272}
2273
2275 const Value *Discriminator,
2276 const DataLayout &DL) const {
2277 // This function may only be validly called to analyze a ptrauth operation
2278 // with no deactivation symbol, so if we have one it isn't compatible.
2280 return false;
2281
2282 // If the keys are different, there's no chance for this to be compatible.
2283 if (getKey() != Key)
2284 return false;
2285
2286 // We can have 3 kinds of discriminators:
2287 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2288 // - address-only: `i64 0, ptr p` vs. `ptr p`
2289 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2290
2291 // If this constant has a simple discriminator (integer, no address), easy:
2292 // it's compatible iff the provided full discriminator is also a simple
2293 // discriminator, identical to our integer discriminator.
2295 return getDiscriminator() == Discriminator;
2296
2297 // Otherwise, we can isolate address and integer discriminator components.
2298 const Value *AddrDiscriminator = nullptr;
2299
2300 // This constant may or may not have an integer discriminator (instead of 0).
2301 if (!getDiscriminator()->isNullValue()) {
2302 // If it does, there's an implicit blend. We need to have a matching blend
2303 // intrinsic in the provided full discriminator.
2304 if (!match(Discriminator,
2306 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2307 return false;
2308 } else {
2309 // Otherwise, interpret the provided full discriminator as address-only.
2310 AddrDiscriminator = Discriminator;
2311 }
2312
2313 // Either way, we can now focus on comparing the address discriminators.
2314
2315 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2316 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2317 AddrDiscriminator = Cast->getPointerOperand();
2318
2319 // Beyond that, we're only interested in compatible pointers.
2320 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2321 return false;
2322
2323 // These are often the same constant GEP, making them trivially equivalent.
2324 if (getAddrDiscriminator() == AddrDiscriminator)
2325 return true;
2326
2327 // Finally, they may be equivalent base+offset expressions.
2328 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2330 DL, Off1, /*AllowNonInbounds=*/true);
2331
2332 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2333 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2334 DL, Off2, /*AllowNonInbounds=*/true);
2335
2336 return Base1 == Base2 && Off1 == Off2;
2337}
2338
2339//---- ConstantExpr::get() implementations.
2340//
2341
2342/// This is a utility function to handle folding of casts and lookup of the
2343/// cast in the ExprConstants map. It is used by the various get* methods below.
2345 bool OnlyIfReduced = false) {
2346 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2347 // Fold a few common cases
2348 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2349 return FC;
2350
2351 if (OnlyIfReduced)
2352 return nullptr;
2353
2354 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2355
2356 // Look up the constant in the table first to ensure uniqueness.
2358
2359 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2360}
2361
2363 bool OnlyIfReduced) {
2365 assert(Instruction::isCast(opc) && "opcode out of range");
2367 "Cast opcode not supported as constant expression");
2368 assert(C && Ty && "Null arguments to getCast");
2369 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2370
2371 switch (opc) {
2372 default:
2373 llvm_unreachable("Invalid cast opcode");
2374 case Instruction::Trunc:
2375 return getTrunc(C, Ty, OnlyIfReduced);
2376 case Instruction::PtrToAddr:
2377 return getPtrToAddr(C, Ty, OnlyIfReduced);
2378 case Instruction::PtrToInt:
2379 return getPtrToInt(C, Ty, OnlyIfReduced);
2380 case Instruction::IntToPtr:
2381 return getIntToPtr(C, Ty, OnlyIfReduced);
2382 case Instruction::BitCast:
2383 return getBitCast(C, Ty, OnlyIfReduced);
2384 case Instruction::AddrSpaceCast:
2385 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2386 }
2387}
2388
2390 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2391 return getBitCast(C, Ty);
2392 return getTrunc(C, Ty);
2393}
2394
2396 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2397 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2398 "Invalid cast");
2399
2400 if (Ty->isIntOrIntVectorTy())
2401 return getPtrToInt(S, Ty);
2402
2403 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2404 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2405 return getAddrSpaceCast(S, Ty);
2406
2407 return getBitCast(S, Ty);
2408}
2409
2411 Type *Ty) {
2412 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2413 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2414
2415 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2416 return getAddrSpaceCast(S, Ty);
2417
2418 return getBitCast(S, Ty);
2419}
2420
2421Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2422#ifndef NDEBUG
2423 bool fromVec = isa<VectorType>(C->getType());
2424 bool toVec = isa<VectorType>(Ty);
2425#endif
2426 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2427 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2428 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2429 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2430 "SrcTy must be larger than DestTy for Trunc!");
2431
2432 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2433}
2434
2436 bool OnlyIfReduced) {
2437 assert(C->getType()->isPtrOrPtrVectorTy() &&
2438 "PtrToAddr source must be pointer or pointer vector");
2439 assert(DstTy->isIntOrIntVectorTy() &&
2440 "PtrToAddr destination must be integer or integer vector");
2441 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2442 if (isa<VectorType>(C->getType()))
2443 assert(cast<VectorType>(C->getType())->getElementCount() ==
2444 cast<VectorType>(DstTy)->getElementCount() &&
2445 "Invalid cast between a different number of vector elements");
2446 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2447}
2448
2450 bool OnlyIfReduced) {
2451 assert(C->getType()->isPtrOrPtrVectorTy() &&
2452 "PtrToInt source must be pointer or pointer vector");
2453 assert(DstTy->isIntOrIntVectorTy() &&
2454 "PtrToInt destination must be integer or integer vector");
2455 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2456 if (isa<VectorType>(C->getType()))
2457 assert(cast<VectorType>(C->getType())->getElementCount() ==
2458 cast<VectorType>(DstTy)->getElementCount() &&
2459 "Invalid cast between a different number of vector elements");
2460 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2461}
2462
2464 bool OnlyIfReduced) {
2465 assert(C->getType()->isIntOrIntVectorTy() &&
2466 "IntToPtr source must be integer or integer vector");
2467 assert(DstTy->isPtrOrPtrVectorTy() &&
2468 "IntToPtr destination must be a pointer or pointer vector");
2469 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2470 if (isa<VectorType>(C->getType()))
2471 assert(cast<VectorType>(C->getType())->getElementCount() ==
2472 cast<VectorType>(DstTy)->getElementCount() &&
2473 "Invalid cast between a different number of vector elements");
2474 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2475}
2476
2478 bool OnlyIfReduced) {
2479 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2480 "Invalid constantexpr bitcast!");
2481
2482 // It is common to ask for a bitcast of a value to its own type, handle this
2483 // speedily.
2484 if (C->getType() == DstTy) return C;
2485
2486 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2487}
2488
2490 bool OnlyIfReduced) {
2491 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2492 "Invalid constantexpr addrspacecast!");
2493 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2494}
2495
2496Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2497 unsigned Flags, Type *OnlyIfReducedTy) {
2498 // Check the operands for consistency first.
2500 "Invalid opcode in binary constant expression");
2501 assert(isSupportedBinOp(Opcode) &&
2502 "Binop not supported as constant expression");
2503 assert(C1->getType() == C2->getType() &&
2504 "Operand types in binary constant expression should match");
2505
2506#ifndef NDEBUG
2507 switch (Opcode) {
2508 case Instruction::Add:
2509 case Instruction::Sub:
2510 case Instruction::Mul:
2512 "Tried to create an integer operation on a non-integer type!");
2513 break;
2514 case Instruction::And:
2515 case Instruction::Or:
2516 case Instruction::Xor:
2518 "Tried to create a logical operation on a non-integral type!");
2519 break;
2520 default:
2521 break;
2522 }
2523#endif
2524
2525 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2526 return FC;
2527
2528 if (OnlyIfReducedTy == C1->getType())
2529 return nullptr;
2530
2531 Constant *ArgVec[] = {C1, C2};
2532 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2533
2534 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2535 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2536}
2537
2538bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2539 switch (Opcode) {
2540 case Instruction::UDiv:
2541 case Instruction::SDiv:
2542 case Instruction::URem:
2543 case Instruction::SRem:
2544 case Instruction::FAdd:
2545 case Instruction::FSub:
2546 case Instruction::FMul:
2547 case Instruction::FDiv:
2548 case Instruction::FRem:
2549 case Instruction::And:
2550 case Instruction::Or:
2551 case Instruction::LShr:
2552 case Instruction::AShr:
2553 case Instruction::Shl:
2554 case Instruction::Mul:
2555 return false;
2556 case Instruction::Add:
2557 case Instruction::Sub:
2558 case Instruction::Xor:
2559 return true;
2560 default:
2561 llvm_unreachable("Argument must be binop opcode");
2562 }
2563}
2564
2565bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2566 switch (Opcode) {
2567 case Instruction::UDiv:
2568 case Instruction::SDiv:
2569 case Instruction::URem:
2570 case Instruction::SRem:
2571 case Instruction::FAdd:
2572 case Instruction::FSub:
2573 case Instruction::FMul:
2574 case Instruction::FDiv:
2575 case Instruction::FRem:
2576 case Instruction::And:
2577 case Instruction::Or:
2578 case Instruction::LShr:
2579 case Instruction::AShr:
2580 case Instruction::Shl:
2581 case Instruction::Mul:
2582 return false;
2583 case Instruction::Add:
2584 case Instruction::Sub:
2585 case Instruction::Xor:
2586 return true;
2587 default:
2588 llvm_unreachable("Argument must be binop opcode");
2589 }
2590}
2591
2592bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2593 switch (Opcode) {
2594 case Instruction::ZExt:
2595 case Instruction::SExt:
2596 case Instruction::FPTrunc:
2597 case Instruction::FPExt:
2598 case Instruction::UIToFP:
2599 case Instruction::SIToFP:
2600 case Instruction::FPToUI:
2601 case Instruction::FPToSI:
2602 return false;
2603 case Instruction::Trunc:
2604 case Instruction::PtrToAddr:
2605 case Instruction::PtrToInt:
2606 case Instruction::IntToPtr:
2607 case Instruction::BitCast:
2608 case Instruction::AddrSpaceCast:
2609 return true;
2610 default:
2611 llvm_unreachable("Argument must be cast opcode");
2612 }
2613}
2614
2615bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2616 switch (Opcode) {
2617 case Instruction::ZExt:
2618 case Instruction::SExt:
2619 case Instruction::FPTrunc:
2620 case Instruction::FPExt:
2621 case Instruction::UIToFP:
2622 case Instruction::SIToFP:
2623 case Instruction::FPToUI:
2624 case Instruction::FPToSI:
2625 return false;
2626 case Instruction::Trunc:
2627 case Instruction::PtrToAddr:
2628 case Instruction::PtrToInt:
2629 case Instruction::IntToPtr:
2630 case Instruction::BitCast:
2631 case Instruction::AddrSpaceCast:
2632 return true;
2633 default:
2634 llvm_unreachable("Argument must be cast opcode");
2635 }
2636}
2637
2639 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2640 // Note that a non-inbounds gep is used, as null isn't within any object.
2641 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2643 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2644 GEPIdx);
2645 return getPtrToInt(GEP,
2646 Type::getInt64Ty(Ty->getContext()));
2647}
2648
2650 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2651 // Note that a non-inbounds gep is used, as null isn't within any object.
2652 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2653 Constant *NullPtr =
2655 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2656 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2657 Constant *Indices[2] = {Zero, One};
2658 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2659 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2660}
2661
2663 ArrayRef<Value *> Idxs,
2664 GEPNoWrapFlags NW,
2665 std::optional<ConstantRange> InRange,
2666 Type *OnlyIfReducedTy) {
2667 assert(Ty && "Must specify element type");
2668 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2669
2670 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2671 return FC; // Fold a few common cases.
2672
2673 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2674 ;
2675
2676 // Get the result type of the getelementptr!
2678 if (OnlyIfReducedTy == ReqTy)
2679 return nullptr;
2680
2681 auto EltCount = ElementCount::getFixed(0);
2682 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2683 EltCount = VecTy->getElementCount();
2684
2685 // Look up the constant in the table first to ensure uniqueness
2686 std::vector<Constant*> ArgVec;
2687 ArgVec.reserve(1 + Idxs.size());
2688 ArgVec.push_back(C);
2689 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2690 for (; GTI != GTE; ++GTI) {
2691 auto *Idx = cast<Constant>(GTI.getOperand());
2692 assert(
2693 (!isa<VectorType>(Idx->getType()) ||
2694 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2695 "getelementptr index type missmatch");
2696
2697 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2698 Idx = Idx->getSplatValue();
2699 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2700 !Idx->getType()->isVectorTy()) {
2701 Idx = ConstantVector::getSplat(EltCount, Idx);
2702 }
2703 ArgVec.push_back(Idx);
2704 }
2705
2706 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2707 {}, Ty, InRange);
2708
2709 LLVMContextImpl *pImpl = C->getContext().pImpl;
2710 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2711}
2712
2715 GEPNoWrapFlags NW,
2716 std::optional<ConstantRange> InRange,
2717 Type *OnlyIfReducedTy) {
2718 // Handle already canonical GEP.
2719 if (Ty->isIntegerTy(8) && Idxs[0]->getType() == DL.getIndexType(C->getType()))
2720 return getPtrAdd(C, Idxs[0], NW, InRange, OnlyIfReducedTy);
2721
2722 // Some API require an ArrayRef of Value * instead of Constant *.
2723 ArrayRef<Value *> ValIdxs =
2724 ArrayRef((Value *const *)Idxs.data(), Idxs.size());
2725 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2726
2727 if (!isSupportedGetElementPtr(Ty))
2728 return nullptr;
2729
2730 Type *RetTy = GetElementPtrInst::getGEPReturnType(C, ValIdxs);
2731 Type *IdxTy = DL.getIndexType(RetTy);
2732
2734 auto GTI = gep_type_begin(Ty, ValIdxs), GTE = gep_type_end(Ty, ValIdxs);
2735 for (; GTI != GTE; ++GTI) {
2736 auto *Idx = cast<Constant>(GTI.getOperand());
2737 if (Idx->isNullValue())
2738 continue;
2739
2740 if (StructType *STy = GTI.getStructTypeOrNull()) {
2741 uint64_t OpValue = Idx->getUniqueInteger().getZExtValue();
2742 uint64_t Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
2743 if (!Size)
2744 continue;
2745
2746 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset,
2747 ConstantInt::get(IdxTy, Size));
2748 if (!Offset)
2749 return nullptr;
2750
2751 continue;
2752 }
2753
2754 // Splat the index if needed.
2755 if (IdxTy->isVectorTy() && !Idx->getType()->isVectorTy())
2756 Idx = ConstantVector::getSplat(cast<VectorType>(IdxTy)->getElementCount(),
2757 Idx);
2758
2759 // Convert to correct type.
2760 if (Idx->getType() != IdxTy) {
2761 Idx = ConstantFoldCastInstruction(Idx->getType()->getScalarSizeInBits() <
2762 IdxTy->getScalarSizeInBits()
2763 ? Instruction::SExt
2764 : Instruction::Trunc,
2765 Idx, IdxTy);
2766 if (!Idx)
2767 return nullptr;
2768 }
2769
2770 TypeSize TySize = GTI.getSequentialElementStride(DL);
2771 if (TySize.isScalable())
2772 return nullptr;
2773
2774 // Multiply by scale.
2775 if (TySize != TypeSize::getFixed(1)) {
2776 Constant *Scale = ConstantInt::getSigned(IdxTy, TySize.getFixedValue(),
2777 /*ImplicitTrunc=*/true);
2778 Idx = ConstantFoldBinaryInstruction(Instruction::Mul, Idx, Scale);
2779 if (!Idx)
2780 return nullptr;
2781 }
2782
2783 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset, Idx);
2784 if (!Offset)
2785 return nullptr;
2786 }
2787
2788 return getPtrAdd(C, Offset, NW, InRange, OnlyIfReducedTy);
2789}
2790
2792 Type *OnlyIfReducedTy) {
2793 assert(Val->getType()->isVectorTy() &&
2794 "Tried to create extractelement operation on non-vector type!");
2795 assert(Idx->getType()->isIntegerTy() &&
2796 "Extractelement index must be an integer type!");
2797
2799 return FC; // Fold a few common cases.
2800
2801 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2802 if (OnlyIfReducedTy == ReqTy)
2803 return nullptr;
2804
2805 // Look up the constant in the table first to ensure uniqueness
2806 Constant *ArgVec[] = { Val, Idx };
2807 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2808
2809 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2810 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2811}
2812
2814 Constant *Idx, Type *OnlyIfReducedTy) {
2815 assert(Val->getType()->isVectorTy() &&
2816 "Tried to create insertelement operation on non-vector type!");
2817 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2818 "Insertelement types must match!");
2819 assert(Idx->getType()->isIntegerTy() &&
2820 "Insertelement index must be i32 type!");
2821
2822 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2823 return FC; // Fold a few common cases.
2824
2825 if (OnlyIfReducedTy == Val->getType())
2826 return nullptr;
2827
2828 // Look up the constant in the table first to ensure uniqueness
2829 Constant *ArgVec[] = { Val, Elt, Idx };
2830 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2831
2832 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2833 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2834}
2835
2837 ArrayRef<int> Mask,
2838 Type *OnlyIfReducedTy) {
2840 "Invalid shuffle vector constant expr operands!");
2841
2843 return FC; // Fold a few common cases.
2844
2845 unsigned NElts = Mask.size();
2846 auto V1VTy = cast<VectorType>(V1->getType());
2847 Type *EltTy = V1VTy->getElementType();
2848 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2849 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2850
2851 if (OnlyIfReducedTy == ShufTy)
2852 return nullptr;
2853
2854 // Look up the constant in the table first to ensure uniqueness
2855 Constant *ArgVec[] = {V1, V2};
2856 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2857
2858 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2859 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2860}
2861
2863 assert(C->getType()->isIntOrIntVectorTy() &&
2864 "Cannot NEG a nonintegral value!");
2865 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2866}
2867
2869 assert(C->getType()->isIntOrIntVectorTy() &&
2870 "Cannot NOT a nonintegral value!");
2871 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2872}
2873
2875 bool HasNUW, bool HasNSW) {
2876 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2878 return get(Instruction::Add, C1, C2, Flags);
2879}
2880
2882 bool HasNUW, bool HasNSW) {
2883 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2885 return get(Instruction::Sub, C1, C2, Flags);
2886}
2887
2889 return get(Instruction::Xor, C1, C2);
2890}
2891
2893 Type *Ty = C->getType();
2894 const APInt *IVal;
2895 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2896 return ConstantInt::get(Ty, IVal->logBase2());
2897
2898 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2899 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2900 if (!VecTy)
2901 return nullptr;
2902
2904 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2905 Constant *Elt = C->getAggregateElement(I);
2906 if (!Elt)
2907 return nullptr;
2908 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2909 if (isa<UndefValue>(Elt)) {
2910 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2911 continue;
2912 }
2913 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2914 return nullptr;
2915 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2916 }
2917
2918 return ConstantVector::get(Elts);
2919}
2920
2922 bool AllowRHSConstant, bool NSZ) {
2923 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2924
2925 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2926 if (Instruction::isCommutative(Opcode)) {
2927 switch (Opcode) {
2928 case Instruction::Add: // X + 0 = X
2929 case Instruction::Or: // X | 0 = X
2930 case Instruction::Xor: // X ^ 0 = X
2931 return Constant::getNullValue(Ty);
2932 case Instruction::Mul: // X * 1 = X
2933 return ConstantInt::get(Ty, 1);
2934 case Instruction::And: // X & -1 = X
2935 return Constant::getAllOnesValue(Ty);
2936 case Instruction::FAdd: // X + -0.0 = X
2937 return ConstantFP::getZero(Ty, !NSZ);
2938 case Instruction::FMul: // X * 1.0 = X
2939 return ConstantFP::get(Ty, 1.0);
2940 default:
2941 llvm_unreachable("Every commutative binop has an identity constant");
2942 }
2943 }
2944
2945 // Non-commutative opcodes: AllowRHSConstant must be set.
2946 if (!AllowRHSConstant)
2947 return nullptr;
2948
2949 switch (Opcode) {
2950 case Instruction::Sub: // X - 0 = X
2951 case Instruction::Shl: // X << 0 = X
2952 case Instruction::LShr: // X >>u 0 = X
2953 case Instruction::AShr: // X >> 0 = X
2954 case Instruction::FSub: // X - 0.0 = X
2955 return Constant::getNullValue(Ty);
2956 case Instruction::SDiv: // X / 1 = X
2957 case Instruction::UDiv: // X /u 1 = X
2958 return ConstantInt::get(Ty, 1);
2959 case Instruction::FDiv: // X / 1.0 = X
2960 return ConstantFP::get(Ty, 1.0);
2961 default:
2962 return nullptr;
2963 }
2964}
2965
2967 switch (ID) {
2968 case Intrinsic::umax:
2969 return Constant::getNullValue(Ty);
2970 case Intrinsic::umin:
2971 return Constant::getAllOnesValue(Ty);
2972 case Intrinsic::smax:
2974 Ty, APInt::getSignedMinValue(Ty->getScalarSizeInBits()));
2975 case Intrinsic::smin:
2977 Ty, APInt::getSignedMaxValue(Ty->getScalarSizeInBits()));
2978 default:
2979 return nullptr;
2980 }
2981}
2982
2984 bool AllowRHSConstant, bool NSZ) {
2985 if (I->isBinaryOp())
2986 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2988 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2989 return nullptr;
2990}
2991
2993 bool AllowLHSConstant) {
2994 switch (Opcode) {
2995 default:
2996 break;
2997
2998 case Instruction::Or: // -1 | X = -1
2999 return Constant::getAllOnesValue(Ty);
3000
3001 case Instruction::And: // 0 & X = 0
3002 case Instruction::Mul: // 0 * X = 0
3003 return Constant::getNullValue(Ty);
3004 }
3005
3006 // AllowLHSConstant must be set.
3007 if (!AllowLHSConstant)
3008 return nullptr;
3009
3010 switch (Opcode) {
3011 default:
3012 return nullptr;
3013 case Instruction::Shl: // 0 << X = 0
3014 case Instruction::LShr: // 0 >>l X = 0
3015 case Instruction::AShr: // 0 >>a X = 0
3016 case Instruction::SDiv: // 0 /s X = 0
3017 case Instruction::UDiv: // 0 /u X = 0
3018 case Instruction::URem: // 0 %u X = 0
3019 case Instruction::SRem: // 0 %s X = 0
3020 return Constant::getNullValue(Ty);
3021 }
3022}
3023
3024/// Remove the constant from the constant table.
3025void ConstantExpr::destroyConstantImpl() {
3026 getType()->getContext().pImpl->ExprConstants.remove(this);
3027}
3028
3029const char *ConstantExpr::getOpcodeName() const {
3031}
3032
3033GetElementPtrConstantExpr::GetElementPtrConstantExpr(
3034 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
3035 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
3036 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
3037 SrcElementTy(SrcElementTy),
3038 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
3039 InRange(std::move(InRange)) {
3040 Op<0>() = C;
3041 Use *OperandList = getOperandList();
3042 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
3043 OperandList[i+1] = IdxList[i];
3044}
3045
3047 return SrcElementTy;
3048}
3049
3051 return ResElementTy;
3052}
3053
3054std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
3055 return InRange;
3056}
3057
3058//===----------------------------------------------------------------------===//
3059// ConstantData* implementations
3060
3063 return ATy->getElementType();
3064 return cast<VectorType>(getType())->getElementType();
3065}
3066
3070
3072 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
3073 return true;
3074 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
3075 switch (IT->getBitWidth()) {
3076 case 8:
3077 case 16:
3078 case 32:
3079 case 64:
3080 return true;
3081 default: break;
3082 }
3083 }
3084 if (auto *IT = dyn_cast<ByteType>(Ty)) {
3085 switch (IT->getBitWidth()) {
3086 case 8:
3087 case 16:
3088 case 32:
3089 case 64:
3090 return true;
3091 default:
3092 break;
3093 }
3094 }
3095 return false;
3096}
3097
3100 return AT->getNumElements();
3101 return cast<FixedVectorType>(getType())->getNumElements();
3102}
3103
3107
3108/// Return the start of the specified element.
3109const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
3110 assert(Elt < getNumElements() && "Invalid Elt");
3111 return DataElements + Elt * getElementByteSize();
3112}
3113
3114/// Return true if the array is empty or all zeros.
3115static bool isAllZeros(StringRef Arr) {
3116 for (char I : Arr)
3117 if (I != 0)
3118 return false;
3119 return true;
3120}
3121
3122/// This is the underlying implementation of all of the
3123/// ConstantDataSequential::get methods. They all thunk down to here, providing
3124/// the correct element type. We take the bytes in as a StringRef because
3125/// we *want* an underlying "char*" to avoid TBAA type punning violations.
3127#ifndef NDEBUG
3128 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
3129 assert(isElementTypeCompatible(ATy->getElementType()));
3130 else
3132#endif
3133 // If the elements are all zero or there are no elements, return a CAZ, which
3134 // is more dense and canonical.
3135 if (isAllZeros(Elements))
3136 return ConstantAggregateZero::get(Ty);
3137
3138 // Do a lookup to see if we have already formed one of these.
3139 auto &Slot =
3140 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
3141
3142 // The bucket can point to a linked list of different CDS's that have the same
3143 // body but different types. For example, 0,0,0,1 could be a 4 element array
3144 // of i8, or a 1-element array of i32. They'll both end up in the same
3145 /// StringMap bucket, linked up by their Next pointers. Walk the list.
3146 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3147 for (; *Entry; Entry = &(*Entry)->Next)
3148 if ((*Entry)->getType() == Ty)
3149 return Entry->get();
3150
3151 // Okay, we didn't get a hit. Create a node of the right class, link it in,
3152 // and return it.
3153 if (isa<ArrayType>(Ty)) {
3154 // Use reset because std::make_unique can't access the constructor.
3155 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3156 return Entry->get();
3157 }
3158
3160 // Use reset because std::make_unique can't access the constructor.
3161 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3162 return Entry->get();
3163}
3164
3165void ConstantDataSequential::destroyConstantImpl() {
3166 // Remove the constant from the StringMap.
3169
3170 auto Slot = CDSConstants.find(getRawDataValues());
3171
3172 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3173
3174 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3175
3176 // Remove the entry from the hash table.
3177 if (!(*Entry)->Next) {
3178 // If there is only one value in the bucket (common case) it must be this
3179 // entry, and removing the entry should remove the bucket completely.
3180 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3181 getContext().pImpl->CDSConstants.erase(Slot);
3182 return;
3183 }
3184
3185 // Otherwise, there are multiple entries linked off the bucket, unlink the
3186 // node we care about but keep the bucket around.
3187 while (true) {
3188 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3189 assert(Node && "Didn't find entry in its uniquing hash table!");
3190 // If we found our entry, unlink it from the list and we're done.
3191 if (Node.get() == this) {
3192 Node = std::move(Node->Next);
3193 return;
3194 }
3195
3196 Entry = &Node->Next;
3197 }
3198}
3199
3200/// getFP() constructors - Return a constant of array type with a float
3201/// element type taken from argument `ElementType', and count taken from
3202/// argument `Elts'. The amount of bits of the contained type must match the
3203/// number of bits of the type contained in the passed in ArrayRef.
3204/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3205/// that this can return a ConstantAggregateZero object.
3207 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3208 "Element type is not a 16-bit float type");
3209 Type *Ty = ArrayType::get(ElementType, Elts.size());
3210 const char *Data = reinterpret_cast<const char *>(Elts.data());
3211 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3212}
3214 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3215 Type *Ty = ArrayType::get(ElementType, Elts.size());
3216 const char *Data = reinterpret_cast<const char *>(Elts.data());
3217 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3218}
3220 assert(ElementType->isDoubleTy() &&
3221 "Element type is not a 64-bit float type");
3222 Type *Ty = ArrayType::get(ElementType, Elts.size());
3223 const char *Data = reinterpret_cast<const char *>(Elts.data());
3224 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3225}
3226
3227/// getByte() constructors - Return a constant of array type with a byte
3228/// element type taken from argument `ElementType', and count taken from
3229/// argument `Elts'. The amount of bits of the contained type must match the
3230/// number of bits of the type contained in the passed in ArrayRef.
3231/// Note that this can return a ConstantAggregateZero object.
3233 ArrayRef<uint8_t> Elts) {
3234 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte type");
3235 Type *Ty = ArrayType::get(ElementType, Elts.size());
3236 const char *Data = reinterpret_cast<const char *>(Elts.data());
3237 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3238}
3240 ArrayRef<uint16_t> Elts) {
3241 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte type");
3242 Type *Ty = ArrayType::get(ElementType, Elts.size());
3243 const char *Data = reinterpret_cast<const char *>(Elts.data());
3244 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3245}
3247 ArrayRef<uint32_t> Elts) {
3248 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte type");
3249 Type *Ty = ArrayType::get(ElementType, Elts.size());
3250 const char *Data = reinterpret_cast<const char *>(Elts.data());
3251 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3252}
3254 ArrayRef<uint64_t> Elts) {
3255 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte type");
3256 Type *Ty = ArrayType::get(ElementType, Elts.size());
3257 const char *Data = reinterpret_cast<const char *>(Elts.data());
3258 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3259}
3260
3262 bool AddNull, bool ByteString) {
3263 if (!AddNull) {
3264 const uint8_t *Data = Str.bytes_begin();
3265 return ByteString
3266 ? getByte(Type::getByte8Ty(Context), ArrayRef(Data, Str.size()))
3267 : get(Context, ArrayRef(Data, Str.size()));
3268 }
3269
3270 SmallVector<uint8_t, 64> ElementVals;
3271 ElementVals.append(Str.begin(), Str.end());
3272 ElementVals.push_back(0);
3273 return ByteString ? getByte(Type::getByte8Ty(Context), ElementVals)
3274 : get(Context, ElementVals);
3275}
3276
3277/// get() constructors - Return a constant with vector type with an element
3278/// count and element type matching the ArrayRef passed in. Note that this
3279/// can return a ConstantAggregateZero object.
3281 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3282 const char *Data = reinterpret_cast<const char *>(Elts.data());
3283 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3284}
3286 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3287 const char *Data = reinterpret_cast<const char *>(Elts.data());
3288 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3289}
3291 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3292 const char *Data = reinterpret_cast<const char *>(Elts.data());
3293 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3294}
3296 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3297 const char *Data = reinterpret_cast<const char *>(Elts.data());
3298 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3299}
3301 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3302 const char *Data = reinterpret_cast<const char *>(Elts.data());
3303 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3304}
3306 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3307 const char *Data = reinterpret_cast<const char *>(Elts.data());
3308 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3309}
3310
3311/// getByte() constructors - Return a constant of vector type with a byte
3312/// element type taken from argument `ElementType', and count taken from
3313/// argument `Elts'. The amount of bits of the contained type must match the
3314/// number of bits of the type contained in the passed in ArrayRef.
3315/// Note that this can return a ConstantAggregateZero object.
3317 ArrayRef<uint8_t> Elts) {
3318 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte");
3319 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3320 const char *Data = reinterpret_cast<const char *>(Elts.data());
3321 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3322}
3324 ArrayRef<uint16_t> Elts) {
3325 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte");
3326 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3327 const char *Data = reinterpret_cast<const char *>(Elts.data());
3328 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3329}
3331 ArrayRef<uint32_t> Elts) {
3332 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte");
3333 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3334 const char *Data = reinterpret_cast<const char *>(Elts.data());
3335 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3336}
3338 ArrayRef<uint64_t> Elts) {
3339 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte");
3340 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3341 const char *Data = reinterpret_cast<const char *>(Elts.data());
3342 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3343}
3344
3345/// getFP() constructors - Return a constant of vector type with a float
3346/// element type taken from argument `ElementType', and count taken from
3347/// argument `Elts'. The amount of bits of the contained type must match the
3348/// number of bits of the type contained in the passed in ArrayRef.
3349/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3350/// that this can return a ConstantAggregateZero object.
3352 ArrayRef<uint16_t> Elts) {
3353 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3354 "Element type is not a 16-bit float type");
3355 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3356 const char *Data = reinterpret_cast<const char *>(Elts.data());
3357 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3358}
3360 ArrayRef<uint32_t> Elts) {
3361 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3362 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3363 const char *Data = reinterpret_cast<const char *>(Elts.data());
3364 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3365}
3367 ArrayRef<uint64_t> Elts) {
3368 assert(ElementType->isDoubleTy() &&
3369 "Element type is not a 64-bit float type");
3370 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3371 const char *Data = reinterpret_cast<const char *>(Elts.data());
3372 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3373}
3374
3376 assert(isElementTypeCompatible(V->getType()) &&
3377 "Element type not compatible with ConstantData");
3378 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3379 if (CI->getType()->isIntegerTy(8)) {
3380 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3381 return get(V->getContext(), Elts);
3382 }
3383 if (CI->getType()->isIntegerTy(16)) {
3384 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3385 return get(V->getContext(), Elts);
3386 }
3387 if (CI->getType()->isIntegerTy(32)) {
3388 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3389 return get(V->getContext(), Elts);
3390 }
3391 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3392 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3393 return get(V->getContext(), Elts);
3394 }
3395
3396 if (ConstantByte *CB = dyn_cast<ConstantByte>(V)) {
3397 if (CB->getType()->isByteTy(8)) {
3398 SmallVector<uint8_t, 16> Elts(NumElts, CB->getZExtValue());
3399 return getByte(V->getType(), Elts);
3400 }
3401 if (CB->getType()->isByteTy(16)) {
3402 SmallVector<uint16_t, 16> Elts(NumElts, CB->getZExtValue());
3403 return getByte(V->getType(), Elts);
3404 }
3405 if (CB->getType()->isByteTy(32)) {
3406 SmallVector<uint32_t, 16> Elts(NumElts, CB->getZExtValue());
3407 return getByte(V->getType(), Elts);
3408 }
3409 assert(CB->getType()->isByteTy(64) && "Unsupported ConstantData type");
3410 SmallVector<uint64_t, 16> Elts(NumElts, CB->getZExtValue());
3411 return getByte(V->getType(), Elts);
3412 }
3413
3414 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3415 if (CFP->getType()->isHalfTy()) {
3417 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3418 return getFP(V->getType(), Elts);
3419 }
3420 if (CFP->getType()->isBFloatTy()) {
3422 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3423 return getFP(V->getType(), Elts);
3424 }
3425 if (CFP->getType()->isFloatTy()) {
3427 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3428 return getFP(V->getType(), Elts);
3429 }
3430 if (CFP->getType()->isDoubleTy()) {
3432 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3433 return getFP(V->getType(), Elts);
3434 }
3435 }
3437}
3438
3440 assert(
3442 "Accessor can only be used when element is an integer or byte");
3443 const char *EltPtr = getElementPointer(Elt);
3444
3445 // The data is stored in host byte order, make sure to cast back to the right
3446 // type to load with the right endianness.
3447 switch (getElementByteSize()) {
3448 default: llvm_unreachable("Invalid bitwidth for CDS");
3449 case 1:
3450 return *reinterpret_cast<const uint8_t *>(EltPtr);
3451 case 2:
3452 return *reinterpret_cast<const uint16_t *>(EltPtr);
3453 case 4:
3454 return *reinterpret_cast<const uint32_t *>(EltPtr);
3455 case 8:
3456 return *reinterpret_cast<const uint64_t *>(EltPtr);
3457 }
3458}
3459
3461 assert(
3463 "Accessor can only be used when element is an integer or byte");
3464 const char *EltPtr = getElementPointer(Elt);
3465
3466 // The data is stored in host byte order, make sure to cast back to the right
3467 // type to load with the right endianness.
3468 switch (getElementByteSize()) {
3469 default: llvm_unreachable("Invalid bitwidth for CDS");
3470 case 1: {
3471 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3472 return APInt(8, EltVal);
3473 }
3474 case 2: {
3475 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3476 return APInt(16, EltVal);
3477 }
3478 case 4: {
3479 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3480 return APInt(32, EltVal);
3481 }
3482 case 8: {
3483 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3484 return APInt(64, EltVal);
3485 }
3486 }
3487}
3488
3490 const char *EltPtr = getElementPointer(Elt);
3491
3492 switch (getElementType()->getTypeID()) {
3493 default:
3494 llvm_unreachable("Accessor can only be used when element is float/double!");
3495 case Type::HalfTyID: {
3496 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3497 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3498 }
3499 case Type::BFloatTyID: {
3500 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3501 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3502 }
3503 case Type::FloatTyID: {
3504 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3505 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3506 }
3507 case Type::DoubleTyID: {
3508 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3509 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3510 }
3511 }
3512}
3513
3515 assert(getElementType()->isFloatTy() &&
3516 "Accessor can only be used when element is a 'float'");
3517 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3518}
3519
3521 assert(getElementType()->isDoubleTy() &&
3522 "Accessor can only be used when element is a 'float'");
3523 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3524}
3525
3527 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3528 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3529 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3530
3531 if (getElementType()->isByteTy())
3532 return ConstantByte::get(getElementType(), getElementAsInteger(Elt));
3533
3534 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3535}
3536
3537bool ConstantDataSequential::isString(unsigned CharSize) const {
3538 return isa<ArrayType>(getType()) &&
3539 (getElementType()->isIntegerTy(CharSize) ||
3540 getElementType()->isByteTy(CharSize));
3541}
3542
3544 if (!isString())
3545 return false;
3546
3547 StringRef Str = getAsString();
3548
3549 // The last value must be nul.
3550 if (Str.back() != 0) return false;
3551
3552 // Other elements must be non-nul.
3553 return !Str.drop_back().contains(0);
3554}
3555
3556bool ConstantDataVector::isSplatData() const {
3557 const char *Base = getRawDataValues().data();
3558
3559 // Compare elements 1+ to the 0'th element.
3560 unsigned EltSize = getElementByteSize();
3561 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3562 if (memcmp(Base, Base+i*EltSize, EltSize))
3563 return false;
3564
3565 return true;
3566}
3567
3569 if (!IsSplatSet) {
3570 IsSplatSet = true;
3571 IsSplat = isSplatData();
3572 }
3573 return IsSplat;
3574}
3575
3577 // If they're all the same, return the 0th one as a representative.
3578 return isSplat() ? getElementAsConstant(0) : nullptr;
3579}
3580
3581//===----------------------------------------------------------------------===//
3582// handleOperandChange implementations
3583
3584/// Update this constant array to change uses of
3585/// 'From' to be uses of 'To'. This must update the uniquing data structures
3586/// etc.
3587///
3588/// Note that we intentionally replace all uses of From with To here. Consider
3589/// a large array that uses 'From' 1000 times. By handling this case all here,
3590/// ConstantArray::handleOperandChange is only invoked once, and that
3591/// single invocation handles all 1000 uses. Handling them one at a time would
3592/// work, but would be really slow because it would have to unique each updated
3593/// array instance.
3594///
3596 Value *Replacement = nullptr;
3597 switch (getValueID()) {
3598 default:
3599 llvm_unreachable("Not a constant!");
3600#define HANDLE_CONSTANT(Name) \
3601 case Value::Name##Val: \
3602 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3603 break;
3604#include "llvm/IR/Value.def"
3605 }
3606
3607 // If handleOperandChangeImpl returned nullptr, then it handled
3608 // replacing itself and we don't want to delete or replace anything else here.
3609 if (!Replacement)
3610 return;
3611
3612 // I do need to replace this with an existing value.
3613 assert(Replacement != this && "I didn't contain From!");
3614
3615 // Everyone using this now uses the replacement.
3616 replaceAllUsesWith(Replacement);
3617
3618 // Delete the old constant!
3620}
3621
3622Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3623 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3624 Constant *ToC = cast<Constant>(To);
3625
3627 Values.reserve(getNumOperands()); // Build replacement array.
3628
3629 // Fill values with the modified operands of the constant array. Also,
3630 // compute whether this turns into an all-zeros array.
3631 unsigned NumUpdated = 0;
3632
3633 // Keep track of whether all the values in the array are "ToC".
3634 bool AllSame = true;
3635 Use *OperandList = getOperandList();
3636 unsigned OperandNo = 0;
3637 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3638 Constant *Val = cast<Constant>(O->get());
3639 if (Val == From) {
3640 OperandNo = (O - OperandList);
3641 Val = ToC;
3642 ++NumUpdated;
3643 }
3644 Values.push_back(Val);
3645 AllSame &= Val == ToC;
3646 }
3647
3648 if (AllSame && ToC->isNullValue())
3650
3651 if (AllSame && isa<UndefValue>(ToC))
3652 return UndefValue::get(getType());
3653
3654 // Check for any other type of constant-folding.
3655 if (Constant *C = getImpl(getType(), Values))
3656 return C;
3657
3658 // Update to the new value.
3660 Values, this, From, ToC, NumUpdated, OperandNo);
3661}
3662
3663Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3664 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3665 Constant *ToC = cast<Constant>(To);
3666
3667 Use *OperandList = getOperandList();
3668
3670 Values.reserve(getNumOperands()); // Build replacement struct.
3671
3672 // Fill values with the modified operands of the constant struct. Also,
3673 // compute whether this turns into an all-zeros struct.
3674 unsigned NumUpdated = 0;
3675 bool AllSame = true;
3676 unsigned OperandNo = 0;
3677 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3678 Constant *Val = cast<Constant>(O->get());
3679 if (Val == From) {
3680 OperandNo = (O - OperandList);
3681 Val = ToC;
3682 ++NumUpdated;
3683 }
3684 Values.push_back(Val);
3685 AllSame &= Val == ToC;
3686 }
3687
3688 if (AllSame && ToC->isNullValue())
3690
3691 if (AllSame && isa<UndefValue>(ToC))
3692 return UndefValue::get(getType());
3693
3694 // Update to the new value.
3696 Values, this, From, ToC, NumUpdated, OperandNo);
3697}
3698
3699Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3700 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3701 Constant *ToC = cast<Constant>(To);
3702
3704 Values.reserve(getNumOperands()); // Build replacement array...
3705 unsigned NumUpdated = 0;
3706 unsigned OperandNo = 0;
3707 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3708 Constant *Val = getOperand(i);
3709 if (Val == From) {
3710 OperandNo = i;
3711 ++NumUpdated;
3712 Val = ToC;
3713 }
3714 Values.push_back(Val);
3715 }
3716
3717 if (Constant *C = getImpl(Values))
3718 return C;
3719
3720 // Update to the new value.
3722 Values, this, From, ToC, NumUpdated, OperandNo);
3723}
3724
3725Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3726 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3727 Constant *To = cast<Constant>(ToV);
3728
3730 unsigned NumUpdated = 0;
3731 unsigned OperandNo = 0;
3732 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3733 Constant *Op = getOperand(i);
3734 if (Op == From) {
3735 OperandNo = i;
3736 ++NumUpdated;
3737 Op = To;
3738 }
3739 NewOps.push_back(Op);
3740 }
3741 assert(NumUpdated && "I didn't contain From!");
3742
3743 if (Constant *C = getWithOperands(NewOps, getType(), true))
3744 return C;
3745
3746 // Update to the new value.
3747 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3748 NewOps, this, From, To, NumUpdated, OperandNo);
3749}
3750
3752 SmallVector<Value *, 4> ValueOperands(operands());
3753 ArrayRef<Value*> Ops(ValueOperands);
3754
3755 switch (getOpcode()) {
3756 case Instruction::Trunc:
3757 case Instruction::PtrToAddr:
3758 case Instruction::PtrToInt:
3759 case Instruction::IntToPtr:
3760 case Instruction::BitCast:
3761 case Instruction::AddrSpaceCast:
3763 getType(), "");
3764 case Instruction::InsertElement:
3765 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3766 case Instruction::ExtractElement:
3767 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3768 case Instruction::ShuffleVector:
3769 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3770
3771 case Instruction::GetElementPtr: {
3772 const auto *GO = cast<GEPOperator>(this);
3773 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3774 Ops.slice(1), GO->getNoWrapFlags(), "");
3775 }
3776 default:
3777 assert(getNumOperands() == 2 && "Must be binary operator?");
3779 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3785 }
3788 return BO;
3789 }
3790}
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 Constant * getByteSequenceIfElementsMatch(ArrayRef< Constant * > V)
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 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...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSigned(unsigned 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:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
#define T
uint64_t IntrinsicInst * II
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
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:304
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:326
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:307
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1232
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6034
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6060
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
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:230
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned logBase2() const
Definition APInt.h:1781
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
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:672
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:1088
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Class to represent byte types.
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
Definition Type.cpp:368
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:514
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:565
LLVM_ABI ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V, AllocInfo AllocInfo)
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:592
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:609
Class for constant bytes.
Definition Constants.h:281
friend class Constant
Definition Constants.h:282
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
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:878
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 ...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of array type with a byte 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:831
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 or bytes.
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:951
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...
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of vector type with a byte element type taken from argumen...
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:1316
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:1324
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:1317
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:1318
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1513
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:1614
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:1554
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:1474
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:1572
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:420
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
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 ConstantFP * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
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 ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
A constant pointer value that points to null.
Definition Constants.h:716
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
A signed pointer, in the ptrauth sense.
Definition Constants.h:1223
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1264
friend struct ConstantPtrAuthKeyType
Definition Constants.h:1224
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, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
friend class Constant
Definition Constants.h:1225
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:1254
Constant * getDeactivationSymbol() const
Definition Constants.h:1273
bool hasAddressDiscriminator() const
Whether there is any non-null address discriminator.
Definition Constants.h:1269
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1257
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:624
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:661
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:1076
A constant token which is empty.
Definition Constants.h:1035
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:674
friend class Constant
Definition Constants.h:676
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:697
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.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
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.
Definition Constants.cpp:89
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:50
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
Constant(Type *ty, ValueTy vty, AllocInfo AllocInfo)
Definition Constant.h:54
LLVM_ABI bool containsMatchingVectorElement(function_ref< bool(Constant *)> PredFn) const
Return true if this is a vector constant where at least one element satisfies the given predicate.
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 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 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:1143
GlobalValue * getGlobalValue() const
Definition Constants.h:1164
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:64
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
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:843
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:338
A wrapper class for inspecting calls to intrinsic functions.
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< Type *, std::unique_ptr< ConstantPointerNull > > CPNConstants
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
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
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteOneConstants
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteZeroConstants
DenseMap< APInt, std::unique_ptr< ConstantByte > > ByteConstants
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:1182
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:1206
GlobalValue * getGlobalValue() const
Definition Constants.h:1201
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1695
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
friend class Constant
Definition Constants.h:1696
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:340
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 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:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
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:467
Class to represent target extensions types, which are generally unintrospectable from target-independ...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ TargetExtTyID
Target extension type.
Definition Type.h:80
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ TokenTyID
Tokens.
Definition Type.h:68
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:115
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:298
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI ByteType * getByte8Ty(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:277
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:276
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
'undef' values are things that do not have specified contents.
Definition Constants.h:1647
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:1648
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:200
op_range operands()
Definition User.h:267
User(Type *ty, unsigned vty, AllocInfo AllocInfo)
Definition User.h:119
op_iterator op_begin()
Definition User.h:259
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator_impl< const User > const_user_iterator
Definition Value.h:394
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
unsigned char SubclassOptionalData
Hold arbitary subclass data.
Definition Value.h:85
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:724
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
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:712
bool use_empty() const
Definition Value.h:348
user_iterator user_end()
Definition Value.h:412
iterator_range< use_iterator > uses()
Definition Value.h:382
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
ValueTy
Concrete subclass of this.
Definition Value.h:526
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
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
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
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.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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:244
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)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
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:209
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.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
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:1933
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:249
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.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
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:878
#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