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 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
756
757 return Result;
758}
759
760/// Return true if the specified constantexpr is dead. This involves
761/// recursively traversing users of the constantexpr.
762/// If RemoveDeadUsers is true, also remove dead users at the same time.
763static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
764 if (isa<GlobalValue>(C)) return false; // Cannot remove this
765
766 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
767 while (I != E) {
769 if (!User) return false; // Non-constant usage;
770 if (!constantIsDead(User, RemoveDeadUsers))
771 return false; // Constant wasn't dead
772
773 // Just removed User, so the iterator was invalidated.
774 // Since we return immediately upon finding a live user, we can always
775 // restart from user_begin().
776 if (RemoveDeadUsers)
777 I = C->user_begin();
778 else
779 ++I;
780 }
781
782 if (RemoveDeadUsers) {
783 // If C is only used by metadata, it should not be preserved but should
784 // have its uses replaced.
786 const_cast<Constant *>(C)->destroyConstant();
787 }
788
789 return true;
790}
791
794 Value::const_user_iterator LastNonDeadUser = E;
795 while (I != E) {
797 if (!User) {
798 LastNonDeadUser = I;
799 ++I;
800 continue;
801 }
802
803 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
804 // If the constant wasn't dead, remember that this was the last live use
805 // and move on to the next constant.
806 LastNonDeadUser = I;
807 ++I;
808 continue;
809 }
810
811 // If the constant was dead, then the iterator is invalidated.
812 if (LastNonDeadUser == E)
813 I = user_begin();
814 else
815 I = std::next(LastNonDeadUser);
816 }
817}
818
819bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
820
821bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
822
823bool Constant::hasNLiveUses(unsigned N) const {
824 unsigned NumUses = 0;
825 for (const Use &U : uses()) {
826 const Constant *User = dyn_cast<Constant>(U.getUser());
827 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
828 ++NumUses;
829
830 if (NumUses > N)
831 return false;
832 }
833 }
834 return NumUses == N;
835}
836
838 assert(C && Replacement && "Expected non-nullptr constant arguments");
839 Type *Ty = C->getType();
840 if (match(C, m_Undef())) {
841 assert(Ty == Replacement->getType() && "Expected matching types");
842 return Replacement;
843 }
844
845 // Don't know how to deal with this constant.
846 auto *VTy = dyn_cast<FixedVectorType>(Ty);
847 if (!VTy)
848 return C;
849
850 unsigned NumElts = VTy->getNumElements();
851 SmallVector<Constant *, 32> NewC(NumElts);
852 for (unsigned i = 0; i != NumElts; ++i) {
853 Constant *EltC = C->getAggregateElement(i);
854 assert((!EltC || EltC->getType() == Replacement->getType()) &&
855 "Expected matching types");
856 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
857 }
858 return ConstantVector::get(NewC);
859}
860
862 assert(C && Other && "Expected non-nullptr constant arguments");
863 if (match(C, m_Undef()))
864 return C;
865
866 Type *Ty = C->getType();
867 if (match(Other, m_Undef()))
868 return UndefValue::get(Ty);
869
870 auto *VTy = dyn_cast<FixedVectorType>(Ty);
871 if (!VTy)
872 return C;
873
874 Type *EltTy = VTy->getElementType();
875 unsigned NumElts = VTy->getNumElements();
876 assert(isa<FixedVectorType>(Other->getType()) &&
877 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
878 "Type mismatch");
879
880 bool FoundExtraUndef = false;
881 SmallVector<Constant *, 32> NewC(NumElts);
882 for (unsigned I = 0; I != NumElts; ++I) {
883 NewC[I] = C->getAggregateElement(I);
884 Constant *OtherEltC = Other->getAggregateElement(I);
885 assert(NewC[I] && OtherEltC && "Unknown vector element");
886 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
887 NewC[I] = UndefValue::get(EltTy);
888 FoundExtraUndef = true;
889 }
890 }
891 if (FoundExtraUndef)
892 return ConstantVector::get(NewC);
893 return C;
894}
895
897 if (isa<UndefValue>(this))
898 return false;
899 if (isa<ConstantData>(this))
900 return true;
901 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
902 for (const Value *Op : operand_values())
904 return false;
905 return true;
906 }
907 return false;
908}
909
910//===----------------------------------------------------------------------===//
911// ConstantInt
912//===----------------------------------------------------------------------===//
913
914ConstantInt::ConstantInt(Type *Ty, const APInt &V)
915 : ConstantData(Ty, ConstantIntVal), Val(V) {
916 assert(V.getBitWidth() ==
917 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
918 "Invalid constant for type");
919 if (V.isZero())
921}
922
923ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
924 LLVMContextImpl *pImpl = Context.pImpl;
925 if (!pImpl->TheTrueVal)
926 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
927 return pImpl->TheTrueVal;
928}
929
930ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
931 LLVMContextImpl *pImpl = Context.pImpl;
932 if (!pImpl->TheFalseVal)
933 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
934 return pImpl->TheFalseVal;
935}
936
937ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
938 return V ? getTrue(Context) : getFalse(Context);
939}
940
942 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
943 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
944 if (auto *VTy = dyn_cast<VectorType>(Ty))
945 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
946 return TrueC;
947}
948
950 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
951 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
952 if (auto *VTy = dyn_cast<VectorType>(Ty))
953 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
954 return FalseC;
955}
956
958 return V ? getTrue(Ty) : getFalse(Ty);
959}
960
961// Get a ConstantInt from an APInt.
962ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
963 // get an existing value or the insertion position
964 LLVMContextImpl *pImpl = Context.pImpl;
965 std::unique_ptr<ConstantInt> &Slot =
966 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
967 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
968 : pImpl->IntConstants[V];
969 if (!Slot) {
970 // Get the corresponding integer type for the bit width of the value.
971 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
972 Slot.reset(new ConstantInt(ITy, V));
973 }
974 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
975 return Slot.get();
976}
977
978// Get a ConstantInt vector with each lane set to the same APInt.
979ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
980 const APInt &V) {
981 // Get an existing value or the insertion position.
982 std::unique_ptr<ConstantInt> &Slot =
983 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
984 if (!Slot) {
985 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
986 VectorType *VTy = VectorType::get(ITy, EC);
987 Slot.reset(new ConstantInt(VTy, V));
988 }
989
990#ifndef NDEBUG
991 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
992 VectorType *VTy = VectorType::get(ITy, EC);
993 assert(Slot->getType() == VTy);
994#endif
995 return Slot.get();
996}
997
998Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
999 bool ImplicitTrunc) {
1000 Constant *C =
1001 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
1002
1003 // For vectors, broadcast the value.
1004 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1005 return ConstantVector::getSplat(VTy->getElementCount(), C);
1006
1007 return C;
1008}
1009
1010ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
1011 bool ImplicitTrunc) {
1012 return get(Ty->getContext(),
1013 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
1014}
1015
1016Constant *ConstantInt::get(Type *Ty, const APInt& V) {
1017 ConstantInt *C = get(Ty->getContext(), V);
1018 assert(C->getType() == Ty->getScalarType() &&
1019 "ConstantInt type doesn't match the type implied by its value!");
1020
1021 // For vectors, broadcast the value.
1022 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1023 return ConstantVector::getSplat(VTy->getElementCount(), C);
1024
1025 return C;
1026}
1027
1028ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
1029 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1030}
1031
1032/// Remove the constant from the constant table.
1033void ConstantInt::destroyConstantImpl() {
1034 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
1035}
1036
1037//===----------------------------------------------------------------------===//
1038// ConstantByte
1039//===----------------------------------------------------------------------===//
1040
1041ConstantByte::ConstantByte(Type *Ty, const APInt &V)
1042 : ConstantData(Ty, ConstantByteVal), Val(V) {
1043 assert(V.getBitWidth() ==
1044 cast<ByteType>(Ty->getScalarType())->getBitWidth() &&
1045 "Invalid constant for type");
1046 if (V.isZero())
1048}
1049
1050// Get a ConstantByte from an APInt.
1051ConstantByte *ConstantByte::get(LLVMContext &Context, const APInt &V) {
1052 // get an existing value or the insertion position
1053 LLVMContextImpl *pImpl = Context.pImpl;
1054 std::unique_ptr<ConstantByte> &Slot =
1055 V.isZero() ? pImpl->ByteZeroConstants[V.getBitWidth()]
1056 : V.isOne() ? pImpl->ByteOneConstants[V.getBitWidth()]
1057 : pImpl->ByteConstants[V];
1058 if (!Slot) {
1059 // Get the corresponding byte type for the bit width of the value.
1060 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1061 Slot.reset(new ConstantByte(BTy, V));
1062 }
1063 assert(Slot->getType() == ByteType::get(Context, V.getBitWidth()));
1064 return Slot.get();
1065}
1066
1067// Get a ConstantByte vector with each lane set to the same APInt.
1068ConstantByte *ConstantByte::get(LLVMContext &Context, ElementCount EC,
1069 const APInt &V) {
1070 // Get an existing value or the insertion position.
1071 std::unique_ptr<ConstantByte> &Slot =
1072 Context.pImpl->ByteSplatConstants[std::make_pair(EC, V)];
1073 if (!Slot) {
1074 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1075 VectorType *VTy = VectorType::get(BTy, EC);
1076 Slot.reset(new ConstantByte(VTy, V));
1077 }
1078
1079#ifndef NDEBUG
1080 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1081 VectorType *VTy = VectorType::get(BTy, EC);
1082 assert(Slot->getType() == VTy);
1083#endif
1084 return Slot.get();
1085}
1086
1087Constant *ConstantByte::get(Type *Ty, uint64_t V, bool isSigned,
1088 bool ImplicitTrunc) {
1089 Constant *C =
1090 get(cast<ByteType>(Ty->getScalarType()), V, isSigned, ImplicitTrunc);
1091
1092 // For vectors, broadcast the value.
1093 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1094 return ConstantVector::getSplat(VTy->getElementCount(), C);
1095
1096 return C;
1097}
1098
1099ConstantByte *ConstantByte::get(ByteType *Ty, uint64_t V, bool isSigned,
1100 bool ImplicitTrunc) {
1101 return get(Ty->getContext(),
1102 APInt(Ty->getBitWidth(), V, isSigned, ImplicitTrunc));
1103}
1104
1105Constant *ConstantByte::get(Type *Ty, const APInt &V) {
1106 ConstantByte *C = get(Ty->getContext(), V);
1107 assert(C->getType() == Ty->getScalarType() &&
1108 "ConstantByte type doesn't match the type implied by its value!");
1109
1110 // For vectors, broadcast the value.
1111 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1112 return ConstantVector::getSplat(VTy->getElementCount(), C);
1113
1114 return C;
1115}
1116
1117ConstantByte *ConstantByte::get(ByteType *Ty, StringRef Str, uint8_t radix) {
1118 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1119}
1120
1121/// Remove the constant from the constant table.
1122void ConstantByte::destroyConstantImpl() {
1123 llvm_unreachable("You can't ConstantByte->destroyConstantImpl()!");
1124}
1125
1126//===----------------------------------------------------------------------===//
1127// ConstantFP
1128//===----------------------------------------------------------------------===//
1129
1130ConstantFP *ConstantFP::get(Type *Ty, double V) {
1131 LLVMContext &Context = Ty->getContext();
1132
1133 APFloat FV(V);
1134 bool ignored;
1135 FV.convert(Ty->getScalarType()->getFltSemantics(),
1137
1138 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1139 return get(Context, VTy->getElementCount(), FV);
1140
1141 return get(Context, FV);
1142}
1143
1144ConstantFP *ConstantFP::get(Type *Ty, const APFloat &V) {
1145 LLVMContext &Context = Ty->getContext();
1146 assert(Ty->getScalarType() ==
1147 Type::getFloatingPointTy(Context, V.getSemantics()) &&
1148 "ConstantFP type doesn't match the type implied by its value!");
1149
1150 if (auto *VTy = dyn_cast<VectorType>(Ty))
1151 return get(Context, VTy->getElementCount(), V);
1152
1153 return get(Ty->getContext(), V);
1154}
1155
1156ConstantFP *ConstantFP::get(Type *Ty, StringRef Str) {
1157 LLVMContext &Context = Ty->getContext();
1158 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1159
1160 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1161 return get(Context, VTy->getElementCount(), FV);
1162
1163 return get(Context, FV);
1164}
1165
1166ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1167 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1168 return get(Ty, APFloat::getInf(Semantics, Negative));
1169}
1170
1171ConstantFP *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1172 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1173 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1174 return get(Ty, NaN);
1175}
1176
1177ConstantFP *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1178 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1179 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1180 return get(Ty, NaN);
1181}
1182
1183ConstantFP *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1184 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1185 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1186 return get(Ty, NaN);
1187}
1188
1189ConstantFP *ConstantFP::getZero(Type *Ty, bool Negative) {
1190 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1191 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1192 return get(Ty, NegZero);
1193}
1194
1195// ConstantFP accessors.
1196ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1197 LLVMContextImpl* pImpl = Context.pImpl;
1198
1199 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1200
1201 if (!Slot) {
1202 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1203 Slot.reset(new ConstantFP(Ty, V));
1204 }
1205
1206 return Slot.get();
1207}
1208
1209// Get a ConstantFP vector with each lane set to the same APFloat.
1210ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1211 const APFloat &V) {
1212 // Get an existing value or the insertion position.
1213 std::unique_ptr<ConstantFP> &Slot =
1214 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1215 if (!Slot) {
1216 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1217 VectorType *VTy = VectorType::get(EltTy, EC);
1218 Slot.reset(new ConstantFP(VTy, V));
1219 }
1220
1221#ifndef NDEBUG
1222 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1223 VectorType *VTy = VectorType::get(EltTy, EC);
1224 assert(Slot->getType() == VTy);
1225#endif
1226 return Slot.get();
1227}
1228
1229ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1230 : ConstantData(Ty, ConstantFPVal), Val(V) {
1231 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1232 "FP type Mismatch");
1233 // ppc_fp128 determine isZero using high order double only
1234 // so check the bitwise value to make sure all bits are zero.
1235 if (V.bitcastToAPInt().isZero())
1237}
1238
1240 return Val.bitwiseIsEqual(V);
1241}
1242
1243/// Remove the constant from the constant table.
1244void ConstantFP::destroyConstantImpl() {
1245 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1246}
1247
1248//===----------------------------------------------------------------------===//
1249// ConstantAggregateZero Implementation
1250//===----------------------------------------------------------------------===//
1251
1253 if (auto *AT = dyn_cast<ArrayType>(getType()))
1254 return Constant::getNullValue(AT->getElementType());
1255 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1256}
1257
1259 return Constant::getNullValue(getType()->getStructElementType(Elt));
1260}
1261
1267
1270 return getSequentialElement();
1271 return getStructElement(Idx);
1272}
1273
1275 Type *Ty = getType();
1276 if (auto *AT = dyn_cast<ArrayType>(Ty))
1277 return ElementCount::getFixed(AT->getNumElements());
1278 if (auto *VT = dyn_cast<VectorType>(Ty))
1279 return VT->getElementCount();
1280 return ElementCount::getFixed(Ty->getStructNumElements());
1281}
1282
1283//===----------------------------------------------------------------------===//
1284// UndefValue Implementation
1285//===----------------------------------------------------------------------===//
1286
1289 return UndefValue::get(ATy->getElementType());
1290 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1291}
1292
1293UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1294 return UndefValue::get(getType()->getStructElementType(Elt));
1295}
1296
1299 return getSequentialElement();
1300 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1301}
1302
1303UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1305 return getSequentialElement();
1306 return getStructElement(Idx);
1307}
1308
1310 Type *Ty = getType();
1311 if (auto *AT = dyn_cast<ArrayType>(Ty))
1312 return AT->getNumElements();
1313 if (auto *VT = dyn_cast<VectorType>(Ty))
1314 return cast<FixedVectorType>(VT)->getNumElements();
1315 return Ty->getStructNumElements();
1316}
1317
1318//===----------------------------------------------------------------------===//
1319// PoisonValue Implementation
1320//===----------------------------------------------------------------------===//
1321
1324 return PoisonValue::get(ATy->getElementType());
1325 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1326}
1327
1328PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1329 return PoisonValue::get(getType()->getStructElementType(Elt));
1330}
1331
1334 return getSequentialElement();
1335 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1336}
1337
1338PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1340 return getSequentialElement();
1341 return getStructElement(Idx);
1342}
1343
1344//===----------------------------------------------------------------------===//
1345// ConstantXXX Classes
1346//===----------------------------------------------------------------------===//
1347
1348template <typename ItTy, typename EltTy>
1349static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1350 for (; Start != End; ++Start)
1351 if (*Start != Elt)
1352 return false;
1353 return true;
1354}
1355
1356template <typename SequentialTy, typename ElementTy>
1358 assert(!V.empty() && "Cannot get empty int sequence.");
1359
1361 for (Constant *C : V)
1362 if (auto *CI = dyn_cast<ConstantInt>(C))
1363 Elts.push_back(CI->getZExtValue());
1364 else
1365 return nullptr;
1366 return SequentialTy::get(V[0]->getContext(), Elts);
1367}
1368
1369template <typename SequentialTy, typename ElementTy>
1371 assert(!V.empty() && "Cannot get empty byte sequence.");
1372
1374 for (Constant *C : V)
1375 if (auto *CI = dyn_cast<ConstantByte>(C))
1376 Elts.push_back(CI->getZExtValue());
1377 else
1378 return nullptr;
1379 return SequentialTy::getByte(V[0]->getType(), Elts);
1380}
1381
1382template <typename SequentialTy, typename ElementTy>
1384 assert(!V.empty() && "Cannot get empty FP sequence.");
1385
1387 for (Constant *C : V)
1388 if (auto *CFP = dyn_cast<ConstantFP>(C))
1389 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1390 else
1391 return nullptr;
1392 return SequentialTy::getFP(V[0]->getType(), Elts);
1393}
1394
1395template <typename SequenceTy>
1398 // We speculatively build the elements here even if it turns out that there is
1399 // a constantexpr or something else weird, since it is so uncommon for that to
1400 // happen.
1401 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1402 if (CI->getType()->isIntegerTy(8))
1404 else if (CI->getType()->isIntegerTy(16))
1406 else if (CI->getType()->isIntegerTy(32))
1408 else if (CI->getType()->isIntegerTy(64))
1410 } else if (ConstantByte *CB = dyn_cast<ConstantByte>(C)) {
1411 if (CB->getType()->isByteTy(8))
1413 else if (CB->getType()->isByteTy(16))
1415 else if (CB->getType()->isByteTy(32))
1417 else if (CB->getType()->isByteTy(64))
1419 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1420 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1422 else if (CFP->getType()->isFloatTy())
1424 else if (CFP->getType()->isDoubleTy())
1426 }
1427
1428 return nullptr;
1429}
1430
1434 : Constant(T, VT, AllocInfo) {
1435 llvm::copy(V, op_begin());
1436
1437 // Check that types match, unless this is an opaque struct.
1438 if (auto *ST = dyn_cast<StructType>(T)) {
1439 if (ST->isOpaque())
1440 return;
1441 for (unsigned I = 0, E = V.size(); I != E; ++I)
1442 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1443 "Initializer for struct element doesn't match!");
1444 }
1445}
1446
1447ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1449 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1450 assert(V.size() == T->getNumElements() &&
1451 "Invalid initializer for constant array");
1452}
1453
1455 if (Constant *C = getImpl(Ty, V))
1456 return C;
1457 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1458}
1459
1460Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1461 // Empty arrays are canonicalized to ConstantAggregateZero.
1462 if (V.empty())
1463 return ConstantAggregateZero::get(Ty);
1464
1465 for (Constant *C : V) {
1466 assert(C->getType() == Ty->getElementType() &&
1467 "Wrong type in array element initializer");
1468 (void)C;
1469 }
1470
1471 // If this is an all-zero array, return a ConstantAggregateZero object. If
1472 // all undef, return an UndefValue, if "all simple", then return a
1473 // ConstantDataArray.
1474 Constant *C = V[0];
1475 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1476 return PoisonValue::get(Ty);
1477
1478 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1479 return UndefValue::get(Ty);
1480
1481 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1482 return ConstantAggregateZero::get(Ty);
1483
1484 // Check to see if all of the elements are ConstantFP or ConstantInt or
1485 // ConstantByte and if the element type is compatible with ConstantDataVector.
1486 // If so, use it.
1489
1490 // Otherwise, we really do want to create a ConstantArray.
1491 return nullptr;
1492}
1493
1496 bool Packed) {
1497 unsigned VecSize = V.size();
1498 SmallVector<Type*, 16> EltTypes(VecSize);
1499 for (unsigned i = 0; i != VecSize; ++i)
1500 EltTypes[i] = V[i]->getType();
1501
1502 return StructType::get(Context, EltTypes, Packed);
1503}
1504
1505
1507 bool Packed) {
1508 assert(!V.empty() &&
1509 "ConstantStruct::getTypeForElements cannot be called on empty list");
1510 return getTypeForElements(V[0]->getContext(), V, Packed);
1511}
1512
1513ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1515 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1516 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1517 "Invalid initializer for constant struct");
1518}
1519
1520// ConstantStruct accessors.
1522 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1523 "Incorrect # elements specified to ConstantStruct::get");
1524
1525 // Create a ConstantAggregateZero value if all elements are zeros.
1526 bool isZero = true;
1527 bool isUndef = false;
1528 bool isPoison = false;
1529
1530 if (!V.empty()) {
1531 isUndef = isa<UndefValue>(V[0]);
1532 isPoison = isa<PoisonValue>(V[0]);
1533 isZero = V[0]->isNullValue();
1534 // PoisonValue inherits UndefValue, so its check is not necessary.
1535 if (isUndef || isZero) {
1536 for (Constant *C : V) {
1537 if (!C->isNullValue())
1538 isZero = false;
1539 if (!isa<PoisonValue>(C))
1540 isPoison = false;
1542 isUndef = false;
1543 }
1544 }
1545 }
1546 if (isZero)
1547 return ConstantAggregateZero::get(ST);
1548 if (isPoison)
1549 return PoisonValue::get(ST);
1550 if (isUndef)
1551 return UndefValue::get(ST);
1552
1553 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1554}
1555
1556ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1558 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1559 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1560 "Invalid initializer for constant vector");
1561}
1562
1563// ConstantVector accessors.
1565 if (Constant *C = getImpl(V))
1566 return C;
1567 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1568 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1569}
1570
1571Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1572 assert(!V.empty() && "Vectors can't be empty");
1573 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1574
1575 // If this is an all-undef or all-zero vector, return a
1576 // ConstantAggregateZero or UndefValue.
1577 Constant *C = V[0];
1578 bool isZero = C->isNullValue();
1579 bool isUndef = isa<UndefValue>(C);
1580 bool isPoison = isa<PoisonValue>(C);
1581 bool isSplatFP = isa<ConstantFP>(C);
1582 bool isSplatInt =
1584 getIROptions(C->getContext()).use_constant_int_for_fixed_length_splat;
1585 bool isSplatByte = isa<ConstantByte>(C);
1586 bool isSplatPtrNull = isa<ConstantPointerNull>(C);
1587
1588 if (isZero || isUndef || isSplatFP || isSplatInt || isSplatByte ||
1589 isSplatPtrNull) {
1590 for (unsigned i = 1, e = V.size(); i != e; ++i)
1591 if (V[i] != C) {
1592 isZero = isUndef = isPoison = isSplatFP = isSplatInt = isSplatByte =
1593 isSplatPtrNull = false;
1594 break;
1595 }
1596 }
1597
1598 if (isSplatPtrNull)
1600 if (isZero)
1602 if (isPoison)
1603 return PoisonValue::get(T);
1604 if (isUndef)
1605 return UndefValue::get(T);
1606 if (isSplatFP)
1607 return ConstantFP::get(C->getContext(), T->getElementCount(),
1608 cast<ConstantFP>(C)->getValue());
1609 if (isSplatInt)
1610 return ConstantInt::get(C->getContext(), T->getElementCount(),
1611 cast<ConstantInt>(C)->getValue());
1612 if (isSplatByte)
1613 return ConstantByte::get(C->getContext(), T->getElementCount(),
1614 cast<ConstantByte>(C)->getValue());
1615
1616 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1617 // the element type is compatible with ConstantDataVector. If so, use it.
1620
1621 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1622 // the operand list contains a ConstantExpr or something else strange.
1623 return nullptr;
1624}
1625
1627 if (isa<ConstantPointerNull>(V)) {
1628 VectorType *VTy = VectorType::get(V->getType(), EC);
1629 return ConstantPointerNull::get(VTy);
1630 }
1631
1632 if (auto *CB = dyn_cast<ConstantByte>(V))
1633 return ConstantByte::get(V->getContext(), EC, CB->getValue());
1634
1635 if (auto *CFP = dyn_cast<ConstantFP>(V))
1636 return ConstantFP::get(V->getContext(), EC, CFP->getValue());
1637
1638 if (!EC.isScalable()) {
1639 // Maintain special handling of zero.
1640 if (!V->isNullValue()) {
1641 if (isa<ConstantInt>(V) &&
1642 getIROptions(V->getContext()).use_constant_int_for_fixed_length_splat)
1643 return ConstantInt::get(V->getContext(), EC,
1644 cast<ConstantInt>(V)->getValue());
1645 }
1646
1647 // If this splat is compatible with ConstantDataVector, use it instead of
1648 // ConstantVector.
1649 if (isa<ConstantInt>(V) &&
1651 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1652
1653 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1654 return get(Elts);
1655 }
1656
1657 // Maintain special handling of zero.
1658 if (!V->isNullValue()) {
1659 if (isa<ConstantInt>(V) &&
1660 getIROptions(V->getContext()).use_constant_int_for_scalable_splat)
1661 return ConstantInt::get(V->getContext(), EC,
1662 cast<ConstantInt>(V)->getValue());
1663 }
1664
1665 Type *VTy = VectorType::get(V->getType(), EC);
1666
1667 if (V->isNullValue())
1668 return ConstantAggregateZero::get(VTy);
1669 if (isa<PoisonValue>(V))
1670 return PoisonValue::get(VTy);
1671 if (isa<UndefValue>(V))
1672 return UndefValue::get(VTy);
1673
1674 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1675
1676 // Move scalar into vector.
1677 Constant *PoisonV = PoisonValue::get(VTy);
1678 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1679 // Build shuffle mask to perform the splat.
1680 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1681 // Splat.
1682 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1683}
1684
1685ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1686 LLVMContextImpl *pImpl = Context.pImpl;
1687 if (!pImpl->TheNoneToken)
1688 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1689 return pImpl->TheNoneToken.get();
1690}
1691
1692/// Remove the constant from the constant table.
1693void ConstantTokenNone::destroyConstantImpl() {
1694 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1695}
1696
1697// Utility function for determining if a ConstantExpr is a CastOp or not. This
1698// can't be inline because we don't want to #include Instruction.h into
1699// Constant.h
1701
1705
1707 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1708}
1709
1711 bool OnlyIfReduced, Type *SrcTy) const {
1712 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1713
1714 // If no operands changed return self.
1715 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1716 return const_cast<ConstantExpr*>(this);
1717
1718 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1719 switch (getOpcode()) {
1720 case Instruction::Trunc:
1721 case Instruction::ZExt:
1722 case Instruction::SExt:
1723 case Instruction::FPTrunc:
1724 case Instruction::FPExt:
1725 case Instruction::UIToFP:
1726 case Instruction::SIToFP:
1727 case Instruction::FPToUI:
1728 case Instruction::FPToSI:
1729 case Instruction::PtrToAddr:
1730 case Instruction::PtrToInt:
1731 case Instruction::IntToPtr:
1732 case Instruction::BitCast:
1733 case Instruction::AddrSpaceCast:
1734 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1735 case Instruction::InsertElement:
1736 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1737 OnlyIfReducedTy);
1738 case Instruction::ExtractElement:
1739 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1740 case Instruction::ShuffleVector:
1742 OnlyIfReducedTy);
1743 case Instruction::GetElementPtr: {
1744 auto *GEPO = cast<GEPOperator>(this);
1745 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1748 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1749 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1751 }
1752 default:
1753 assert(getNumOperands() == 2 && "Must be binary operator?");
1755 OnlyIfReducedTy);
1756 }
1757}
1758
1759
1760//===----------------------------------------------------------------------===//
1761// isValueValidForType implementations
1762
1764 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1765 if (Ty->isIntegerTy(1))
1766 return Val == 0 || Val == 1;
1767 return isUIntN(NumBits, Val);
1768}
1769
1771 unsigned NumBits = Ty->getIntegerBitWidth();
1772 if (Ty->isIntegerTy(1))
1773 return Val == 0 || Val == 1 || Val == -1;
1774 return isIntN(NumBits, Val);
1775}
1776
1778 // convert modifies in place, so make a copy.
1779 APFloat Val2 = APFloat(Val);
1780 bool losesInfo;
1781 switch (Ty->getTypeID()) {
1782 default:
1783 return false; // These can't be represented as floating point!
1784
1785 // FIXME rounding mode needs to be more flexible
1786 case Type::HalfTyID: {
1787 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1788 return true;
1790 return !losesInfo;
1791 }
1792 case Type::BFloatTyID: {
1793 if (&Val2.getSemantics() == &APFloat::BFloat())
1794 return true;
1796 return !losesInfo;
1797 }
1798 case Type::FloatTyID: {
1799 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1800 return true;
1802 return !losesInfo;
1803 }
1804 case Type::DoubleTyID: {
1805 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1806 &Val2.getSemantics() == &APFloat::BFloat() ||
1807 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1808 &Val2.getSemantics() == &APFloat::IEEEdouble())
1809 return true;
1811 return !losesInfo;
1812 }
1813 case Type::X86_FP80TyID:
1814 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1815 &Val2.getSemantics() == &APFloat::BFloat() ||
1816 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1817 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1819 case Type::FP128TyID:
1820 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1821 &Val2.getSemantics() == &APFloat::BFloat() ||
1822 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1823 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1824 &Val2.getSemantics() == &APFloat::IEEEquad();
1826 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1827 &Val2.getSemantics() == &APFloat::BFloat() ||
1828 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1829 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1831 }
1832}
1833
1834
1835//===----------------------------------------------------------------------===//
1836// Factory Function Implementation
1837
1838ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1839 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1840 "Cannot create an aggregate zero of non-aggregate type!");
1841
1842 std::unique_ptr<ConstantAggregateZero> &Entry =
1843 Ty->getContext().pImpl->CAZConstants[Ty];
1844 if (!Entry)
1845 Entry.reset(new ConstantAggregateZero(Ty));
1846
1847 return Entry.get();
1848}
1849
1850/// Remove the constant from the constant table.
1851void ConstantAggregateZero::destroyConstantImpl() {
1853}
1854
1855/// Remove the constant from the constant table.
1856void ConstantArray::destroyConstantImpl() {
1858}
1859
1860
1861//---- ConstantStruct::get() implementation...
1862//
1863
1864/// Remove the constant from the constant table.
1865void ConstantStruct::destroyConstantImpl() {
1867}
1868
1869/// Remove the constant from the constant table.
1870void ConstantVector::destroyConstantImpl() {
1872}
1873
1874Constant *Constant::getSplatValue(bool AllowPoison) const {
1875 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1876 if (isa<PoisonValue>(this))
1877 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1879 return getNullValue(cast<VectorType>(getType())->getElementType());
1880 if (auto *CI = dyn_cast<ConstantInt>(this))
1881 return ConstantInt::get(getContext(), CI->getValue());
1882 if (auto *CB = dyn_cast<ConstantByte>(this))
1883 return ConstantByte::get(getContext(), CB->getValue());
1884 if (auto *CFP = dyn_cast<ConstantFP>(this))
1885 return ConstantFP::get(getContext(), CFP->getValue());
1886 if (auto *CPN = dyn_cast<ConstantPointerNull>(this))
1887 return ConstantPointerNull::get(CPN->getPointerType());
1889 return CV->getSplatValue();
1890 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1891 return CV->getSplatValue(AllowPoison);
1892
1893 // Check if this is a constant expression splat of the form returned by
1894 // ConstantVector::getSplat()
1895 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1896 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1897 isa<UndefValue>(Shuf->getOperand(1))) {
1898
1899 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1900 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1901 isa<UndefValue>(IElt->getOperand(0))) {
1902
1903 ArrayRef<int> Mask = Shuf->getShuffleMask();
1904 Constant *SplatVal = IElt->getOperand(1);
1905 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1906
1907 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1908 return SplatVal;
1909 }
1910 }
1911
1912 return nullptr;
1913}
1914
1915Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1916 // Check out first element.
1917 Constant *Elt = getOperand(0);
1918 // Then make sure all remaining elements point to the same value.
1919 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1920 Constant *OpC = getOperand(I);
1921 if (OpC == Elt)
1922 continue;
1923
1924 // Strict mode: any mismatch is not a splat.
1925 if (!AllowPoison)
1926 return nullptr;
1927
1928 // Allow poison mode: ignore poison elements.
1929 if (isa<PoisonValue>(OpC))
1930 continue;
1931
1932 // If we do not have a defined element yet, use the current operand.
1933 if (isa<PoisonValue>(Elt))
1934 Elt = OpC;
1935
1936 if (OpC != Elt)
1937 return nullptr;
1938 }
1939 return Elt;
1940}
1941
1943 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1944 return CI->getValue();
1945 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
1946 return CB->getValue();
1947 // Scalable vectors can use a ConstantExpr to build a splat.
1948 if (isa<ConstantExpr>(this))
1949 return cast<ConstantInt>(this->getSplatValue())->getValue();
1950 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1951 // calling getSplatValue in release builds.
1952 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1953 const Constant *C = this->getAggregateElement(0U);
1954 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1955 return cast<ConstantInt>(C)->getValue();
1956}
1957
1959 if (auto *CI = dyn_cast<ConstantInt>(this))
1960 return ConstantRange(CI->getValue());
1961
1962 unsigned BitWidth = getType()->getScalarSizeInBits();
1963 if (!getType()->isVectorTy())
1964 return ConstantRange::getFull(BitWidth);
1965
1966 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1967 getSplatValue(/*AllowPoison=*/true)))
1968 return ConstantRange(CI->getValue());
1969
1970 if (auto *CB =
1971 dyn_cast_or_null<ConstantByte>(getSplatValue(/*AllowPoison=*/true)))
1972 return ConstantRange(CB->getValue());
1973
1974 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1975 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1976 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1977 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1978 return CR;
1979 }
1980
1981 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1982 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1983 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1984 Constant *Elem = CV->getOperand(I);
1985 if (!Elem)
1986 return ConstantRange::getFull(BitWidth);
1987 if (isa<PoisonValue>(Elem))
1988 continue;
1989 auto *CI = dyn_cast<ConstantInt>(Elem);
1990 auto *CB = dyn_cast<ConstantByte>(Elem);
1991 if (!CI && !CB)
1992 return ConstantRange::getFull(BitWidth);
1993 CR = CR.unionWith(CI ? CI->getValue() : CB->getValue());
1994 }
1995 return CR;
1996 }
1997
1998 return ConstantRange::getFull(BitWidth);
1999}
2000
2002 if (auto *CFP = dyn_cast<ConstantFP>(this))
2003 return ConstantFPRange(CFP->getValue());
2004
2006 if (!getType()->isVectorTy())
2007 return ConstantFPRange::getFull(Sem);
2008
2009 if (auto *CFP =
2010 dyn_cast_or_null<ConstantFP>(getSplatValue(/*AllowPoison=*/true)))
2011 return ConstantFPRange(CFP->getValue());
2012
2013 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
2014 ConstantFPRange CR = ConstantFPRange::getEmpty(Sem);
2015 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
2016 CR = CR.unionWith(ConstantFPRange(CDV->getElementAsAPFloat(I)));
2017 return CR;
2018 }
2019
2020 if (auto *CV = dyn_cast<ConstantVector>(this)) {
2021 ConstantFPRange CR = ConstantFPRange::getEmpty(Sem);
2022 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
2023 Constant *Elem = CV->getOperand(I);
2024 if (!Elem)
2025 return ConstantFPRange::getFull(Sem);
2026 if (isa<PoisonValue>(Elem))
2027 continue;
2028 auto *CFP = dyn_cast<ConstantFP>(Elem);
2029 if (!CFP)
2030 return ConstantFPRange::getFull(Sem);
2031 CR = CR.unionWith(ConstantFPRange(CFP->getValue()));
2032 }
2033 return CR;
2034 }
2035
2036 return ConstantFPRange::getFull(Sem);
2037}
2038
2039//---- ConstantPointerNull::get() implementation.
2040//
2041
2042ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
2043 return get(static_cast<Type *>(Ty));
2044}
2045
2046ConstantPointerNull *ConstantPointerNull::get(Type *Ty) {
2047 assert(Ty->isPtrOrPtrVectorTy() && "invalid type for null pointer constant");
2048 std::unique_ptr<ConstantPointerNull> &Entry =
2049 Ty->getContext().pImpl->CPNConstants[Ty];
2050 if (!Entry)
2051 Entry.reset(new ConstantPointerNull(Ty));
2052
2053 assert(Entry->getType() == Ty);
2054 return Entry.get();
2055}
2056
2057/// Remove the constant from the constant table.
2058void ConstantPointerNull::destroyConstantImpl() {
2060}
2061
2062//---- ConstantTargetNone::get() implementation.
2063//
2064
2065ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
2066 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
2067 "Target extension type not allowed to have a zeroinitializer");
2068 std::unique_ptr<ConstantTargetNone> &Entry =
2069 Ty->getContext().pImpl->CTNConstants[Ty];
2070 if (!Entry)
2071 Entry.reset(new ConstantTargetNone(Ty));
2072
2073 return Entry.get();
2074}
2075
2076/// Remove the constant from the constant table.
2077void ConstantTargetNone::destroyConstantImpl() {
2079}
2080
2081UndefValue *UndefValue::get(Type *Ty) {
2082 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
2083 if (!Entry)
2084 Entry.reset(new UndefValue(Ty));
2085
2086 return Entry.get();
2087}
2088
2089/// Remove the constant from the constant table.
2090void UndefValue::destroyConstantImpl() {
2091 // Free the constant and any dangling references to it.
2092 if (getValueID() == UndefValueVal) {
2093 getContext().pImpl->UVConstants.erase(getType());
2094 } else if (getValueID() == PoisonValueVal) {
2095 getContext().pImpl->PVConstants.erase(getType());
2096 }
2097 llvm_unreachable("Not a undef or a poison!");
2098}
2099
2100PoisonValue *PoisonValue::get(Type *Ty) {
2101 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
2102 if (!Entry)
2103 Entry.reset(new PoisonValue(Ty));
2104
2105 return Entry.get();
2106}
2107
2108/// Remove the constant from the constant table.
2109void PoisonValue::destroyConstantImpl() {
2110 // Free the constant and any dangling references to it.
2111 getContext().pImpl->PVConstants.erase(getType());
2112}
2113
2114BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
2115 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
2116 if (!BA)
2117 BA = new BlockAddress(Ty, BB);
2118 return BA;
2119}
2120
2121BlockAddress *BlockAddress::get(BasicBlock *BB) {
2122 assert(BB->getParent() && "Block must have a parent");
2123 return get(BB->getParent()->getType(), BB);
2124}
2125
2127 assert(BB->getParent() == F && "Block not part of specified function");
2128 return get(BB->getParent()->getType(), BB);
2129}
2130
2131BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
2132 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
2133 Block = BB;
2134 BB->setHasAddressTaken(true);
2135}
2136
2137BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
2138 if (!BB->hasAddressTaken())
2139 return nullptr;
2140
2141 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
2142 assert(BA && "Refcount and block address map disagree!");
2143 return BA;
2144}
2145
2146/// Remove the constant from the constant table.
2147void BlockAddress::destroyConstantImpl() {
2149 getBasicBlock()->setHasAddressTaken(false);
2150}
2151
2152Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
2153 assert(From == getBasicBlock());
2154 BasicBlock *NewBB = cast<BasicBlock>(To);
2155
2156 // See if the 'new' entry already exists, if not, just update this in place
2157 // and return early.
2158 if (BlockAddress *NewBA = getContext().pImpl->BlockAddresses.lookup(NewBB))
2159 return NewBA;
2160
2161 getBasicBlock()->setHasAddressTaken(false);
2162
2163 // erase invalidates iterators/references, hence the duplicate NewBB lookup.
2165 getContext().pImpl->BlockAddresses[NewBB] = this;
2166 Block = NewBB;
2167 getBasicBlock()->setHasAddressTaken(true);
2168
2169 // If we just want to keep the existing value, then return null.
2170 // Callers know that this means we shouldn't delete this value.
2171 return nullptr;
2172}
2173
2174DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
2175 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
2176 if (!Equiv)
2177 Equiv = new DSOLocalEquivalent(GV);
2178
2179 assert(Equiv->getGlobalValue() == GV &&
2180 "DSOLocalFunction does not match the expected global value");
2181 return Equiv;
2182}
2183
2184DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
2185 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
2186 setOperand(0, GV);
2187}
2188
2189/// Remove the constant from the constant table.
2190void DSOLocalEquivalent::destroyConstantImpl() {
2191 const GlobalValue *GV = getGlobalValue();
2192 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2193}
2194
2195Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2196 assert(From == getGlobalValue() && "Changing value does not match operand.");
2197 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2198
2199 // If the argument is replaced with a null value, just replace this constant
2200 // with a null value.
2202 return To;
2203
2204 // The replacement could be a bitcast to another GlobalValue. We can
2205 // replace it with a bitcast to the dso_local_equivalent of that GV.
2206 GlobalValue *GV = cast<GlobalValue>(To->stripPointerCasts());
2207 if (DSOLocalEquivalent *NewEquiv =
2208 getContext().pImpl->DSOLocalEquivalents.lookup(GV))
2209 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2210
2211 // erase invalidates iterators/references, hence the duplicate GV lookup.
2213 getContext().pImpl->DSOLocalEquivalents[GV] = this;
2214 setOperand(0, GV);
2215
2216 if (GV->getType() != getType()) {
2217 // It is ok to mutate the type here because this constant should always
2218 // reflect the type of the function it's holding.
2219 mutateType(GV->getType());
2220 }
2221 return nullptr;
2222}
2223
2225 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2226 if (!NC)
2227 NC = new NoCFIValue(GV);
2228
2229 assert(NC->getGlobalValue() == GV &&
2230 "NoCFIValue does not match the expected global value");
2231 return NC;
2232}
2233
2234NoCFIValue::NoCFIValue(GlobalValue *GV)
2235 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2236 setOperand(0, GV);
2237}
2238
2239/// Remove the constant from the constant table.
2240void NoCFIValue::destroyConstantImpl() {
2241 const GlobalValue *GV = getGlobalValue();
2242 GV->getContext().pImpl->NoCFIValues.erase(GV);
2243}
2244
2245Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2246 assert(From == getGlobalValue() && "Changing value does not match operand.");
2247
2248 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2249 assert(GV && "Can only replace the operands with a global value");
2250
2251 if (NoCFIValue *NewNC = getContext().pImpl->NoCFIValues.lookup(GV))
2252 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2253
2254 // erase invalidates iterators/references, hence the duplicate GV lookup.
2256 getContext().pImpl->NoCFIValues[GV] = this;
2257 setOperand(0, GV);
2258
2259 if (GV->getType() != getType())
2260 mutateType(GV->getType());
2261
2262 return nullptr;
2263}
2264
2265//---- ConstantPtrAuth::get() implementations.
2266//
2267
2269 ConstantInt *Disc, Constant *AddrDisc,
2270 Constant *DeactivationSymbol) {
2271 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2272 ConstantPtrAuthKeyType MapKey(ArgVec);
2273 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2274 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2275}
2276
2277ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2278 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2280}
2281
2282ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2283 ConstantInt *Disc, Constant *AddrDisc,
2284 Constant *DeactivationSymbol)
2285 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2286 assert(Ptr->getType()->isPointerTy());
2287 assert(Key->getBitWidth() == 32);
2288 assert(Disc->getBitWidth() == 64);
2289 assert(AddrDisc->getType()->isPointerTy());
2290 assert(DeactivationSymbol->getType()->isPointerTy());
2291 setOperand(0, Ptr);
2292 setOperand(1, Key);
2293 setOperand(2, Disc);
2294 setOperand(3, AddrDisc);
2295 setOperand(4, DeactivationSymbol);
2296}
2297
2298/// Remove the constant from the constant table.
2299void ConstantPtrAuth::destroyConstantImpl() {
2300 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2301}
2302
2303Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2304 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2305 Constant *To = cast<Constant>(ToV);
2306
2307 SmallVector<Constant *, 4> Values;
2308 Values.reserve(getNumOperands());
2309
2310 unsigned NumUpdated = 0;
2311
2312 Use *OperandList = getOperandList();
2313 unsigned OperandNo = 0;
2314 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2315 Constant *Val = cast<Constant>(O->get());
2316 if (Val == From) {
2317 OperandNo = (O - OperandList);
2318 Val = To;
2319 ++NumUpdated;
2320 }
2321 Values.push_back(Val);
2322 }
2323
2324 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2325 Values, this, From, To, NumUpdated, OperandNo);
2326}
2327
2329 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2330 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2331 return false;
2332
2333 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2334 if (!IntVal)
2335 return false;
2336
2337 return IntVal->getValue() == Value;
2338}
2339
2341 const Value *Discriminator,
2342 const DataLayout &DL) const {
2343 // This function may only be validly called to analyze a ptrauth operation
2344 // with no deactivation symbol, so if we have one it isn't compatible.
2346 return false;
2347
2348 // If the keys are different, there's no chance for this to be compatible.
2349 if (getKey() != Key)
2350 return false;
2351
2352 // We can have 3 kinds of discriminators:
2353 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2354 // - address-only: `i64 0, ptr p` vs. `ptr p`
2355 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2356
2357 // If this constant has a simple discriminator (integer, no address), easy:
2358 // it's compatible iff the provided full discriminator is also a simple
2359 // discriminator, identical to our integer discriminator.
2361 return getDiscriminator() == Discriminator;
2362
2363 // Otherwise, we can isolate address and integer discriminator components.
2364 const Value *AddrDiscriminator = nullptr;
2365
2366 // This constant may or may not have an integer discriminator (instead of 0).
2367 if (!getDiscriminator()->isNullValue()) {
2368 // If it does, there's an implicit blend. We need to have a matching blend
2369 // intrinsic in the provided full discriminator.
2370 if (!match(Discriminator,
2372 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2373 return false;
2374 } else {
2375 // Otherwise, interpret the provided full discriminator as address-only.
2376 AddrDiscriminator = Discriminator;
2377 }
2378
2379 // Either way, we can now focus on comparing the address discriminators.
2380
2381 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2382 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2383 AddrDiscriminator = Cast->getPointerOperand();
2384
2385 // Beyond that, we're only interested in compatible pointers.
2386 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2387 return false;
2388
2389 // These are often the same constant GEP, making them trivially equivalent.
2390 if (getAddrDiscriminator() == AddrDiscriminator)
2391 return true;
2392
2393 // Finally, they may be equivalent base+offset expressions.
2394 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2396 DL, Off1, /*AllowNonInbounds=*/true);
2397
2398 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2399 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2400 DL, Off2, /*AllowNonInbounds=*/true);
2401
2402 return Base1 == Base2 && Off1 == Off2;
2403}
2404
2405//---- ConstantExpr::get() implementations.
2406//
2407
2408/// This is a utility function to handle folding of casts and lookup of the
2409/// cast in the ExprConstants map. It is used by the various get* methods below.
2411 bool OnlyIfReduced = false) {
2412 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2413 // Fold a few common cases
2414 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2415 return FC;
2416
2417 if (OnlyIfReduced)
2418 return nullptr;
2419
2420 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2421
2422 // Look up the constant in the table first to ensure uniqueness.
2424
2425 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2426}
2427
2429 bool OnlyIfReduced) {
2431 assert(Instruction::isCast(opc) && "opcode out of range");
2433 "Cast opcode not supported as constant expression");
2434 assert(C && Ty && "Null arguments to getCast");
2435 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2436
2437 switch (opc) {
2438 default:
2439 llvm_unreachable("Invalid cast opcode");
2440 case Instruction::Trunc:
2441 return getTrunc(C, Ty, OnlyIfReduced);
2442 case Instruction::PtrToAddr:
2443 return getPtrToAddr(C, Ty, OnlyIfReduced);
2444 case Instruction::PtrToInt:
2445 return getPtrToInt(C, Ty, OnlyIfReduced);
2446 case Instruction::IntToPtr:
2447 return getIntToPtr(C, Ty, OnlyIfReduced);
2448 case Instruction::BitCast:
2449 return getBitCast(C, Ty, OnlyIfReduced);
2450 case Instruction::AddrSpaceCast:
2451 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2452 }
2453}
2454
2456 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2457 return getBitCast(C, Ty);
2458 return getTrunc(C, Ty);
2459}
2460
2462 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2463 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2464 "Invalid cast");
2465
2466 if (Ty->isIntOrIntVectorTy())
2467 return getPtrToInt(S, Ty);
2468
2469 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2470 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2471 return getAddrSpaceCast(S, Ty);
2472
2473 return getBitCast(S, Ty);
2474}
2475
2477 Type *Ty) {
2478 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2479 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2480
2481 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2482 return getAddrSpaceCast(S, Ty);
2483
2484 return getBitCast(S, Ty);
2485}
2486
2487Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2488#ifndef NDEBUG
2489 bool fromVec = isa<VectorType>(C->getType());
2490 bool toVec = isa<VectorType>(Ty);
2491#endif
2492 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2493 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2494 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2495 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2496 "SrcTy must be larger than DestTy for Trunc!");
2497
2498 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2499}
2500
2502 bool OnlyIfReduced) {
2503 assert(C->getType()->isPtrOrPtrVectorTy() &&
2504 "PtrToAddr source must be pointer or pointer vector");
2505 assert(DstTy->isIntOrIntVectorTy() &&
2506 "PtrToAddr destination must be integer or integer vector");
2507 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2508 if (isa<VectorType>(C->getType()))
2509 assert(cast<VectorType>(C->getType())->getElementCount() ==
2510 cast<VectorType>(DstTy)->getElementCount() &&
2511 "Invalid cast between a different number of vector elements");
2512 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2513}
2514
2516 bool OnlyIfReduced) {
2517 assert(C->getType()->isPtrOrPtrVectorTy() &&
2518 "PtrToInt source must be pointer or pointer vector");
2519 assert(DstTy->isIntOrIntVectorTy() &&
2520 "PtrToInt destination must be integer or integer vector");
2521 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2522 if (isa<VectorType>(C->getType()))
2523 assert(cast<VectorType>(C->getType())->getElementCount() ==
2524 cast<VectorType>(DstTy)->getElementCount() &&
2525 "Invalid cast between a different number of vector elements");
2526 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2527}
2528
2530 bool OnlyIfReduced) {
2531 assert(C->getType()->isIntOrIntVectorTy() &&
2532 "IntToPtr source must be integer or integer vector");
2533 assert(DstTy->isPtrOrPtrVectorTy() &&
2534 "IntToPtr destination must be a pointer or pointer vector");
2535 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2536 if (isa<VectorType>(C->getType()))
2537 assert(cast<VectorType>(C->getType())->getElementCount() ==
2538 cast<VectorType>(DstTy)->getElementCount() &&
2539 "Invalid cast between a different number of vector elements");
2540 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2541}
2542
2544 bool OnlyIfReduced) {
2545 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2546 "Invalid constantexpr bitcast!");
2547
2548 // It is common to ask for a bitcast of a value to its own type, handle this
2549 // speedily.
2550 if (C->getType() == DstTy) return C;
2551
2552 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2553}
2554
2556 bool OnlyIfReduced) {
2557 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2558 "Invalid constantexpr addrspacecast!");
2559 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2560}
2561
2562Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2563 unsigned Flags, Type *OnlyIfReducedTy) {
2564 // Check the operands for consistency first.
2566 "Invalid opcode in binary constant expression");
2567 assert(isSupportedBinOp(Opcode) &&
2568 "Binop not supported as constant expression");
2569 assert(C1->getType() == C2->getType() &&
2570 "Operand types in binary constant expression should match");
2571
2572#ifndef NDEBUG
2573 switch (Opcode) {
2574 case Instruction::Add:
2575 case Instruction::Sub:
2576 case Instruction::Mul:
2578 "Tried to create an integer operation on a non-integer type!");
2579 break;
2580 case Instruction::And:
2581 case Instruction::Or:
2582 case Instruction::Xor:
2584 "Tried to create a logical operation on a non-integral type!");
2585 break;
2586 default:
2587 break;
2588 }
2589#endif
2590
2591 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2592 return FC;
2593
2594 if (OnlyIfReducedTy == C1->getType())
2595 return nullptr;
2596
2597 Constant *ArgVec[] = {C1, C2};
2598 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2599
2600 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2601 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2602}
2603
2604bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2605 switch (Opcode) {
2606 case Instruction::UDiv:
2607 case Instruction::SDiv:
2608 case Instruction::URem:
2609 case Instruction::SRem:
2610 case Instruction::FAdd:
2611 case Instruction::FSub:
2612 case Instruction::FMul:
2613 case Instruction::FDiv:
2614 case Instruction::FRem:
2615 case Instruction::And:
2616 case Instruction::Or:
2617 case Instruction::LShr:
2618 case Instruction::AShr:
2619 case Instruction::Shl:
2620 case Instruction::Mul:
2621 return false;
2622 case Instruction::Add:
2623 case Instruction::Sub:
2624 case Instruction::Xor:
2625 return true;
2626 default:
2627 llvm_unreachable("Argument must be binop opcode");
2628 }
2629}
2630
2631bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2632 switch (Opcode) {
2633 case Instruction::UDiv:
2634 case Instruction::SDiv:
2635 case Instruction::URem:
2636 case Instruction::SRem:
2637 case Instruction::FAdd:
2638 case Instruction::FSub:
2639 case Instruction::FMul:
2640 case Instruction::FDiv:
2641 case Instruction::FRem:
2642 case Instruction::And:
2643 case Instruction::Or:
2644 case Instruction::LShr:
2645 case Instruction::AShr:
2646 case Instruction::Shl:
2647 case Instruction::Mul:
2648 return false;
2649 case Instruction::Add:
2650 case Instruction::Sub:
2651 case Instruction::Xor:
2652 return true;
2653 default:
2654 llvm_unreachable("Argument must be binop opcode");
2655 }
2656}
2657
2658bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2659 switch (Opcode) {
2660 case Instruction::ZExt:
2661 case Instruction::SExt:
2662 case Instruction::FPTrunc:
2663 case Instruction::FPExt:
2664 case Instruction::UIToFP:
2665 case Instruction::SIToFP:
2666 case Instruction::FPToUI:
2667 case Instruction::FPToSI:
2668 return false;
2669 case Instruction::Trunc:
2670 case Instruction::PtrToAddr:
2671 case Instruction::PtrToInt:
2672 case Instruction::IntToPtr:
2673 case Instruction::BitCast:
2674 case Instruction::AddrSpaceCast:
2675 return true;
2676 default:
2677 llvm_unreachable("Argument must be cast opcode");
2678 }
2679}
2680
2681bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2682 switch (Opcode) {
2683 case Instruction::ZExt:
2684 case Instruction::SExt:
2685 case Instruction::FPTrunc:
2686 case Instruction::FPExt:
2687 case Instruction::UIToFP:
2688 case Instruction::SIToFP:
2689 case Instruction::FPToUI:
2690 case Instruction::FPToSI:
2691 return false;
2692 case Instruction::Trunc:
2693 case Instruction::PtrToAddr:
2694 case Instruction::PtrToInt:
2695 case Instruction::IntToPtr:
2696 case Instruction::BitCast:
2697 case Instruction::AddrSpaceCast:
2698 return true;
2699 default:
2700 llvm_unreachable("Argument must be cast opcode");
2701 }
2702}
2703
2705 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2706 // Note that a non-inbounds gep is used, as null isn't within any object.
2707 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2710 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2711 GEPIdx);
2713 return getPtrToInt(GEP,
2714 Type::getInt64Ty(Ty->getContext()));
2715}
2716
2718 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2719 // Note that a non-inbounds gep is used, as null isn't within any object.
2720 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2721 Constant *NullPtr =
2723 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2724 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2725 Constant *Indices[2] = {Zero, One};
2727 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2729 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2730}
2731
2733 ArrayRef<Value *> Idxs,
2734 GEPNoWrapFlags NW,
2735 std::optional<ConstantRange> InRange,
2736 Type *OnlyIfReducedTy) {
2737 assert(Ty && "Must specify element type");
2738 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2739
2740 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2741 return FC; // Fold a few common cases.
2742
2743 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2744 ;
2745
2746 // Get the result type of the getelementptr!
2748 if (OnlyIfReducedTy == ReqTy)
2749 return nullptr;
2750
2751 auto EltCount = ElementCount::getFixed(0);
2752 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2753 EltCount = VecTy->getElementCount();
2754
2755 // Look up the constant in the table first to ensure uniqueness
2756 std::vector<Constant*> ArgVec;
2757 ArgVec.reserve(1 + Idxs.size());
2758 ArgVec.push_back(C);
2759 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2760 for (; GTI != GTE; ++GTI) {
2761 auto *Idx = cast<Constant>(GTI.getOperand());
2762 assert(
2763 (!isa<VectorType>(Idx->getType()) ||
2764 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2765 "getelementptr index type missmatch");
2766
2767 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2768 Idx = Idx->getSplatValue();
2769 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2770 !Idx->getType()->isVectorTy()) {
2771 Idx = ConstantVector::getSplat(EltCount, Idx);
2772 }
2773 ArgVec.push_back(Idx);
2774 }
2775
2776 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2777 {}, Ty, InRange);
2778
2779 LLVMContextImpl *pImpl = C->getContext().pImpl;
2780 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2781}
2782
2785 GEPNoWrapFlags NW,
2786 std::optional<ConstantRange> InRange,
2787 Type *OnlyIfReducedTy) {
2788 // Handle already canonical GEP.
2789 if (Ty->isIntegerTy(8) && Idxs[0]->getType() == DL.getIndexType(C->getType()))
2790 return getPtrAdd(C, Idxs[0], NW, InRange, OnlyIfReducedTy);
2791
2792 // Some API require an ArrayRef of Value * instead of Constant *.
2793 ArrayRef<Value *> ValIdxs =
2794 ArrayRef((Value *const *)Idxs.data(), Idxs.size());
2795 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2796
2797 if (!isSupportedGetElementPtr(Ty))
2798 return nullptr;
2799
2800 Type *RetTy = GetElementPtrInst::getGEPReturnType(C, ValIdxs);
2801 Type *IdxTy = DL.getIndexType(RetTy);
2802
2804 auto GTI = gep_type_begin(Ty, ValIdxs), GTE = gep_type_end(Ty, ValIdxs);
2805 for (; GTI != GTE; ++GTI) {
2806 auto *Idx = cast<Constant>(GTI.getOperand());
2807 if (Idx->isNullValue())
2808 continue;
2809
2810 if (StructType *STy = GTI.getStructTypeOrNull()) {
2811 uint64_t OpValue = Idx->getUniqueInteger().getZExtValue();
2812 uint64_t Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
2813 if (!Size)
2814 continue;
2815
2816 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset,
2817 ConstantInt::get(IdxTy, Size));
2818 if (!Offset)
2819 return nullptr;
2820
2821 continue;
2822 }
2823
2824 // Splat the index if needed.
2825 if (IdxTy->isVectorTy() && !Idx->getType()->isVectorTy())
2826 Idx = ConstantVector::getSplat(cast<VectorType>(IdxTy)->getElementCount(),
2827 Idx);
2828
2829 // Convert to correct type.
2830 if (Idx->getType() != IdxTy) {
2831 Idx = ConstantFoldCastInstruction(Idx->getType()->getScalarSizeInBits() <
2832 IdxTy->getScalarSizeInBits()
2833 ? Instruction::SExt
2834 : Instruction::Trunc,
2835 Idx, IdxTy);
2836 if (!Idx)
2837 return nullptr;
2838 }
2839
2840 TypeSize TySize = GTI.getSequentialElementStride(DL);
2841 if (TySize.isScalable())
2842 return nullptr;
2843
2844 // Multiply by scale.
2845 if (TySize != TypeSize::getFixed(1)) {
2846 Constant *Scale = ConstantInt::getSigned(IdxTy, TySize.getFixedValue(),
2847 /*ImplicitTrunc=*/true);
2848 Idx = ConstantFoldBinaryInstruction(Instruction::Mul, Idx, Scale);
2849 if (!Idx)
2850 return nullptr;
2851 }
2852
2853 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset, Idx);
2854 if (!Offset)
2855 return nullptr;
2856 }
2857
2858 return getPtrAdd(C, Offset, NW, InRange, OnlyIfReducedTy);
2859}
2860
2862 Type *OnlyIfReducedTy) {
2863 assert(Val->getType()->isVectorTy() &&
2864 "Tried to create extractelement operation on non-vector type!");
2865 assert(Idx->getType()->isIntegerTy() &&
2866 "Extractelement index must be an integer type!");
2867
2869 return FC; // Fold a few common cases.
2870
2871 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2872 if (OnlyIfReducedTy == ReqTy)
2873 return nullptr;
2874
2875 // Look up the constant in the table first to ensure uniqueness
2876 Constant *ArgVec[] = { Val, Idx };
2877 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2878
2879 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2880 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2881}
2882
2884 Constant *Idx, Type *OnlyIfReducedTy) {
2885 assert(Val->getType()->isVectorTy() &&
2886 "Tried to create insertelement operation on non-vector type!");
2887 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2888 "Insertelement types must match!");
2889 assert(Idx->getType()->isIntegerTy() &&
2890 "Insertelement index must be i32 type!");
2891
2892 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2893 return FC; // Fold a few common cases.
2894
2895 if (OnlyIfReducedTy == Val->getType())
2896 return nullptr;
2897
2898 // Look up the constant in the table first to ensure uniqueness
2899 Constant *ArgVec[] = { Val, Elt, Idx };
2900 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2901
2902 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2903 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2904}
2905
2907 ArrayRef<int> Mask,
2908 Type *OnlyIfReducedTy) {
2910 "Invalid shuffle vector constant expr operands!");
2911
2913 return FC; // Fold a few common cases.
2914
2915 unsigned NElts = Mask.size();
2916 auto V1VTy = cast<VectorType>(V1->getType());
2917 Type *EltTy = V1VTy->getElementType();
2918 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2919 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2920
2921 if (OnlyIfReducedTy == ShufTy)
2922 return nullptr;
2923
2924 // Look up the constant in the table first to ensure uniqueness
2925 Constant *ArgVec[] = {V1, V2};
2926 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2927
2928 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2929 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2930}
2931
2933 assert(C->getType()->isIntOrIntVectorTy() &&
2934 "Cannot NEG a nonintegral value!");
2935 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2936}
2937
2939 assert(C->getType()->isIntOrIntVectorTy() &&
2940 "Cannot NOT a nonintegral value!");
2941 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2942}
2943
2945 bool HasNUW, bool HasNSW) {
2946 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2948 return get(Instruction::Add, C1, C2, Flags);
2949}
2950
2952 bool HasNUW, bool HasNSW) {
2953 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2955 return get(Instruction::Sub, C1, C2, Flags);
2956}
2957
2959 return get(Instruction::Xor, C1, C2);
2960}
2961
2963 Type *Ty = C->getType();
2964 const APInt *IVal;
2965 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2966 return ConstantInt::get(Ty, IVal->logBase2());
2967
2968 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2969 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2970 if (!VecTy)
2971 return nullptr;
2972
2974 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2975 Constant *Elt = C->getAggregateElement(I);
2976 if (!Elt)
2977 return nullptr;
2978 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2979 if (isa<UndefValue>(Elt)) {
2980 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2981 continue;
2982 }
2983 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2984 return nullptr;
2985 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2986 }
2987
2988 return ConstantVector::get(Elts);
2989}
2990
2992 bool AllowRHSConstant, bool NSZ) {
2993 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2994
2995 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2996 if (Instruction::isCommutative(Opcode)) {
2997 switch (Opcode) {
2998 case Instruction::Add: // X + 0 = X
2999 case Instruction::Or: // X | 0 = X
3000 case Instruction::Xor: // X ^ 0 = X
3001 return Constant::getNullValue(Ty);
3002 case Instruction::Mul: // X * 1 = X
3003 return ConstantInt::get(Ty, 1);
3004 case Instruction::And: // X & -1 = X
3005 return Constant::getAllOnesValue(Ty);
3006 case Instruction::FAdd: // X + -0.0 = X
3007 return ConstantFP::getZero(Ty, !NSZ);
3008 case Instruction::FMul: // X * 1.0 = X
3009 return ConstantFP::get(Ty, 1.0);
3010 default:
3011 llvm_unreachable("Every commutative binop has an identity constant");
3012 }
3013 }
3014
3015 // Non-commutative opcodes: AllowRHSConstant must be set.
3016 if (!AllowRHSConstant)
3017 return nullptr;
3018
3019 switch (Opcode) {
3020 case Instruction::Sub: // X - 0 = X
3021 case Instruction::Shl: // X << 0 = X
3022 case Instruction::LShr: // X >>u 0 = X
3023 case Instruction::AShr: // X >> 0 = X
3024 case Instruction::FSub: // X - 0.0 = X
3025 return Constant::getNullValue(Ty);
3026 case Instruction::SDiv: // X / 1 = X
3027 case Instruction::UDiv: // X /u 1 = X
3028 return ConstantInt::get(Ty, 1);
3029 case Instruction::FDiv: // X / 1.0 = X
3030 return ConstantFP::get(Ty, 1.0);
3031 default:
3032 return nullptr;
3033 }
3034}
3035
3037 switch (ID) {
3038 case Intrinsic::umax:
3039 return Constant::getNullValue(Ty);
3040 case Intrinsic::umin:
3041 return Constant::getAllOnesValue(Ty);
3042 case Intrinsic::smax:
3044 Ty, APInt::getSignedMinValue(Ty->getScalarSizeInBits()));
3045 case Intrinsic::smin:
3047 Ty, APInt::getSignedMaxValue(Ty->getScalarSizeInBits()));
3048 default:
3049 return nullptr;
3050 }
3051}
3052
3054 bool AllowRHSConstant, bool NSZ) {
3055 if (I->isBinaryOp())
3056 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
3058 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
3059 return nullptr;
3060}
3061
3063 bool AllowLHSConstant) {
3064 switch (Opcode) {
3065 default:
3066 break;
3067
3068 case Instruction::Or: // -1 | X = -1
3069 return Constant::getAllOnesValue(Ty);
3070
3071 case Instruction::And: // 0 & X = 0
3072 case Instruction::Mul: // 0 * X = 0
3073 return Constant::getNullValue(Ty);
3074 }
3075
3076 // AllowLHSConstant must be set.
3077 if (!AllowLHSConstant)
3078 return nullptr;
3079
3080 switch (Opcode) {
3081 default:
3082 return nullptr;
3083 case Instruction::Shl: // 0 << X = 0
3084 case Instruction::LShr: // 0 >>l X = 0
3085 case Instruction::AShr: // 0 >>a X = 0
3086 case Instruction::SDiv: // 0 /s X = 0
3087 case Instruction::UDiv: // 0 /u X = 0
3088 case Instruction::URem: // 0 %u X = 0
3089 case Instruction::SRem: // 0 %s X = 0
3090 return Constant::getNullValue(Ty);
3091 }
3092}
3093
3094/// Remove the constant from the constant table.
3095void ConstantExpr::destroyConstantImpl() {
3096 getType()->getContext().pImpl->ExprConstants.remove(this);
3097}
3098
3099const char *ConstantExpr::getOpcodeName() const {
3101}
3102
3103GetElementPtrConstantExpr::GetElementPtrConstantExpr(
3104 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
3105 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
3106 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
3107 SrcElementTy(SrcElementTy),
3108 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
3109 InRange(std::move(InRange)) {
3110 Op<0>() = C;
3111 Use *OperandList = getOperandList();
3112 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
3113 OperandList[i+1] = IdxList[i];
3114}
3115
3117 return SrcElementTy;
3118}
3119
3121 return ResElementTy;
3122}
3123
3124std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
3125 return InRange;
3126}
3127
3128//===----------------------------------------------------------------------===//
3129// ConstantData* implementations
3130
3133 return ATy->getElementType();
3134 return cast<VectorType>(getType())->getElementType();
3135}
3136
3140
3142 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
3143 return true;
3144 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
3145 switch (IT->getBitWidth()) {
3146 case 8:
3147 case 16:
3148 case 32:
3149 case 64:
3150 return true;
3151 default: break;
3152 }
3153 }
3154 if (auto *IT = dyn_cast<ByteType>(Ty)) {
3155 switch (IT->getBitWidth()) {
3156 case 8:
3157 case 16:
3158 case 32:
3159 case 64:
3160 return true;
3161 default:
3162 break;
3163 }
3164 }
3165 return false;
3166}
3167
3170 return AT->getNumElements();
3171 return cast<FixedVectorType>(getType())->getNumElements();
3172}
3173
3177
3178/// Return the start of the specified element.
3179const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
3180 assert(Elt < getNumElements() && "Invalid Elt");
3181 return DataElements + Elt * getElementByteSize();
3182}
3183
3184/// Return true if the array is empty or all zeros.
3185static bool isAllZeros(StringRef Arr) {
3186 for (char I : Arr)
3187 if (I != 0)
3188 return false;
3189 return true;
3190}
3191
3192/// This is the underlying implementation of all of the
3193/// ConstantDataSequential::get methods. They all thunk down to here, providing
3194/// the correct element type. We take the bytes in as a StringRef because
3195/// we *want* an underlying "char*" to avoid TBAA type punning violations.
3197#ifndef NDEBUG
3198 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
3199 assert(isElementTypeCompatible(ATy->getElementType()));
3200 else
3202#endif
3203 // If the elements are all zero or there are no elements, return a CAZ, which
3204 // is more dense and canonical.
3205 if (isAllZeros(Elements))
3206 return ConstantAggregateZero::get(Ty);
3207
3208 // Do a lookup to see if we have already formed one of these.
3209 auto &Slot =
3210 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
3211
3212 // The bucket can point to a linked list of different CDS's that have the same
3213 // body but different types. For example, 0,0,0,1 could be a 4 element array
3214 // of i8, or a 1-element array of i32. They'll both end up in the same
3215 /// StringMap bucket, linked up by their Next pointers. Walk the list.
3216 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3217 for (; *Entry; Entry = &(*Entry)->Next)
3218 if ((*Entry)->getType() == Ty)
3219 return Entry->get();
3220
3221 // Okay, we didn't get a hit. Create a node of the right class, link it in,
3222 // and return it.
3223 if (isa<ArrayType>(Ty)) {
3224 // Use reset because std::make_unique can't access the constructor.
3225 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3226 return Entry->get();
3227 }
3228
3230 // Use reset because std::make_unique can't access the constructor.
3231 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3232 return Entry->get();
3233}
3234
3235void ConstantDataSequential::destroyConstantImpl() {
3236 // Remove the constant from the StringMap.
3239
3240 auto Slot = CDSConstants.find(getRawDataValues());
3241
3242 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3243
3244 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3245
3246 // Remove the entry from the hash table.
3247 if (!(*Entry)->Next) {
3248 // If there is only one value in the bucket (common case) it must be this
3249 // entry, and removing the entry should remove the bucket completely.
3250 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3251 getContext().pImpl->CDSConstants.erase(Slot);
3252 return;
3253 }
3254
3255 // Otherwise, there are multiple entries linked off the bucket, unlink the
3256 // node we care about but keep the bucket around.
3257 while (true) {
3258 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3259 assert(Node && "Didn't find entry in its uniquing hash table!");
3260 // If we found our entry, unlink it from the list and we're done.
3261 if (Node.get() == this) {
3262 Node = std::move(Node->Next);
3263 return;
3264 }
3265
3266 Entry = &Node->Next;
3267 }
3268}
3269
3270/// getFP() constructors - Return a constant of array type with a float
3271/// element type taken from argument `ElementType', and count taken from
3272/// argument `Elts'. The amount of bits of the contained type must match the
3273/// number of bits of the type contained in the passed in ArrayRef.
3274/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3275/// that this can return a ConstantAggregateZero object.
3277 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3278 "Element type is not a 16-bit float type");
3279 Type *Ty = ArrayType::get(ElementType, Elts.size());
3280 const char *Data = reinterpret_cast<const char *>(Elts.data());
3281 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3282}
3284 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3285 Type *Ty = ArrayType::get(ElementType, Elts.size());
3286 const char *Data = reinterpret_cast<const char *>(Elts.data());
3287 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3288}
3290 assert(ElementType->isDoubleTy() &&
3291 "Element type is not a 64-bit float type");
3292 Type *Ty = ArrayType::get(ElementType, Elts.size());
3293 const char *Data = reinterpret_cast<const char *>(Elts.data());
3294 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3295}
3296
3297/// getByte() constructors - Return a constant of array type with a byte
3298/// element type taken from argument `ElementType', and count taken from
3299/// argument `Elts'. The amount of bits of the contained type must match the
3300/// number of bits of the type contained in the passed in ArrayRef.
3301/// Note that this can return a ConstantAggregateZero object.
3303 ArrayRef<uint8_t> Elts) {
3304 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte type");
3305 Type *Ty = ArrayType::get(ElementType, Elts.size());
3306 const char *Data = reinterpret_cast<const char *>(Elts.data());
3307 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3308}
3310 ArrayRef<uint16_t> Elts) {
3311 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte type");
3312 Type *Ty = ArrayType::get(ElementType, Elts.size());
3313 const char *Data = reinterpret_cast<const char *>(Elts.data());
3314 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3315}
3317 ArrayRef<uint32_t> Elts) {
3318 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte type");
3319 Type *Ty = ArrayType::get(ElementType, Elts.size());
3320 const char *Data = reinterpret_cast<const char *>(Elts.data());
3321 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3322}
3324 ArrayRef<uint64_t> Elts) {
3325 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte type");
3326 Type *Ty = ArrayType::get(ElementType, Elts.size());
3327 const char *Data = reinterpret_cast<const char *>(Elts.data());
3328 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3329}
3330
3332 bool AddNull, bool ByteString) {
3333 if (!AddNull) {
3334 const uint8_t *Data = Str.bytes_begin();
3335 return ByteString
3336 ? getByte(Type::getByte8Ty(Context), ArrayRef(Data, Str.size()))
3337 : get(Context, ArrayRef(Data, Str.size()));
3338 }
3339
3340 SmallVector<uint8_t, 64> ElementVals;
3341 ElementVals.append(Str.begin(), Str.end());
3342 ElementVals.push_back(0);
3343 return ByteString ? getByte(Type::getByte8Ty(Context), ElementVals)
3344 : get(Context, ElementVals);
3345}
3346
3347/// get() constructors - Return a constant with vector type with an element
3348/// count and element type matching the ArrayRef passed in. Note that this
3349/// can return a ConstantAggregateZero object.
3351 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3352 const char *Data = reinterpret_cast<const char *>(Elts.data());
3353 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3354}
3356 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3357 const char *Data = reinterpret_cast<const char *>(Elts.data());
3358 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3359}
3361 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3362 const char *Data = reinterpret_cast<const char *>(Elts.data());
3363 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3364}
3366 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3367 const char *Data = reinterpret_cast<const char *>(Elts.data());
3368 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3369}
3371 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3372 const char *Data = reinterpret_cast<const char *>(Elts.data());
3373 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3374}
3376 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3377 const char *Data = reinterpret_cast<const char *>(Elts.data());
3378 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3379}
3380
3381/// getByte() constructors - Return a constant of vector type with a byte
3382/// element type taken from argument `ElementType', and count taken from
3383/// argument `Elts'. The amount of bits of the contained type must match the
3384/// number of bits of the type contained in the passed in ArrayRef.
3385/// Note that this can return a ConstantAggregateZero object.
3387 ArrayRef<uint8_t> Elts) {
3388 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte");
3389 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3390 const char *Data = reinterpret_cast<const char *>(Elts.data());
3391 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3392}
3394 ArrayRef<uint16_t> Elts) {
3395 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte");
3396 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3397 const char *Data = reinterpret_cast<const char *>(Elts.data());
3398 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3399}
3401 ArrayRef<uint32_t> Elts) {
3402 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte");
3403 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3404 const char *Data = reinterpret_cast<const char *>(Elts.data());
3405 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3406}
3408 ArrayRef<uint64_t> Elts) {
3409 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte");
3410 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3411 const char *Data = reinterpret_cast<const char *>(Elts.data());
3412 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3413}
3414
3415/// getFP() constructors - Return a constant of vector type with a float
3416/// element type taken from argument `ElementType', and count taken from
3417/// argument `Elts'. The amount of bits of the contained type must match the
3418/// number of bits of the type contained in the passed in ArrayRef.
3419/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3420/// that this can return a ConstantAggregateZero object.
3422 ArrayRef<uint16_t> Elts) {
3423 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3424 "Element type is not a 16-bit float type");
3425 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3426 const char *Data = reinterpret_cast<const char *>(Elts.data());
3427 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3428}
3430 ArrayRef<uint32_t> Elts) {
3431 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3432 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3433 const char *Data = reinterpret_cast<const char *>(Elts.data());
3434 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3435}
3437 ArrayRef<uint64_t> Elts) {
3438 assert(ElementType->isDoubleTy() &&
3439 "Element type is not a 64-bit float type");
3440 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3441 const char *Data = reinterpret_cast<const char *>(Elts.data());
3442 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3443}
3444
3446 assert(isElementTypeCompatible(V->getType()) &&
3447 "Element type not compatible with ConstantData");
3448 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3449 if (CI->getType()->isIntegerTy(8)) {
3450 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3451 return get(V->getContext(), Elts);
3452 }
3453 if (CI->getType()->isIntegerTy(16)) {
3454 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3455 return get(V->getContext(), Elts);
3456 }
3457 if (CI->getType()->isIntegerTy(32)) {
3458 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3459 return get(V->getContext(), Elts);
3460 }
3461 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3462 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3463 return get(V->getContext(), Elts);
3464 }
3465
3466 if (ConstantByte *CB = dyn_cast<ConstantByte>(V)) {
3467 if (CB->getType()->isByteTy(8)) {
3468 SmallVector<uint8_t, 16> Elts(NumElts, CB->getZExtValue());
3469 return getByte(V->getType(), Elts);
3470 }
3471 if (CB->getType()->isByteTy(16)) {
3472 SmallVector<uint16_t, 16> Elts(NumElts, CB->getZExtValue());
3473 return getByte(V->getType(), Elts);
3474 }
3475 if (CB->getType()->isByteTy(32)) {
3476 SmallVector<uint32_t, 16> Elts(NumElts, CB->getZExtValue());
3477 return getByte(V->getType(), Elts);
3478 }
3479 assert(CB->getType()->isByteTy(64) && "Unsupported ConstantData type");
3480 SmallVector<uint64_t, 16> Elts(NumElts, CB->getZExtValue());
3481 return getByte(V->getType(), Elts);
3482 }
3483
3484 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3485 if (CFP->getType()->isHalfTy()) {
3487 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3488 return getFP(V->getType(), Elts);
3489 }
3490 if (CFP->getType()->isBFloatTy()) {
3492 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3493 return getFP(V->getType(), Elts);
3494 }
3495 if (CFP->getType()->isFloatTy()) {
3497 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3498 return getFP(V->getType(), Elts);
3499 }
3500 if (CFP->getType()->isDoubleTy()) {
3502 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3503 return getFP(V->getType(), Elts);
3504 }
3505 }
3507}
3508
3510 assert(
3512 "Accessor can only be used when element is an integer or byte");
3513 const char *EltPtr = getElementPointer(Elt);
3514
3515 // The data is stored in host byte order, make sure to cast back to the right
3516 // type to load with the right endianness.
3517 switch (getElementByteSize()) {
3518 default: llvm_unreachable("Invalid bitwidth for CDS");
3519 case 1:
3520 return *reinterpret_cast<const uint8_t *>(EltPtr);
3521 case 2:
3522 return *reinterpret_cast<const uint16_t *>(EltPtr);
3523 case 4:
3524 return *reinterpret_cast<const uint32_t *>(EltPtr);
3525 case 8:
3526 return *reinterpret_cast<const uint64_t *>(EltPtr);
3527 }
3528}
3529
3531 assert(
3533 "Accessor can only be used when element is an integer or byte");
3534 const char *EltPtr = getElementPointer(Elt);
3535
3536 // The data is stored in host byte order, make sure to cast back to the right
3537 // type to load with the right endianness.
3538 switch (getElementByteSize()) {
3539 default: llvm_unreachable("Invalid bitwidth for CDS");
3540 case 1: {
3541 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3542 return APInt(8, EltVal);
3543 }
3544 case 2: {
3545 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3546 return APInt(16, EltVal);
3547 }
3548 case 4: {
3549 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3550 return APInt(32, EltVal);
3551 }
3552 case 8: {
3553 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3554 return APInt(64, EltVal);
3555 }
3556 }
3557}
3558
3560 const char *EltPtr = getElementPointer(Elt);
3561
3562 switch (getElementType()->getTypeID()) {
3563 default:
3564 llvm_unreachable("Accessor can only be used when element is float/double!");
3565 case Type::HalfTyID: {
3566 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3567 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3568 }
3569 case Type::BFloatTyID: {
3570 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3571 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3572 }
3573 case Type::FloatTyID: {
3574 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3575 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3576 }
3577 case Type::DoubleTyID: {
3578 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3579 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3580 }
3581 }
3582}
3583
3585 assert(getElementType()->isFloatTy() &&
3586 "Accessor can only be used when element is a 'float'");
3587 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3588}
3589
3591 assert(getElementType()->isDoubleTy() &&
3592 "Accessor can only be used when element is a 'float'");
3593 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3594}
3595
3597 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3598 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3599 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3600
3601 if (getElementType()->isByteTy())
3602 return ConstantByte::get(getElementType(), getElementAsInteger(Elt));
3603
3604 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3605}
3606
3607bool ConstantDataSequential::isString(unsigned CharSize) const {
3608 return isa<ArrayType>(getType()) &&
3609 (getElementType()->isIntegerTy(CharSize) ||
3610 getElementType()->isByteTy(CharSize));
3611}
3612
3614 if (!isString())
3615 return false;
3616
3617 StringRef Str = getAsString();
3618
3619 // The last value must be nul.
3620 if (Str.back() != 0) return false;
3621
3622 // Other elements must be non-nul.
3623 return !Str.drop_back().contains(0);
3624}
3625
3626bool ConstantDataVector::isSplatData() const {
3627 const char *Base = getRawDataValues().data();
3628
3629 // Compare elements 1+ to the 0'th element.
3630 unsigned EltSize = getElementByteSize();
3631 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3632 if (memcmp(Base, Base+i*EltSize, EltSize))
3633 return false;
3634
3635 return true;
3636}
3637
3639 if (!IsSplatSet) {
3640 IsSplatSet = true;
3641 IsSplat = isSplatData();
3642 }
3643 return IsSplat;
3644}
3645
3647 // If they're all the same, return the 0th one as a representative.
3648 return isSplat() ? getElementAsConstant(0) : nullptr;
3649}
3650
3651//===----------------------------------------------------------------------===//
3652// handleOperandChange implementations
3653
3654/// Update this constant array to change uses of
3655/// 'From' to be uses of 'To'. This must update the uniquing data structures
3656/// etc.
3657///
3658/// Note that we intentionally replace all uses of From with To here. Consider
3659/// a large array that uses 'From' 1000 times. By handling this case all here,
3660/// ConstantArray::handleOperandChange is only invoked once, and that
3661/// single invocation handles all 1000 uses. Handling them one at a time would
3662/// work, but would be really slow because it would have to unique each updated
3663/// array instance.
3664///
3666 Value *Replacement = nullptr;
3667 switch (getValueID()) {
3668 default:
3669 llvm_unreachable("Not a constant!");
3670#define HANDLE_CONSTANT(Name) \
3671 case Value::Name##Val: \
3672 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3673 break;
3674#include "llvm/IR/Value.def"
3675 }
3676
3677 // If handleOperandChangeImpl returned nullptr, then it handled
3678 // replacing itself and we don't want to delete or replace anything else here.
3679 if (!Replacement)
3680 return;
3681
3682 // I do need to replace this with an existing value.
3683 assert(Replacement != this && "I didn't contain From!");
3684
3685 // Everyone using this now uses the replacement.
3686 replaceAllUsesWith(Replacement);
3687
3688 // Delete the old constant!
3690}
3691
3692Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3693 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3694 Constant *ToC = cast<Constant>(To);
3695
3697 Values.reserve(getNumOperands()); // Build replacement array.
3698
3699 // Fill values with the modified operands of the constant array. Also,
3700 // compute whether this turns into an all-zeros array.
3701 unsigned NumUpdated = 0;
3702
3703 // Keep track of whether all the values in the array are "ToC".
3704 bool AllSame = true;
3705 Use *OperandList = getOperandList();
3706 unsigned OperandNo = 0;
3707 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3708 Constant *Val = cast<Constant>(O->get());
3709 if (Val == From) {
3710 OperandNo = (O - OperandList);
3711 Val = ToC;
3712 ++NumUpdated;
3713 }
3714 Values.push_back(Val);
3715 AllSame &= Val == ToC;
3716 }
3717
3718 if (AllSame && ToC->isNullValue())
3720
3721 if (AllSame && isa<UndefValue>(ToC))
3722 return UndefValue::get(getType());
3723
3724 // Check for any other type of constant-folding.
3725 if (Constant *C = getImpl(getType(), Values))
3726 return C;
3727
3728 // Update to the new value.
3730 Values, this, From, ToC, NumUpdated, OperandNo);
3731}
3732
3733Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3734 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3735 Constant *ToC = cast<Constant>(To);
3736
3737 Use *OperandList = getOperandList();
3738
3740 Values.reserve(getNumOperands()); // Build replacement struct.
3741
3742 // Fill values with the modified operands of the constant struct. Also,
3743 // compute whether this turns into an all-zeros struct.
3744 unsigned NumUpdated = 0;
3745 bool AllSame = true;
3746 unsigned OperandNo = 0;
3747 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3748 Constant *Val = cast<Constant>(O->get());
3749 if (Val == From) {
3750 OperandNo = (O - OperandList);
3751 Val = ToC;
3752 ++NumUpdated;
3753 }
3754 Values.push_back(Val);
3755 AllSame &= Val == ToC;
3756 }
3757
3758 if (AllSame && ToC->isNullValue())
3760
3761 if (AllSame && isa<UndefValue>(ToC))
3762 return UndefValue::get(getType());
3763
3764 // Update to the new value.
3766 Values, this, From, ToC, NumUpdated, OperandNo);
3767}
3768
3769Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3770 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3771 Constant *ToC = cast<Constant>(To);
3772
3774 Values.reserve(getNumOperands()); // Build replacement array...
3775 unsigned NumUpdated = 0;
3776 unsigned OperandNo = 0;
3777 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3778 Constant *Val = getOperand(i);
3779 if (Val == From) {
3780 OperandNo = i;
3781 ++NumUpdated;
3782 Val = ToC;
3783 }
3784 Values.push_back(Val);
3785 }
3786
3787 if (Constant *C = getImpl(Values))
3788 return C;
3789
3790 // Update to the new value.
3792 Values, this, From, ToC, NumUpdated, OperandNo);
3793}
3794
3795Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3796 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3797 Constant *To = cast<Constant>(ToV);
3798
3800 unsigned NumUpdated = 0;
3801 unsigned OperandNo = 0;
3802 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3803 Constant *Op = getOperand(i);
3804 if (Op == From) {
3805 OperandNo = i;
3806 ++NumUpdated;
3807 Op = To;
3808 }
3809 NewOps.push_back(Op);
3810 }
3811 assert(NumUpdated && "I didn't contain From!");
3812
3813 if (Constant *C = getWithOperands(NewOps, getType(), true))
3814 return C;
3815
3816 // Update to the new value.
3817 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3818 NewOps, this, From, To, NumUpdated, OperandNo);
3819}
3820
3822 SmallVector<Value *, 4> ValueOperands(operands());
3823 ArrayRef<Value*> Ops(ValueOperands);
3824
3825 switch (getOpcode()) {
3826 case Instruction::Trunc:
3827 case Instruction::PtrToAddr:
3828 case Instruction::PtrToInt:
3829 case Instruction::IntToPtr:
3830 case Instruction::BitCast:
3831 case Instruction::AddrSpaceCast:
3833 getType(), "");
3834 case Instruction::InsertElement:
3835 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3836 case Instruction::ExtractElement:
3837 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3838 case Instruction::ShuffleVector:
3839 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3840
3841 case Instruction::GetElementPtr: {
3842 const auto *GO = cast<GEPOperator>(this);
3843 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3844 Ops.slice(1), GO->getNoWrapFlags(), "");
3845 }
3846 default:
3847 assert(getNumOperands() == 2 && "Must be binary operator?");
3849 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3855 }
3858 return BO;
3859 }
3860}
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:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
#define T
uint64_t IntrinsicInst * II
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:307
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:310
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1232
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6045
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6071
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned logBase2() const
Definition APInt.h:1781
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h: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:368
CastConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to implement...
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
All zero aggregate value.
Definition Constants.h:514
LLVM_ABI ElementCount getElementCount() const
Return the number of elements in the array, vector, or struct.
LLVM_ABI Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
LLVM_ABI Constant * getElementValue(Constant *C) const
Return a zero of the right value for the specified GEP index if we can, otherwise return null (e....
LLVM_ABI Constant * getStructElement(unsigned Elt) const
If this CAZ has struct type, return a zero with the right element type for the specified element.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
Base class for aggregate constants (with operands).
Definition Constants.h:565
LLVM_ABI ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V, AllocInfo AllocInfo)
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:592
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:609
Class for constant bytes.
Definition Constants.h:281
friend class Constant
Definition Constants.h:282
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of array type with a byte element type taken from argument...
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
LLVM_ABI Constant * getElementAsConstant(uint64_t i) const
Return a Constant for a specified index's element.
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI float getElementAsFloat(uint64_t i) const
If this is an sequential container of floats, return the specified element as a float.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers or bytes.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI APInt getElementAsAPInt(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element as an APInt...
static LLVM_ABI Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
LLVM_ABI double getElementAsDouble(uint64_t i) const
If this is an sequential container of doubles, return the specified element as a double.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
LLVM_ABI bool isCString() const
This method returns true if the array "isString", ends with a null byte, and does not contains any ot...
LLVM_ABI StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
LLVM_ABI Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value,...
static LLVM_ABI Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
LLVM_ABI bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value.
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of vector type with a byte element type taken from argumen...
Base class for constants with no operands.
Definition Constants.h:56
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
ConstantExpr(Type *ty, unsigned Opcode, AllocInfo AllocInfo)
Definition Constants.h:1324
static LLVM_ABI Constant * getAlignOf(Type *Ty)
getAlignOf constant expr - computes the alignment of a type in a target independent way (Note: the re...
friend struct ConstantExprKeyType
Definition Constants.h:1317
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getTruncOrBitCast(Constant *C, Type *Ty)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
LLVM_ABI bool isCast() const
Return true if this is a convert constant expression.
static LLVM_ABI Constant * getIdentity(Instruction *I, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary or intrinsic Instruction.
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
LLVM_ABI Constant * getShuffleMaskForBitcode() const
Assert that this is a shufflevector and return the mask.
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
friend class Constant
Definition Constants.h:1318
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h: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:843
Represents flags for the getelementptr instruction/expression.
unsigned getRaw() const
GetElementPtrConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
std::optional< ConstantRange > getInRange() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static Type * getGEPReturnType(Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
PointerType * getType() const
Global values are always pointers.
InsertElementConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool isCast() const
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
const char * getOpcodeName() const
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A wrapper class for inspecting calls to intrinsic functions.
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< Type *, std::unique_ptr< ConstantPointerNull > > CPNConstants
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
DenseMap< Type *, std::unique_ptr< PoisonValue > > PVConstants
DenseMap< APInt, std::unique_ptr< ConstantInt > > IntConstants
std::unique_ptr< ConstantTokenNone > TheNoneToken
VectorConstantsTy VectorConstants
DenseMap< const GlobalValue *, NoCFIValue * > NoCFIValues
DenseMap< const BasicBlock *, BlockAddress * > BlockAddresses
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
StringMap< std::unique_ptr< ConstantDataSequential > > CDSConstants
StructConstantsTy StructConstants
ConstantUniqueMap< ConstantPtrAuth > ConstantPtrAuths
DenseMap< TargetExtType *, std::unique_ptr< ConstantTargetNone > > CTNConstants
ConstantUniqueMap< ConstantExpr > ExprConstants
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteOneConstants
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteZeroConstants
DenseMap< APInt, std::unique_ptr< ConstantByte > > ByteConstants
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h: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:340
ShuffleVectorConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
Class to represent target extensions types, which are generally unintrospectable from target-independ...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:348
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ TargetExtTyID
Target extension type.
Definition Type.h:80
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ TokenTyID
Tokens.
Definition Type.h:68
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:115
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:298
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI ByteType * getByte8Ty(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:277
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:276
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
'undef' values are things that do not have specified contents.
Definition Constants.h: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:50
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:720
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h: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:708
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:267
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
#define NC
Definition regutils.h:42
Summary of memprof metadata on allocations.
Information about how a User object was allocated, to be passed into the User constructor.
Definition User.h:79