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