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