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