LLVM 19.0.0git
Constants.cpp
Go to the documentation of this file.
1//===-- Constants.cpp - Implement Constant nodes --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Constant* classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Constants.h"
14#include "LLVMContextImpl.h"
15#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/GlobalIFunc.h"
25#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Operator.h"
33#include <algorithm>
34
35using namespace llvm;
36using namespace PatternMatch;
37
38// As set of temporary options to help migrate how splats are represented.
40 "use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden,
41 cl::desc("Use ConstantInt's native fixed-length vector splat support."));
43 "use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantFP's native fixed-length vector splat support."));
46 "use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,
47 cl::desc("Use ConstantInt's native scalable vector splat support."));
49 "use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden,
50 cl::desc("Use ConstantFP's native scalable vector splat support."));
51
52//===----------------------------------------------------------------------===//
53// Constant Class
54//===----------------------------------------------------------------------===//
55
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && CFP->isNegative();
60
61 // Equivalent for a vector of -0.0's.
62 if (getType()->isVectorTy())
63 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
64 return SplatCFP->isNegativeZeroValue();
65
66 // We've already handled true FP case; any other FP vectors can't represent -0.0.
67 if (getType()->isFPOrFPVectorTy())
68 return false;
69
70 // Otherwise, just use +0.0.
71 return isNullValue();
72}
73
74// Return true iff this constant is positive zero (floating point), negative
75// zero (floating point), or a null value.
77 // Floating point values have an explicit -0.0 value.
78 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
79 return CFP->isZero();
80
81 // Check for constant splat vectors of 1 values.
82 if (getType()->isVectorTy())
83 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
84 return SplatCFP->isZero();
85
86 // Otherwise, just use +0.0.
87 return isNullValue();
88}
89
91 // 0 is null.
92 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
93 return CI->isZero();
94
95 // +0.0 is null.
96 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
97 // ppc_fp128 determine isZero using high order double only
98 // Should check the bitwise value to make sure all bits are zero.
99 return CFP->isExactlyValue(+0.0);
100
101 // constant zero is zero for aggregates, cpnull is null for pointers, none for
102 // tokens.
103 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
104 isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);
105}
106
108 // Check for -1 integers
109 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
110 return CI->isMinusOne();
111
112 // Check for FP which are bitcasted from -1 integers
113 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
114 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
115
116 // Check for constant splat vectors of 1 values.
117 if (getType()->isVectorTy())
118 if (const auto *SplatVal = getSplatValue())
119 return SplatVal->isAllOnesValue();
120
121 return false;
122}
123
125 // Check for 1 integers
126 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
127 return CI->isOne();
128
129 // Check for FP which are bitcasted from 1 integers
130 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
131 return CFP->getValueAPF().bitcastToAPInt().isOne();
132
133 // Check for constant splat vectors of 1 values.
134 if (getType()->isVectorTy())
135 if (const auto *SplatVal = getSplatValue())
136 return SplatVal->isOneValue();
137
138 return false;
139}
140
142 // Check for 1 integers
143 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
144 return !CI->isOneValue();
145
146 // Check for FP which are bitcasted from 1 integers
147 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
148 return !CFP->getValueAPF().bitcastToAPInt().isOne();
149
150 // Check that vectors don't contain 1
151 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
152 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
154 if (!Elt || !Elt->isNotOneValue())
155 return false;
156 }
157 return true;
158 }
159
160 // Check for splats that don't contain 1
161 if (getType()->isVectorTy())
162 if (const auto *SplatVal = getSplatValue())
163 return SplatVal->isNotOneValue();
164
165 // It *may* contain 1, we can't tell.
166 return false;
167}
168
170 // Check for INT_MIN integers
171 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
172 return CI->isMinValue(/*isSigned=*/true);
173
174 // Check for FP which are bitcasted from INT_MIN integers
175 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
176 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
177
178 // Check for splats of INT_MIN values.
179 if (getType()->isVectorTy())
180 if (const auto *SplatVal = getSplatValue())
181 return SplatVal->isMinSignedValue();
182
183 return false;
184}
185
187 // Check for INT_MIN integers
188 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
189 return !CI->isMinValue(/*isSigned=*/true);
190
191 // Check for FP which are bitcasted from INT_MIN integers
192 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
193 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
194
195 // Check that vectors don't contain INT_MIN
196 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
197 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
199 if (!Elt || !Elt->isNotMinSignedValue())
200 return false;
201 }
202 return true;
203 }
204
205 // Check for splats that aren't INT_MIN
206 if (getType()->isVectorTy())
207 if (const auto *SplatVal = getSplatValue())
208 return SplatVal->isNotMinSignedValue();
209
210 // It *may* contain INT_MIN, we can't tell.
211 return false;
212}
213
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isFiniteNonZero();
217
218 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
219 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
221 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
222 return false;
223 }
224 return true;
225 }
226
227 if (getType()->isVectorTy())
228 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
229 return SplatCFP->isFiniteNonZeroFP();
230
231 // It *may* contain finite non-zero, we can't tell.
232 return false;
233}
234
236 if (auto *CFP = dyn_cast<ConstantFP>(this))
237 return CFP->getValueAPF().isNormal();
238
239 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
240 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
241 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
242 if (!CFP || !CFP->getValueAPF().isNormal())
243 return false;
244 }
245 return true;
246 }
247
248 if (getType()->isVectorTy())
249 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
250 return SplatCFP->isNormalFP();
251
252 // It *may* contain a normal fp value, we can't tell.
253 return false;
254}
255
257 if (auto *CFP = dyn_cast<ConstantFP>(this))
258 return CFP->getValueAPF().getExactInverse(nullptr);
259
260 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
261 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
262 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
263 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
264 return false;
265 }
266 return true;
267 }
268
269 if (getType()->isVectorTy())
270 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
271 return SplatCFP->hasExactInverseFP();
272
273 // It *may* have an exact inverse fp value, we can't tell.
274 return false;
275}
276
277bool Constant::isNaN() const {
278 if (auto *CFP = dyn_cast<ConstantFP>(this))
279 return CFP->isNaN();
280
281 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
282 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
283 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
284 if (!CFP || !CFP->isNaN())
285 return false;
286 }
287 return true;
288 }
289
290 if (getType()->isVectorTy())
291 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
292 return SplatCFP->isNaN();
293
294 // It *may* be NaN, we can't tell.
295 return false;
296}
297
299 // Are they fully identical?
300 if (this == Y)
301 return true;
302
303 // The input value must be a vector constant with the same type.
304 auto *VTy = dyn_cast<VectorType>(getType());
305 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
306 return false;
307
308 // TODO: Compare pointer constants?
309 if (!(VTy->getElementType()->isIntegerTy() ||
310 VTy->getElementType()->isFloatingPointTy()))
311 return false;
312
313 // They may still be identical element-wise (if they have `undef`s).
314 // Bitcast to integer to allow exact bitwise comparison for all types.
315 Type *IntTy = VectorType::getInteger(VTy);
316 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
317 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
319 return 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
1759//---- ConstantPointerNull::get() implementation.
1760//
1761
1763 std::unique_ptr<ConstantPointerNull> &Entry =
1764 Ty->getContext().pImpl->CPNConstants[Ty];
1765 if (!Entry)
1766 Entry.reset(new ConstantPointerNull(Ty));
1767
1768 return Entry.get();
1769}
1770
1771/// Remove the constant from the constant table.
1772void ConstantPointerNull::destroyConstantImpl() {
1774}
1775
1776//---- ConstantTargetNone::get() implementation.
1777//
1778
1781 "Target extension type not allowed to have a zeroinitializer");
1782 std::unique_ptr<ConstantTargetNone> &Entry =
1783 Ty->getContext().pImpl->CTNConstants[Ty];
1784 if (!Entry)
1785 Entry.reset(new ConstantTargetNone(Ty));
1786
1787 return Entry.get();
1788}
1789
1790/// Remove the constant from the constant table.
1791void ConstantTargetNone::destroyConstantImpl() {
1793}
1794
1796 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1797 if (!Entry)
1798 Entry.reset(new UndefValue(Ty));
1799
1800 return Entry.get();
1801}
1802
1803/// Remove the constant from the constant table.
1804void UndefValue::destroyConstantImpl() {
1805 // Free the constant and any dangling references to it.
1806 if (getValueID() == UndefValueVal) {
1807 getContext().pImpl->UVConstants.erase(getType());
1808 } else if (getValueID() == PoisonValueVal) {
1809 getContext().pImpl->PVConstants.erase(getType());
1810 }
1811 llvm_unreachable("Not a undef or a poison!");
1812}
1813
1815 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1816 if (!Entry)
1817 Entry.reset(new PoisonValue(Ty));
1818
1819 return Entry.get();
1820}
1821
1822/// Remove the constant from the constant table.
1823void PoisonValue::destroyConstantImpl() {
1824 // Free the constant and any dangling references to it.
1825 getContext().pImpl->PVConstants.erase(getType());
1826}
1827
1829 assert(BB->getParent() && "Block must have a parent");
1830 return get(BB->getParent(), BB);
1831}
1832
1834 BlockAddress *&BA =
1835 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1836 if (!BA)
1837 BA = new BlockAddress(F, BB);
1838
1839 assert(BA->getFunction() == F && "Basic block moved between functions");
1840 return BA;
1841}
1842
1843BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1844 : Constant(PointerType::get(F->getContext(), F->getAddressSpace()),
1845 Value::BlockAddressVal, &Op<0>(), 2) {
1846 setOperand(0, F);
1847 setOperand(1, BB);
1848 BB->AdjustBlockAddressRefCount(1);
1849}
1850
1852 if (!BB->hasAddressTaken())
1853 return nullptr;
1854
1855 const Function *F = BB->getParent();
1856 assert(F && "Block must have a parent");
1857 BlockAddress *BA =
1858 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1859 assert(BA && "Refcount and block address map disagree!");
1860 return BA;
1861}
1862
1863/// Remove the constant from the constant table.
1864void BlockAddress::destroyConstantImpl() {
1866 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1867 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1868}
1869
1870Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1871 // This could be replacing either the Basic Block or the Function. In either
1872 // case, we have to remove the map entry.
1873 Function *NewF = getFunction();
1874 BasicBlock *NewBB = getBasicBlock();
1875
1876 if (From == NewF)
1877 NewF = cast<Function>(To->stripPointerCasts());
1878 else {
1879 assert(From == NewBB && "From does not match any operand");
1880 NewBB = cast<BasicBlock>(To);
1881 }
1882
1883 // See if the 'new' entry already exists, if not, just update this in place
1884 // and return early.
1885 BlockAddress *&NewBA =
1886 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1887 if (NewBA)
1888 return NewBA;
1889
1890 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1891
1892 // Remove the old entry, this can't cause the map to rehash (just a
1893 // tombstone will get added).
1894 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1895 getBasicBlock()));
1896 NewBA = this;
1897 setOperand(0, NewF);
1898 setOperand(1, NewBB);
1899 getBasicBlock()->AdjustBlockAddressRefCount(1);
1900
1901 // If we just want to keep the existing value, then return null.
1902 // Callers know that this means we shouldn't delete this value.
1903 return nullptr;
1904}
1905
1908 if (!Equiv)
1909 Equiv = new DSOLocalEquivalent(GV);
1910
1911 assert(Equiv->getGlobalValue() == GV &&
1912 "DSOLocalFunction does not match the expected global value");
1913 return Equiv;
1914}
1915
1916DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1917 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
1918 setOperand(0, GV);
1919}
1920
1921/// Remove the constant from the constant table.
1922void DSOLocalEquivalent::destroyConstantImpl() {
1923 const GlobalValue *GV = getGlobalValue();
1924 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1925}
1926
1927Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1928 assert(From == getGlobalValue() && "Changing value does not match operand.");
1929 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1930
1931 // The replacement is with another global value.
1932 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1933 DSOLocalEquivalent *&NewEquiv =
1935 if (NewEquiv)
1936 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1937 }
1938
1939 // If the argument is replaced with a null value, just replace this constant
1940 // with a null value.
1941 if (cast<Constant>(To)->isNullValue())
1942 return To;
1943
1944 // The replacement could be a bitcast or an alias to another function. We can
1945 // replace it with a bitcast to the dso_local_equivalent of that function.
1946 auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
1948 if (NewEquiv)
1949 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1950
1951 // Replace this with the new one.
1953 NewEquiv = this;
1954 setOperand(0, Func);
1955
1956 if (Func->getType() != getType()) {
1957 // It is ok to mutate the type here because this constant should always
1958 // reflect the type of the function it's holding.
1959 mutateType(Func->getType());
1960 }
1961 return nullptr;
1962}
1963
1965 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1966 if (!NC)
1967 NC = new NoCFIValue(GV);
1968
1969 assert(NC->getGlobalValue() == GV &&
1970 "NoCFIValue does not match the expected global value");
1971 return NC;
1972}
1973
1974NoCFIValue::NoCFIValue(GlobalValue *GV)
1975 : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1976 setOperand(0, GV);
1977}
1978
1979/// Remove the constant from the constant table.
1980void NoCFIValue::destroyConstantImpl() {
1981 const GlobalValue *GV = getGlobalValue();
1982 GV->getContext().pImpl->NoCFIValues.erase(GV);
1983}
1984
1985Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1986 assert(From == getGlobalValue() && "Changing value does not match operand.");
1987
1988 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
1989 assert(GV && "Can only replace the operands with a global value");
1990
1991 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
1992 if (NewNC)
1993 return llvm::ConstantExpr::getBitCast(NewNC, getType());
1994
1996 NewNC = this;
1997 setOperand(0, GV);
1998
1999 if (GV->getType() != getType())
2000 mutateType(GV->getType());
2001
2002 return nullptr;
2003}
2004
2005//---- ConstantPtrAuth::get() implementations.
2006//
2007
2009 ConstantInt *Disc, Constant *AddrDisc) {
2010 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc};
2011 ConstantPtrAuthKeyType MapKey(ArgVec);
2012 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2013 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2014}
2015
2017 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator());
2018}
2019
2020ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2021 ConstantInt *Disc, Constant *AddrDisc)
2022 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, &Op<0>(), 4) {
2023 assert(Ptr->getType()->isPointerTy());
2024 assert(Key->getBitWidth() == 32);
2025 assert(Disc->getBitWidth() == 64);
2026 assert(AddrDisc->getType()->isPointerTy());
2027 setOperand(0, Ptr);
2028 setOperand(1, Key);
2029 setOperand(2, Disc);
2030 setOperand(3, AddrDisc);
2031}
2032
2033/// Remove the constant from the constant table.
2034void ConstantPtrAuth::destroyConstantImpl() {
2035 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2036}
2037
2038Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2039 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2040 Constant *To = cast<Constant>(ToV);
2041
2043 Values.reserve(getNumOperands());
2044
2045 unsigned NumUpdated = 0;
2046
2047 Use *OperandList = getOperandList();
2048 unsigned OperandNo = 0;
2049 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2050 Constant *Val = cast<Constant>(O->get());
2051 if (Val == From) {
2052 OperandNo = (O - OperandList);
2053 Val = To;
2054 ++NumUpdated;
2055 }
2056 Values.push_back(Val);
2057 }
2058
2059 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2060 Values, this, From, To, NumUpdated, OperandNo);
2061}
2062
2064 const Value *Discriminator,
2065 const DataLayout &DL) const {
2066 // If the keys are different, there's no chance for this to be compatible.
2067 if (getKey() != Key)
2068 return false;
2069
2070 // We can have 3 kinds of discriminators:
2071 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2072 // - address-only: `i64 0, ptr p` vs. `ptr p`
2073 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2074
2075 // If this constant has a simple discriminator (integer, no address), easy:
2076 // it's compatible iff the provided full discriminator is also a simple
2077 // discriminator, identical to our integer discriminator.
2079 return getDiscriminator() == Discriminator;
2080
2081 // Otherwise, we can isolate address and integer discriminator components.
2082 const Value *AddrDiscriminator = nullptr;
2083
2084 // This constant may or may not have an integer discriminator (instead of 0).
2085 if (!getDiscriminator()->isNullValue()) {
2086 // If it does, there's an implicit blend. We need to have a matching blend
2087 // intrinsic in the provided full discriminator.
2088 if (!match(Discriminator,
2089 m_Intrinsic<Intrinsic::ptrauth_blend>(
2090 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2091 return false;
2092 } else {
2093 // Otherwise, interpret the provided full discriminator as address-only.
2094 AddrDiscriminator = Discriminator;
2095 }
2096
2097 // Either way, we can now focus on comparing the address discriminators.
2098
2099 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2100 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2101 AddrDiscriminator = Cast->getPointerOperand();
2102
2103 // Beyond that, we're only interested in compatible pointers.
2104 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2105 return false;
2106
2107 // These are often the same constant GEP, making them trivially equivalent.
2108 if (getAddrDiscriminator() == AddrDiscriminator)
2109 return true;
2110
2111 // Finally, they may be equivalent base+offset expressions.
2112 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2114 DL, Off1, /*AllowNonInbounds=*/true);
2115
2116 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2117 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2118 DL, Off2, /*AllowNonInbounds=*/true);
2119
2120 return Base1 == Base2 && Off1 == Off2;
2121}
2122
2123//---- ConstantExpr::get() implementations.
2124//
2125
2126/// This is a utility function to handle folding of casts and lookup of the
2127/// cast in the ExprConstants map. It is used by the various get* methods below.
2129 bool OnlyIfReduced = false) {
2130 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2131 // Fold a few common cases
2132 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2133 return FC;
2134
2135 if (OnlyIfReduced)
2136 return nullptr;
2137
2138 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2139
2140 // Look up the constant in the table first to ensure uniqueness.
2141 ConstantExprKeyType Key(opc, C);
2142
2143 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2144}
2145
2147 bool OnlyIfReduced) {
2149 assert(Instruction::isCast(opc) && "opcode out of range");
2151 "Cast opcode not supported as constant expression");
2152 assert(C && Ty && "Null arguments to getCast");
2153 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2154
2155 switch (opc) {
2156 default:
2157 llvm_unreachable("Invalid cast opcode");
2158 case Instruction::Trunc:
2159 return getTrunc(C, Ty, OnlyIfReduced);
2160 case Instruction::PtrToInt:
2161 return getPtrToInt(C, Ty, OnlyIfReduced);
2162 case Instruction::IntToPtr:
2163 return getIntToPtr(C, Ty, OnlyIfReduced);
2164 case Instruction::BitCast:
2165 return getBitCast(C, Ty, OnlyIfReduced);
2166 case Instruction::AddrSpaceCast:
2167 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2168 }
2169}
2170
2172 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2173 return getBitCast(C, Ty);
2174 return getTrunc(C, Ty);
2175}
2176
2178 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2179 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2180 "Invalid cast");
2181
2182 if (Ty->isIntOrIntVectorTy())
2183 return getPtrToInt(S, Ty);
2184
2185 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2186 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2187 return getAddrSpaceCast(S, Ty);
2188
2189 return getBitCast(S, Ty);
2190}
2191
2193 Type *Ty) {
2194 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2195 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2196
2198 return getAddrSpaceCast(S, Ty);
2199
2200 return getBitCast(S, Ty);
2201}
2202
2203Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2204#ifndef NDEBUG
2205 bool fromVec = isa<VectorType>(C->getType());
2206 bool toVec = isa<VectorType>(Ty);
2207#endif
2208 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2209 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2210 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2211 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2212 "SrcTy must be larger than DestTy for Trunc!");
2213
2214 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2215}
2216
2218 bool OnlyIfReduced) {
2219 assert(C->getType()->isPtrOrPtrVectorTy() &&
2220 "PtrToInt source must be pointer or pointer vector");
2221 assert(DstTy->isIntOrIntVectorTy() &&
2222 "PtrToInt destination must be integer or integer vector");
2223 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2224 if (isa<VectorType>(C->getType()))
2225 assert(cast<VectorType>(C->getType())->getElementCount() ==
2226 cast<VectorType>(DstTy)->getElementCount() &&
2227 "Invalid cast between a different number of vector elements");
2228 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2229}
2230
2232 bool OnlyIfReduced) {
2233 assert(C->getType()->isIntOrIntVectorTy() &&
2234 "IntToPtr source must be integer or integer vector");
2235 assert(DstTy->isPtrOrPtrVectorTy() &&
2236 "IntToPtr destination must be a pointer or pointer vector");
2237 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2238 if (isa<VectorType>(C->getType()))
2239 assert(cast<VectorType>(C->getType())->getElementCount() ==
2240 cast<VectorType>(DstTy)->getElementCount() &&
2241 "Invalid cast between a different number of vector elements");
2242 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2243}
2244
2246 bool OnlyIfReduced) {
2247 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2248 "Invalid constantexpr bitcast!");
2249
2250 // It is common to ask for a bitcast of a value to its own type, handle this
2251 // speedily.
2252 if (C->getType() == DstTy) return C;
2253
2254 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2255}
2256
2258 bool OnlyIfReduced) {
2259 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2260 "Invalid constantexpr addrspacecast!");
2261 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2262}
2263
2264Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2265 unsigned Flags, Type *OnlyIfReducedTy) {
2266 // Check the operands for consistency first.
2268 "Invalid opcode in binary constant expression");
2269 assert(isSupportedBinOp(Opcode) &&
2270 "Binop not supported as constant expression");
2271 assert(C1->getType() == C2->getType() &&
2272 "Operand types in binary constant expression should match");
2273
2274#ifndef NDEBUG
2275 switch (Opcode) {
2276 case Instruction::Add:
2277 case Instruction::Sub:
2278 case Instruction::Mul:
2280 "Tried to create an integer operation on a non-integer type!");
2281 break;
2282 case Instruction::And:
2283 case Instruction::Or:
2284 case Instruction::Xor:
2286 "Tried to create a logical operation on a non-integral type!");
2287 break;
2288 default:
2289 break;
2290 }
2291#endif
2292
2293 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2294 return FC;
2295
2296 if (OnlyIfReducedTy == C1->getType())
2297 return nullptr;
2298
2299 Constant *ArgVec[] = {C1, C2};
2300 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2301
2302 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2303 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2304}
2305
2306bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2307 switch (Opcode) {
2308 case Instruction::UDiv:
2309 case Instruction::SDiv:
2310 case Instruction::URem:
2311 case Instruction::SRem:
2312 case Instruction::FAdd:
2313 case Instruction::FSub:
2314 case Instruction::FMul:
2315 case Instruction::FDiv:
2316 case Instruction::FRem:
2317 case Instruction::And:
2318 case Instruction::Or:
2319 case Instruction::LShr:
2320 case Instruction::AShr:
2321 case Instruction::Shl:
2322 return false;
2323 case Instruction::Add:
2324 case Instruction::Sub:
2325 case Instruction::Mul:
2326 case Instruction::Xor:
2327 return true;
2328 default:
2329 llvm_unreachable("Argument must be binop opcode");
2330 }
2331}
2332
2333bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2334 switch (Opcode) {
2335 case Instruction::UDiv:
2336 case Instruction::SDiv:
2337 case Instruction::URem:
2338 case Instruction::SRem:
2339 case Instruction::FAdd:
2340 case Instruction::FSub:
2341 case Instruction::FMul:
2342 case Instruction::FDiv:
2343 case Instruction::FRem:
2344 case Instruction::And:
2345 case Instruction::Or:
2346 case Instruction::LShr:
2347 case Instruction::AShr:
2348 case Instruction::Shl:
2349 return false;
2350 case Instruction::Add:
2351 case Instruction::Sub:
2352 case Instruction::Mul:
2353 case Instruction::Xor:
2354 return true;
2355 default:
2356 llvm_unreachable("Argument must be binop opcode");
2357 }
2358}
2359
2360bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2361 switch (Opcode) {
2362 case Instruction::ZExt:
2363 case Instruction::SExt:
2364 case Instruction::FPTrunc:
2365 case Instruction::FPExt:
2366 case Instruction::UIToFP:
2367 case Instruction::SIToFP:
2368 case Instruction::FPToUI:
2369 case Instruction::FPToSI:
2370 return false;
2371 case Instruction::Trunc:
2372 case Instruction::PtrToInt:
2373 case Instruction::IntToPtr:
2374 case Instruction::BitCast:
2375 case Instruction::AddrSpaceCast:
2376 return true;
2377 default:
2378 llvm_unreachable("Argument must be cast opcode");
2379 }
2380}
2381
2382bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2383 switch (Opcode) {
2384 case Instruction::ZExt:
2385 case Instruction::SExt:
2386 case Instruction::FPTrunc:
2387 case Instruction::FPExt:
2388 case Instruction::UIToFP:
2389 case Instruction::SIToFP:
2390 case Instruction::FPToUI:
2391 case Instruction::FPToSI:
2392 return false;
2393 case Instruction::Trunc:
2394 case Instruction::PtrToInt:
2395 case Instruction::IntToPtr:
2396 case Instruction::BitCast:
2397 case Instruction::AddrSpaceCast:
2398 return true;
2399 default:
2400 llvm_unreachable("Argument must be cast opcode");
2401 }
2402}
2403
2405 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2406 // Note that a non-inbounds gep is used, as null isn't within any object.
2407 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2410 return getPtrToInt(GEP,
2412}
2413
2415 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2416 // Note that a non-inbounds gep is used, as null isn't within any object.
2417 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2418 Constant *NullPtr =
2420 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2421 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2422 Constant *Indices[2] = {Zero, One};
2423 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2425}
2426
2428 ArrayRef<Value *> Idxs,
2429 GEPNoWrapFlags NW,
2430 std::optional<ConstantRange> InRange,
2431 Type *OnlyIfReducedTy) {
2432 assert(Ty && "Must specify element type");
2433 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2434
2435 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2436 return FC; // Fold a few common cases.
2437
2438 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2439 ;
2440
2441 // Get the result type of the getelementptr!
2443 if (OnlyIfReducedTy == ReqTy)
2444 return nullptr;
2445
2446 auto EltCount = ElementCount::getFixed(0);
2447 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2448 EltCount = VecTy->getElementCount();
2449
2450 // Look up the constant in the table first to ensure uniqueness
2451 std::vector<Constant*> ArgVec;
2452 ArgVec.reserve(1 + Idxs.size());
2453 ArgVec.push_back(C);
2454 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2455 for (; GTI != GTE; ++GTI) {
2456 auto *Idx = cast<Constant>(GTI.getOperand());
2457 assert(
2458 (!isa<VectorType>(Idx->getType()) ||
2459 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2460 "getelementptr index type missmatch");
2461
2462 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2463 Idx = Idx->getSplatValue();
2464 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2465 !Idx->getType()->isVectorTy()) {
2466 Idx = ConstantVector::getSplat(EltCount, Idx);
2467 }
2468 ArgVec.push_back(Idx);
2469 }
2470
2471 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2472 std::nullopt, Ty, InRange);
2473
2474 LLVMContextImpl *pImpl = C->getContext().pImpl;
2475 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2476}
2477
2479 Type *OnlyIfReducedTy) {
2480 assert(Val->getType()->isVectorTy() &&
2481 "Tried to create extractelement operation on non-vector type!");
2482 assert(Idx->getType()->isIntegerTy() &&
2483 "Extractelement index must be an integer type!");
2484
2486 return FC; // Fold a few common cases.
2487
2488 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2489 if (OnlyIfReducedTy == ReqTy)
2490 return nullptr;
2491
2492 // Look up the constant in the table first to ensure uniqueness
2493 Constant *ArgVec[] = { Val, Idx };
2494 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2495
2496 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2497 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2498}
2499
2501 Constant *Idx, Type *OnlyIfReducedTy) {
2502 assert(Val->getType()->isVectorTy() &&
2503 "Tried to create insertelement operation on non-vector type!");
2504 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2505 "Insertelement types must match!");
2506 assert(Idx->getType()->isIntegerTy() &&
2507 "Insertelement index must be i32 type!");
2508
2510 return FC; // Fold a few common cases.
2511
2512 if (OnlyIfReducedTy == Val->getType())
2513 return nullptr;
2514
2515 // Look up the constant in the table first to ensure uniqueness
2516 Constant *ArgVec[] = { Val, Elt, Idx };
2517 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2518
2519 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2520 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2521}
2522
2524 ArrayRef<int> Mask,
2525 Type *OnlyIfReducedTy) {
2527 "Invalid shuffle vector constant expr operands!");
2528
2529 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2530 return FC; // Fold a few common cases.
2531
2532 unsigned NElts = Mask.size();
2533 auto V1VTy = cast<VectorType>(V1->getType());
2534 Type *EltTy = V1VTy->getElementType();
2535 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2536 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2537
2538 if (OnlyIfReducedTy == ShufTy)
2539 return nullptr;
2540
2541 // Look up the constant in the table first to ensure uniqueness
2542 Constant *ArgVec[] = {V1, V2};
2543 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2544
2545 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2546 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2547}
2548
2550 assert(C->getType()->isIntOrIntVectorTy() &&
2551 "Cannot NEG a nonintegral value!");
2552 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2553}
2554
2556 assert(C->getType()->isIntOrIntVectorTy() &&
2557 "Cannot NOT a nonintegral value!");
2558 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2559}
2560
2562 bool HasNUW, bool HasNSW) {
2563 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2565 return get(Instruction::Add, C1, C2, Flags);
2566}
2567
2569 bool HasNUW, bool HasNSW) {
2570 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2572 return get(Instruction::Sub, C1, C2, Flags);
2573}
2574
2576 bool HasNUW, bool HasNSW) {
2577 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2579 return get(Instruction::Mul, C1, C2, Flags);
2580}
2581
2583 return get(Instruction::Xor, C1, C2);
2584}
2585
2587 Type *Ty = C->getType();
2588 const APInt *IVal;
2589 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2590 return ConstantInt::get(Ty, IVal->logBase2());
2591
2592 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2593 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2594 if (!VecTy)
2595 return nullptr;
2596
2598 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2599 Constant *Elt = C->getAggregateElement(I);
2600 if (!Elt)
2601 return nullptr;
2602 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2603 if (isa<UndefValue>(Elt)) {
2605 continue;
2606 }
2607 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2608 return nullptr;
2609 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2610 }
2611
2612 return ConstantVector::get(Elts);
2613}
2614
2616 bool AllowRHSConstant, bool NSZ) {
2617 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2618
2619 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2620 if (Instruction::isCommutative(Opcode)) {
2621 switch (Opcode) {
2622 case Instruction::Add: // X + 0 = X
2623 case Instruction::Or: // X | 0 = X
2624 case Instruction::Xor: // X ^ 0 = X
2625 return Constant::getNullValue(Ty);
2626 case Instruction::Mul: // X * 1 = X
2627 return ConstantInt::get(Ty, 1);
2628 case Instruction::And: // X & -1 = X
2629 return Constant::getAllOnesValue(Ty);
2630 case Instruction::FAdd: // X + -0.0 = X
2631 return ConstantFP::getZero(Ty, !NSZ);
2632 case Instruction::FMul: // X * 1.0 = X
2633 return ConstantFP::get(Ty, 1.0);
2634 default:
2635 llvm_unreachable("Every commutative binop has an identity constant");
2636 }
2637 }
2638
2639 // Non-commutative opcodes: AllowRHSConstant must be set.
2640 if (!AllowRHSConstant)
2641 return nullptr;
2642
2643 switch (Opcode) {
2644 case Instruction::Sub: // X - 0 = X
2645 case Instruction::Shl: // X << 0 = X
2646 case Instruction::LShr: // X >>u 0 = X
2647 case Instruction::AShr: // X >> 0 = X
2648 case Instruction::FSub: // X - 0.0 = X
2649 return Constant::getNullValue(Ty);
2650 case Instruction::SDiv: // X / 1 = X
2651 case Instruction::UDiv: // X /u 1 = X
2652 return ConstantInt::get(Ty, 1);
2653 case Instruction::FDiv: // X / 1.0 = X
2654 return ConstantFP::get(Ty, 1.0);
2655 default:
2656 return nullptr;
2657 }
2658}
2659
2661 switch (ID) {
2662 case Intrinsic::umax:
2663 return Constant::getNullValue(Ty);
2664 case Intrinsic::umin:
2665 return Constant::getAllOnesValue(Ty);
2666 case Intrinsic::smax:
2669 case Intrinsic::smin:
2672 default:
2673 return nullptr;
2674 }
2675}
2676
2678 bool AllowRHSConstant, bool NSZ) {
2679 if (I->isBinaryOp())
2680 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2681 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2682 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2683 return nullptr;
2684}
2685
2687 switch (Opcode) {
2688 default:
2689 // Doesn't have an absorber.
2690 return nullptr;
2691
2692 case Instruction::Or:
2693 return Constant::getAllOnesValue(Ty);
2694
2695 case Instruction::And:
2696 case Instruction::Mul:
2697 return Constant::getNullValue(Ty);
2698 }
2699}
2700
2701/// Remove the constant from the constant table.
2702void ConstantExpr::destroyConstantImpl() {
2703 getType()->getContext().pImpl->ExprConstants.remove(this);
2704}
2705
2706const char *ConstantExpr::getOpcodeName() const {
2708}
2709
2710GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2711 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2712 std::optional<ConstantRange> InRange)
2713 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2715 (IdxList.size() + 1),
2716 IdxList.size() + 1),
2717 SrcElementTy(SrcElementTy),
2718 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2719 InRange(std::move(InRange)) {
2720 Op<0>() = C;
2721 Use *OperandList = getOperandList();
2722 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2723 OperandList[i+1] = IdxList[i];
2724}
2725
2727 return SrcElementTy;
2728}
2729
2731 return ResElementTy;
2732}
2733
2734std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2735 return InRange;
2736}
2737
2738//===----------------------------------------------------------------------===//
2739// ConstantData* implementations
2740
2742 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2743 return ATy->getElementType();
2744 return cast<VectorType>(getType())->getElementType();
2745}
2746
2748 return StringRef(DataElements, getNumElements()*getElementByteSize());
2749}
2750
2752 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2753 return true;
2754 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2755 switch (IT->getBitWidth()) {
2756 case 8:
2757 case 16:
2758 case 32:
2759 case 64:
2760 return true;
2761 default: break;
2762 }
2763 }
2764 return false;
2765}
2766
2768 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2769 return AT->getNumElements();
2770 return cast<FixedVectorType>(getType())->getNumElements();
2771}
2772
2773
2776}
2777
2778/// Return the start of the specified element.
2779const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2780 assert(Elt < getNumElements() && "Invalid Elt");
2781 return DataElements+Elt*getElementByteSize();
2782}
2783
2784
2785/// Return true if the array is empty or all zeros.
2786static bool isAllZeros(StringRef Arr) {
2787 for (char I : Arr)
2788 if (I != 0)
2789 return false;
2790 return true;
2791}
2792
2793/// This is the underlying implementation of all of the
2794/// ConstantDataSequential::get methods. They all thunk down to here, providing
2795/// the correct element type. We take the bytes in as a StringRef because
2796/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2798#ifndef NDEBUG
2799 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2800 assert(isElementTypeCompatible(ATy->getElementType()));
2801 else
2802 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2803#endif
2804 // If the elements are all zero or there are no elements, return a CAZ, which
2805 // is more dense and canonical.
2806 if (isAllZeros(Elements))
2807 return ConstantAggregateZero::get(Ty);
2808
2809 // Do a lookup to see if we have already formed one of these.
2810 auto &Slot =
2811 *Ty->getContext()
2812 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2813 .first;
2814
2815 // The bucket can point to a linked list of different CDS's that have the same
2816 // body but different types. For example, 0,0,0,1 could be a 4 element array
2817 // of i8, or a 1-element array of i32. They'll both end up in the same
2818 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2819 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2820 for (; *Entry; Entry = &(*Entry)->Next)
2821 if ((*Entry)->getType() == Ty)
2822 return Entry->get();
2823
2824 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2825 // and return it.
2826 if (isa<ArrayType>(Ty)) {
2827 // Use reset because std::make_unique can't access the constructor.
2828 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2829 return Entry->get();
2830 }
2831
2832 assert(isa<VectorType>(Ty));
2833 // Use reset because std::make_unique can't access the constructor.
2834 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2835 return Entry->get();
2836}
2837
2838void ConstantDataSequential::destroyConstantImpl() {
2839 // Remove the constant from the StringMap.
2842
2843 auto Slot = CDSConstants.find(getRawDataValues());
2844
2845 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2846
2847 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2848
2849 // Remove the entry from the hash table.
2850 if (!(*Entry)->Next) {
2851 // If there is only one value in the bucket (common case) it must be this
2852 // entry, and removing the entry should remove the bucket completely.
2853 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2854 getContext().pImpl->CDSConstants.erase(Slot);
2855 return;
2856 }
2857
2858 // Otherwise, there are multiple entries linked off the bucket, unlink the
2859 // node we care about but keep the bucket around.
2860 while (true) {
2861 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2862 assert(Node && "Didn't find entry in its uniquing hash table!");
2863 // If we found our entry, unlink it from the list and we're done.
2864 if (Node.get() == this) {
2865 Node = std::move(Node->Next);
2866 return;
2867 }
2868
2869 Entry = &Node->Next;
2870 }
2871}
2872
2873/// getFP() constructors - Return a constant of array type with a float
2874/// element type taken from argument `ElementType', and count taken from
2875/// argument `Elts'. The amount of bits of the contained type must match the
2876/// number of bits of the type contained in the passed in ArrayRef.
2877/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2878/// that this can return a ConstantAggregateZero object.
2880 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2881 "Element type is not a 16-bit float type");
2882 Type *Ty = ArrayType::get(ElementType, Elts.size());
2883 const char *Data = reinterpret_cast<const char *>(Elts.data());
2884 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2885}
2887 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2888 Type *Ty = ArrayType::get(ElementType, Elts.size());
2889 const char *Data = reinterpret_cast<const char *>(Elts.data());
2890 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2891}
2893 assert(ElementType->isDoubleTy() &&
2894 "Element type is not a 64-bit float type");
2895 Type *Ty = ArrayType::get(ElementType, Elts.size());
2896 const char *Data = reinterpret_cast<const char *>(Elts.data());
2897 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2898}
2899
2901 StringRef Str, bool AddNull) {
2902 if (!AddNull) {
2903 const uint8_t *Data = Str.bytes_begin();
2904 return get(Context, ArrayRef(Data, Str.size()));
2905 }
2906
2907 SmallVector<uint8_t, 64> ElementVals;
2908 ElementVals.append(Str.begin(), Str.end());
2909 ElementVals.push_back(0);
2910 return get(Context, ElementVals);
2911}
2912
2913/// get() constructors - Return a constant with vector type with an element
2914/// count and element type matching the ArrayRef passed in. Note that this
2915/// can return a ConstantAggregateZero object.
2917 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
2918 const char *Data = reinterpret_cast<const char *>(Elts.data());
2919 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2920}
2922 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
2923 const char *Data = reinterpret_cast<const char *>(Elts.data());
2924 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2925}
2927 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
2928 const char *Data = reinterpret_cast<const char *>(Elts.data());
2929 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2930}
2932 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
2933 const char *Data = reinterpret_cast<const char *>(Elts.data());
2934 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2935}
2937 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
2938 const char *Data = reinterpret_cast<const char *>(Elts.data());
2939 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2940}
2942 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
2943 const char *Data = reinterpret_cast<const char *>(Elts.data());
2944 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2945}
2946
2947/// getFP() constructors - Return a constant of vector type with a float
2948/// element type taken from argument `ElementType', and count taken from
2949/// argument `Elts'. The amount of bits of the contained type must match the
2950/// number of bits of the type contained in the passed in ArrayRef.
2951/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2952/// that this can return a ConstantAggregateZero object.
2954 ArrayRef<uint16_t> Elts) {
2955 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2956 "Element type is not a 16-bit float type");
2957 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2958 const char *Data = reinterpret_cast<const char *>(Elts.data());
2959 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2960}
2962 ArrayRef<uint32_t> Elts) {
2963 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2964 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2965 const char *Data = reinterpret_cast<const char *>(Elts.data());
2966 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2967}
2969 ArrayRef<uint64_t> Elts) {
2970 assert(ElementType->isDoubleTy() &&
2971 "Element type is not a 64-bit float type");
2972 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
2973 const char *Data = reinterpret_cast<const char *>(Elts.data());
2974 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2975}
2976
2978 assert(isElementTypeCompatible(V->getType()) &&
2979 "Element type not compatible with ConstantData");
2980 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2981 if (CI->getType()->isIntegerTy(8)) {
2982 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2983 return get(V->getContext(), Elts);
2984 }
2985 if (CI->getType()->isIntegerTy(16)) {
2986 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2987 return get(V->getContext(), Elts);
2988 }
2989 if (CI->getType()->isIntegerTy(32)) {
2990 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2991 return get(V->getContext(), Elts);
2992 }
2993 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2994 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2995 return get(V->getContext(), Elts);
2996 }
2997
2998 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2999 if (CFP->getType()->isHalfTy()) {
3001 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3002 return getFP(V->getType(), Elts);
3003 }
3004 if (CFP->getType()->isBFloatTy()) {
3006 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3007 return getFP(V->getType(), Elts);
3008 }
3009 if (CFP->getType()->isFloatTy()) {
3011 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3012 return getFP(V->getType(), Elts);
3013 }
3014 if (CFP->getType()->isDoubleTy()) {
3016 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3017 return getFP(V->getType(), Elts);
3018 }
3019 }
3021}
3022
3023
3025 assert(isa<IntegerType>(getElementType()) &&
3026 "Accessor can only be used when element is an integer");
3027 const char *EltPtr = getElementPointer(Elt);
3028
3029 // The data is stored in host byte order, make sure to cast back to the right
3030 // type to load with the right endianness.
3031 switch (getElementType()->getIntegerBitWidth()) {
3032 default: llvm_unreachable("Invalid bitwidth for CDS");
3033 case 8:
3034 return *reinterpret_cast<const uint8_t *>(EltPtr);
3035 case 16:
3036 return *reinterpret_cast<const uint16_t *>(EltPtr);
3037 case 32:
3038 return *reinterpret_cast<const uint32_t *>(EltPtr);
3039 case 64:
3040 return *reinterpret_cast<const uint64_t *>(EltPtr);
3041 }
3042}
3043
3045 assert(isa<IntegerType>(getElementType()) &&
3046 "Accessor can only be used when element is an integer");
3047 const char *EltPtr = getElementPointer(Elt);
3048
3049 // The data is stored in host byte order, make sure to cast back to the right
3050 // type to load with the right endianness.
3051 switch (getElementType()->getIntegerBitWidth()) {
3052 default: llvm_unreachable("Invalid bitwidth for CDS");
3053 case 8: {
3054 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3055 return APInt(8, EltVal);
3056 }
3057 case 16: {
3058 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3059 return APInt(16, EltVal);
3060 }
3061 case 32: {
3062 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3063 return APInt(32, EltVal);
3064 }
3065 case 64: {
3066 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3067 return APInt(64, EltVal);
3068 }
3069 }
3070}
3071
3073 const char *EltPtr = getElementPointer(Elt);
3074
3075 switch (getElementType()->getTypeID()) {
3076 default:
3077 llvm_unreachable("Accessor can only be used when element is float/double!");
3078 case Type::HalfTyID: {
3079 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3080 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3081 }
3082 case Type::BFloatTyID: {
3083 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3084 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3085 }
3086 case Type::FloatTyID: {
3087 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3088 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3089 }
3090 case Type::DoubleTyID: {
3091 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3092 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3093 }
3094 }
3095}
3096
3098 assert(getElementType()->isFloatTy() &&
3099 "Accessor can only be used when element is a 'float'");
3100 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3101}
3102
3104 assert(getElementType()->isDoubleTy() &&
3105 "Accessor can only be used when element is a 'float'");
3106 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3107}
3108
3110 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3111 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3112 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3113
3114 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3115}
3116
3117bool ConstantDataSequential::isString(unsigned CharSize) const {
3118 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3119}
3120
3122 if (!isString())
3123 return false;
3124
3125 StringRef Str = getAsString();
3126
3127 // The last value must be nul.
3128 if (Str.back() != 0) return false;
3129
3130 // Other elements must be non-nul.
3131 return !Str.drop_back().contains(0);
3132}
3133
3134bool ConstantDataVector::isSplatData() const {
3135 const char *Base = getRawDataValues().data();
3136
3137 // Compare elements 1+ to the 0'th element.
3138 unsigned EltSize = getElementByteSize();
3139 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3140 if (memcmp(Base, Base+i*EltSize, EltSize))
3141 return false;
3142
3143 return true;
3144}
3145
3147 if (!IsSplatSet) {
3148 IsSplatSet = true;
3149 IsSplat = isSplatData();
3150 }
3151 return IsSplat;
3152}
3153
3155 // If they're all the same, return the 0th one as a representative.
3156 return isSplat() ? getElementAsConstant(0) : nullptr;
3157}
3158
3159//===----------------------------------------------------------------------===//
3160// handleOperandChange implementations
3161
3162/// Update this constant array to change uses of
3163/// 'From' to be uses of 'To'. This must update the uniquing data structures
3164/// etc.
3165///
3166/// Note that we intentionally replace all uses of From with To here. Consider
3167/// a large array that uses 'From' 1000 times. By handling this case all here,
3168/// ConstantArray::handleOperandChange is only invoked once, and that
3169/// single invocation handles all 1000 uses. Handling them one at a time would
3170/// work, but would be really slow because it would have to unique each updated
3171/// array instance.
3172///
3174 Value *Replacement = nullptr;
3175 switch (getValueID()) {
3176 default:
3177 llvm_unreachable("Not a constant!");
3178#define HANDLE_CONSTANT(Name) \
3179 case Value::Name##Val: \
3180 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3181 break;
3182#include "llvm/IR/Value.def"
3183 }
3184
3185 // If handleOperandChangeImpl returned nullptr, then it handled
3186 // replacing itself and we don't want to delete or replace anything else here.
3187 if (!Replacement)
3188 return;
3189
3190 // I do need to replace this with an existing value.
3191 assert(Replacement != this && "I didn't contain From!");
3192
3193 // Everyone using this now uses the replacement.
3194 replaceAllUsesWith(Replacement);
3195
3196 // Delete the old constant!
3198}
3199
3200Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3201 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3202 Constant *ToC = cast<Constant>(To);
3203
3205 Values.reserve(getNumOperands()); // Build replacement array.
3206
3207 // Fill values with the modified operands of the constant array. Also,
3208 // compute whether this turns into an all-zeros array.
3209 unsigned NumUpdated = 0;
3210
3211 // Keep track of whether all the values in the array are "ToC".
3212 bool AllSame = true;
3213 Use *OperandList = getOperandList();
3214 unsigned OperandNo = 0;
3215 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3216 Constant *Val = cast<Constant>(O->get());
3217 if (Val == From) {
3218 OperandNo = (O - OperandList);
3219 Val = ToC;
3220 ++NumUpdated;
3221 }
3222 Values.push_back(Val);
3223 AllSame &= Val == ToC;
3224 }
3225
3226 if (AllSame && ToC->isNullValue())
3228
3229 if (AllSame && isa<UndefValue>(ToC))
3230 return UndefValue::get(getType());
3231
3232 // Check for any other type of constant-folding.
3233 if (Constant *C = getImpl(getType(), Values))
3234 return C;
3235
3236 // Update to the new value.
3238 Values, this, From, ToC, NumUpdated, OperandNo);
3239}
3240
3241Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3242 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3243 Constant *ToC = cast<Constant>(To);
3244
3245 Use *OperandList = getOperandList();
3246
3248 Values.reserve(getNumOperands()); // Build replacement struct.
3249
3250 // Fill values with the modified operands of the constant struct. Also,
3251 // compute whether this turns into an all-zeros struct.
3252 unsigned NumUpdated = 0;
3253 bool AllSame = true;
3254 unsigned OperandNo = 0;
3255 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3256 Constant *Val = cast<Constant>(O->get());
3257 if (Val == From) {
3258 OperandNo = (O - OperandList);
3259 Val = ToC;
3260 ++NumUpdated;
3261 }
3262 Values.push_back(Val);
3263 AllSame &= Val == ToC;
3264 }
3265
3266 if (AllSame && ToC->isNullValue())
3268
3269 if (AllSame && isa<UndefValue>(ToC))
3270 return UndefValue::get(getType());
3271
3272 // Update to the new value.
3274 Values, this, From, ToC, NumUpdated, OperandNo);
3275}
3276
3277Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3278 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3279 Constant *ToC = cast<Constant>(To);
3280
3282 Values.reserve(getNumOperands()); // Build replacement array...
3283 unsigned NumUpdated = 0;
3284 unsigned OperandNo = 0;
3285 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3286 Constant *Val = getOperand(i);
3287 if (Val == From) {
3288 OperandNo = i;
3289 ++NumUpdated;
3290 Val = ToC;
3291 }
3292 Values.push_back(Val);
3293 }
3294
3295 if (Constant *C = getImpl(Values))
3296 return C;
3297
3298 // Update to the new value.
3300 Values, this, From, ToC, NumUpdated, OperandNo);
3301}
3302
3303Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3304 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3305 Constant *To = cast<Constant>(ToV);
3306
3308 unsigned NumUpdated = 0;
3309 unsigned OperandNo = 0;
3310 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3311 Constant *Op = getOperand(i);
3312 if (Op == From) {
3313 OperandNo = i;
3314 ++NumUpdated;
3315 Op = To;
3316 }
3317 NewOps.push_back(Op);
3318 }
3319 assert(NumUpdated && "I didn't contain From!");
3320
3321 if (Constant *C = getWithOperands(NewOps, getType(), true))
3322 return C;
3323
3324 // Update to the new value.
3325 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3326 NewOps, this, From, To, NumUpdated, OperandNo);
3327}
3328
3330 SmallVector<Value *, 4> ValueOperands(operands());
3331 ArrayRef<Value*> Ops(ValueOperands);
3332
3333 switch (getOpcode()) {
3334 case Instruction::Trunc:
3335 case Instruction::PtrToInt:
3336 case Instruction::IntToPtr:
3337 case Instruction::BitCast:
3338 case Instruction::AddrSpaceCast:
3340 getType(), "");
3341 case Instruction::InsertElement:
3342 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3343 case Instruction::ExtractElement:
3344 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3345 case Instruction::ShuffleVector:
3346 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3347
3348 case Instruction::GetElementPtr: {
3349 const auto *GO = cast<GEPOperator>(this);
3350 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3351 Ops.slice(1), GO->getNoWrapFlags(), "");
3352 }
3353 default:
3354 assert(getNumOperands() == 2 && "Must be binary operator?");
3356 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3357 if (isa<OverflowingBinaryOperator>(BO)) {
3362 }
3363 if (isa<PossiblyExactOperator>(BO))
3365 return BO;
3366 }
3367}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the StringMap class.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
BlockVerifier::State From
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
Definition: Constants.cpp:2786
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:2128
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:528
#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())
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:1020
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:1028
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:5282
bool bitwiseIsEqual(const APFloat &RHS) const
Definition: APFloat.h:1313
static APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition: APFloat.cpp:5307
const fltSemantics & getSemantics() const
Definition: APFloat.h:1356
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition: APFloat.h:998
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition: APFloat.h:1009
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:982
Class for arbitrary precision integers.
Definition: APInt.h:77
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:213
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:188
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:198
unsigned logBase2() const
Definition: APInt.h:1718
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:419
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
const T * data() const
Definition: ArrayRef.h:162
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:195
Class to represent array types.
Definition: DerivedTypes.h:371
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
Type * getElementType() const
Definition: DerivedTypes.h:384
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:648
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:209
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:1851
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:1833
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:2900
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:2879
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:3044
double getElementAsDouble(unsigned i) const
If this is an sequential container of doubles, return the specified element as a double.
Definition: Constants.cpp:3103
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:2774
float getElementAsFloat(unsigned i) const
If this is an sequential container of floats, return the specified element as a float.
Definition: Constants.cpp:3097
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:3117
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:3024
static Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
Definition: Constants.cpp:2797
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2767
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index's element.
Definition: Constants.cpp:3109
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2741
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:3121
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:3072
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2747
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:2751
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:3154
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2977
bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value.
Definition: Constants.cpp:3146
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:2916
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:2953
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:1084
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2231
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2478
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:2414
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2177
static Constant * getTruncOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:2171
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2192
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:2677
static bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
Definition: Constants.cpp:2360
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:2146
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2568
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2555
const char * getOpcodeName() const
Return a string representation for an opcode.
Definition: Constants.cpp:2706
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2500
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2217
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2523
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:2404
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition: Constants.h:1352
static Constant * getIntrinsicIdentity(Intrinsic::ID, Type *Ty)
Definition: Constants.cpp:2660
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2582
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
Definition: Constants.cpp:2686
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2575
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:2264
static bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
Definition: Constants.cpp:2306
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:2333
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2257
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1292
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:1240
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2561
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2245
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2615
static bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
Definition: Constants.cpp:2382
static Constant * getNeg(Constant *C, bool HasNSW=false)
Definition: Constants.cpp:2549
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2203
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:2586
Constant * getWithOperands(ArrayRef< Constant * > Ops) const
This returns the current constant expression with the operands replaced with the specified values.
Definition: Constants.h:1310
Instruction * getAsInstruction() const
Returns an Instruction which implements the same operation as this ConstantExpr.
Definition: Constants.cpp:3329
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:1762
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:2063
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2008
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:2016
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
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:1779
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:41
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:400
bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
Definition: Constants.cpp:256
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
Definition: Constants.cpp: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
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:3173
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:1906
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:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:308
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:692
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:2734
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:914
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:937
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:278
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:72
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h: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:1964
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:1433
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1814
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:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
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:373
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:720
bool hasProperty(Property Prop) const
Returns true if the target extension type contains the given property.
Definition: Type.cpp:855
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:769
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
static Type * getDoubleTy(LLVMContext &C)
const fltSemantics & getFltSemantics() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
static Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:252
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:146
unsigned getStructNumElements() const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition: Type.h:75
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:79
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:77
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:74
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:76
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition: Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
@ TokenTyID
Tokens.
Definition: Type.h:68
@ PointerTyID
Pointers.
Definition: Type.h:73
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition: Type.h:61
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:249
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:281
static IntegerType * getInt16Ty(LLVMContext &C)
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:157
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
static Type * getFloatTy(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
'undef' values are things that do not have specified contents.
Definition: Constants.h:1385
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:1795
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:697
const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition: Value.cpp:705
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
User * user_back()
Definition: Value.h:407
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:532
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
bool use_empty() const
Definition: Value.h:344
user_iterator user_end()
Definition: Value.h:405
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
iterator_range< use_iterator > uses()
Definition: Value.h:376
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition: Value.h:815
ValueTy
Concrete subclass of this.
Definition: Value.h:513
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:641
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
Definition: DerivedTypes.h:454
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
Type * getElementType() const
Definition: DerivedTypes.h:436
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition: COFF.h:811
@ 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:31
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h: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:239
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:244
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1824
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:1849
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:271
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:246
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:274
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:288
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:273
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:272
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:269
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:270
Compile-time customization of User operands.
Definition: User.h:42